apache-log4cxx-1.1.0/patch000644 001750 001750 00000001617 14354132262 016205 0ustar00robertrobert000000 000000 diff --git a/CMakeLists.txt b/CMakeLists.txt index e89881dc..5722524d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,8 +30,8 @@ set(LOG4CXX_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") # 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(LIBLOG4CXX_LIB_VERSION ${log4cxx_VERSION_MAJOR}.${log4cxx_VERSION_MINOR}.${log4cxx_VERSION_PATCH}.${log4cxx_VERSION_TWEAK}) -set(LIBLOG4CXX_LIB_SOVERSION 15.0.0) +set(LIBLOG4CXX_LIB_VERSION 15.${log4cxx_VERSION_MINOR}.${log4cxx_VERSION_PATCH}) +set(LIBLOG4CXX_LIB_SOVERSION 15.${log4cxx_VERSION_MINOR}.${log4cxx_VERSION_PATCH}) # Set the 'release' version. This is the human-readable version set(LOG4CXX_RELEASE_VERSION ${log4cxx_VERSION_MAJOR}.${log4cxx_VERSION_MINOR}.${log4cxx_VERSION_PATCH}) apache-log4cxx-1.1.0/liblog4cxx.pc.in000644 001750 001750 00000002005 14353331212 020156 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 Description: log4cxx C++ logging framework Version: @VERSION@ Libs: -L${libdir} -llog4cxx Cflags: -I${includedir} Requires.private: apr-1 apr-util-1 apache-log4cxx-1.1.0/LICENSE000644 001750 001750 00000026136 14353331212 016166 0ustar00robertrobert000000 000000 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.1.0/liblog4cxx-qt.pc.in000644 001750 001750 00000002006 14353331212 020601 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 Description: log4cxx C++ logging framework(Qt support) Version: @VERSION@ Libs: -L${libdir} -llog4cxx-qt Cflags: -I${includedir} Requires: liblog4cxx apache-log4cxx-1.1.0/INSTALL000644 001750 001750 00000001737 14353331212 016212 0ustar00robertrobert000000 000000 Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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.1.0/.github/000755 001750 001750 00000000000 14424433605 016521 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/.github/workflows/000755 001750 001750 00000000000 14424433605 020556 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/.github/workflows/abi-compatibility.yml000644 001750 001750 00000003651 14353331212 024700 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: abi-compatibility on: [push, pull_request] #on: # push: # branches: # - master # pull_request: # branches: # - master jobs: job: name: abi-check runs-on: ubuntu-20.04 timeout-minutes: 38 strategy: fail-fast: false steps: - uses: actions/checkout@v2 with: path: main - name: 'Configure Dependencies - Ubuntu' run: | sudo apt-get update sudo apt-get install -y libapr1-dev libaprutil1-dev elfutils vtable-dumper universal-ctags # note: sqlext.h exists on github VM, purge for now as we don't link correctly... sudo apt-get purge unixodbc-dev - name: 'run CMake' run: | cd main mkdir build cd build cmake -DCMAKE_CXX_COMPILER=g++ -DCMAKE_C_COMPILER=gcc -DLOG4CXX_ABI_CHECK=ON -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_FLAGS="-Og" -DBUILD_TESTING=off .. cmake --build . - name: 'copy compat report' if: always() run: | cp $(find . -name compat_report.html) . - uses: actions/upload-artifact@v2 if: always() with: name: compat_report.html path: compat_report.html apache-log4cxx-1.1.0/.github/workflows/log4cxx-posix.yml000644 001750 001750 00000004537 14424032606 024036 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: log4cxx-posix on: [push, pull_request] jobs: job: name: ${{ matrix.os }}-${{ matrix.cxx }}-build-and-test runs-on: ${{ matrix.os }} timeout-minutes: 38 strategy: fail-fast: false matrix: name: [ubuntu20-gcc, ubuntu20-clang, ubuntu22-gcc, ubuntu22-clang, osx-11, osx-12] include: - name: ubuntu20-gcc os: ubuntu-20.04 cxx: g++ cc: gcc - name: ubuntu20-clang os: ubuntu-20.04 cxx: clang++ cc: clang - name: ubuntu22-gcc os: ubuntu-22.04 cxx: g++ cc: gcc - name: ubuntu22-clang os: ubuntu-22.04 cxx: clang++ cc: clang - name: osx-11 os: macos-11 cxx: clang++ cc: clang - name: osx-12 os: macos-12 cxx: clang++ cc: clang steps: - uses: actions/checkout@v3 with: path: main - name: 'Configure Dependencies - Ubuntu' if: startsWith( matrix.name,'ubuntu' ) run: | sudo apt-get update sudo apt-get install -y libapr1-dev libaprutil1-dev libfmt-dev unixodbc-dev - name: 'run cmake - posix' run: | cd main mkdir build cd build cmake -DCMAKE_CXX_COMPILER=${{ matrix.cxx }} -DCMAKE_C_COMPILER=${{ matrix.cc }} -DLOG4CXX_ENABLE_ODBC=on .. cmake --build . - name: run unit tests shell: pwsh run: | cd main cd build ctest -C Debug --output-on-failure -V apache-log4cxx-1.1.0/.github/workflows/log4cxx-windows-static.yml000644 001750 001750 00000005140 14424032606 025642 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: log4cxx-windows-static on: [push, pull_request] jobs: job: name: ${{ matrix.os }}-${{ matrix.cxx }}-build-and-test runs-on: ${{ matrix.os }} timeout-minutes: 38 strategy: fail-fast: false matrix: name: [windows-2019, windows-2022] include: - name: windows-2019 os: windows-2019 - name: windows-2022 os: windows-2022 steps: - uses: actions/checkout@v3 with: path: main - name: 'Restore Prebuilt Dependencies' id: restore-vcpkg-cache uses: actions/cache@v3 with: path: vcpkg key: ${{ runner.os }}-${{ matrix.name }}-cache-x64-static - name: 'Checkout VCPKG' if: steps.restore-vcpkg-cache.outputs.cache-hit != 'true' uses: actions/checkout@v3 with: repository: microsoft/vcpkg path: vcpkg ref: 0ba60bfef5dea4cb2599daa7ad8364e309835a68 - name: 'Configure Dependencies' if: steps.restore-vcpkg-cache.outputs.cache-hit != 'true' id: runvcpkg shell: pwsh run: | cd vcpkg ./bootstrap-vcpkg.bat ./vcpkg install apr apr-util --triplet=x64-windows-static - name: 'Install zip' id: install-zip shell: pwsh run: | $Env:PATH += ";C:\msys64\usr\bin" pacman --noconfirm -S zip - name: 'run cmake - static' shell: pwsh run: | $THISDIR=Get-Location cd main mkdir build cd build cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBUILD_SHARED_LIBS=off -DLOG4CXX_TEST_PROGRAM_PATH=C:\msys64\usr\bin "-DCMAKE_TOOLCHAIN_FILE=$THISDIR/vcpkg/scripts/buildsystems/vcpkg.cmake" .. cmake --build . - name: run unit tests shell: pwsh run: | cd main cd build ctest -C Debug --output-on-failure -V apache-log4cxx-1.1.0/.github/workflows/sonarcloud.yml000644 001750 001750 00000007607 14353331212 023454 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: sonarcloud on: push: branches: - master - next_stable - sonar* # pull_request: # types: [opened, synchronize, reopened] jobs: build: name: Build runs-on: ubuntu-latest env: SONAR_SCANNER_VERSION: 4.7.0.2747 SONAR_SERVER_URL: "https://sonarcloud.io" BUILD_WRAPPER_OUT_DIR: build_wrapper_output_directory # Directory where build-wrapper output will be placed steps: - uses: actions/checkout@v2 with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis path: main - name: Set up JDK 11 uses: actions/setup-java@v1 with: java-version: 11 - name: Set up Python 3.8 for gcovr uses: actions/setup-python@v2 with: python-version: 3.8 - name: install gcovr 5.2 run: | pip install gcovr==5.2 # 5.1 is not supported - name: 'Configure Dependencies - Ubuntu' run: | sudo apt-get update sudo apt-get install -y libapr1-dev libaprutil1-dev - name: Download and set up sonar-scanner env: SONAR_SCANNER_DOWNLOAD_URL: https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-${{ env.SONAR_SCANNER_VERSION }}-linux.zip run: | mkdir -p $HOME/.sonar curl -sSLo $HOME/.sonar/sonar-scanner.zip ${{ env.SONAR_SCANNER_DOWNLOAD_URL }} unzip -o $HOME/.sonar/sonar-scanner.zip -d $HOME/.sonar/ echo "$HOME/.sonar/sonar-scanner-${{ env.SONAR_SCANNER_VERSION }}-linux/bin" >> $GITHUB_PATH - name: Download and set up build-wrapper env: BUILD_WRAPPER_DOWNLOAD_URL: ${{ env.SONAR_SERVER_URL }}/static/cpp/build-wrapper-linux-x86.zip run: | curl -sSLo $HOME/.sonar/build-wrapper-linux-x86.zip ${{ env.BUILD_WRAPPER_DOWNLOAD_URL }} unzip -o $HOME/.sonar/build-wrapper-linux-x86.zip -d $HOME/.sonar/ echo "$HOME/.sonar/build-wrapper-linux-x86" >> $GITHUB_PATH - name: Run build-wrapper run: | cd main mkdir build cmake -DBUILD_TESTING=on -DENABLE_COVERAGE=on -S . -B build build-wrapper-linux-x86-64 --out-dir ${{ env.BUILD_WRAPPER_OUT_DIR }} cmake --build build/ --config Release - name: Run tests to generate coverage statistics run: | cd main/build make test - name: Collect coverage into one XML report run: | cd main/build/src/main/cpp gcovr --version gcovr --sonarqube -r ../../../../ --verbose --gcov-ignore-parse-errors --exclude '../../../../src/test/' --exclude '../../../../src/examples' -o ../../../coverage.xml - name: Run sonar-scanner env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONARCLOUD_TOKEN }} run: | cd main sonar-scanner \ --define sonar.host.url="${{ env.SONAR_SERVER_URL }}" \ --define sonar.cfamily.build-wrapper-output="${{ env.BUILD_WRAPPER_OUT_DIR }}" \ --define sonar.coverageReportPaths=build/coverage.xml apache-log4cxx-1.1.0/.github/workflows/log4cxx-cpp11.yml000644 001750 001750 00000002763 14424032606 023617 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: log4cxx-cpp11 on: [push, pull_request] jobs: job: name: log4cxx-cpp11 runs-on: ubuntu-20.04 timeout-minutes: 38 steps: - uses: actions/checkout@v3 with: path: main - name: 'Configure Dependencies - Ubuntu' run: | sudo apt-get update sudo apt-get install -y libapr1-dev libaprutil1-dev libboost-filesystem-dev libboost-thread-dev libesmtp-dev - name: 'run cmake - *nix' run: | cd main mkdir build cd build cmake -DCMAKE_CXX_STANDARD=11 -DLOG4CXX_ENABLE_ESMTP=ON .. cmake --build . - name: run unit tests shell: pwsh run: | cd main cd build ctest -C Debug --output-on-failure -V apache-log4cxx-1.1.0/.github/workflows/log4cxx-windows.yml000644 001750 001750 00000005064 14424032606 024362 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: log4cxx-windows on: [push, pull_request] jobs: job: name: ${{ matrix.os }}-${{ matrix.cxx }}-build-and-test runs-on: ${{ matrix.os }} timeout-minutes: 38 strategy: fail-fast: false matrix: name: [windows-2019, windows-2022] include: - name: windows-2019 os: windows-2019 - name: windows-2022 os: windows-2022 steps: - uses: actions/checkout@v3 with: path: main - name: 'Restore Prebuilt Dependencies' id: restore-vcpkg-cache uses: actions/cache@v3 with: path: vcpkg key: ${{ runner.os }}-${{ matrix.name }}-cache-x64 - name: 'Checkout VCPKG' if: steps.restore-vcpkg-cache.outputs.cache-hit != 'true' uses: actions/checkout@v3 with: repository: microsoft/vcpkg path: vcpkg ref: 0ba60bfef5dea4cb2599daa7ad8364e309835a68 - name: 'Configure Dependencies' if: steps.restore-vcpkg-cache.outputs.cache-hit != 'true' id: runvcpkg shell: pwsh run: | cd vcpkg ./bootstrap-vcpkg.bat ./vcpkg install apr apr-util fmt --triplet=x64-windows - name: 'Install zip' id: install-zip shell: pwsh run: | $Env:PATH += ";C:\msys64\usr\bin" pacman --noconfirm -S zip - name: 'run cmake' shell: pwsh run: | $THISDIR=Get-Location cd main mkdir build cd build cmake -DLOG4CXX_TEST_PROGRAM_PATH=C:\msys64\usr\bin -DLOG4CXX_CHAR=wchar_t -DLOG4CXX_ENABLE_ODBC=on "-DCMAKE_TOOLCHAIN_FILE=$THISDIR/vcpkg/scripts/buildsystems/vcpkg.cmake" .. cmake --build . - name: run unit tests shell: pwsh run: | cd main cd build ctest -C Debug --output-on-failure -V apache-log4cxx-1.1.0/KEYS000644 001750 001750 00000034774 14353331212 015666 0ustar00robertrobert000000 000000 This 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----- apache-log4cxx-1.1.0/.asf.yaml000644 001750 001750 00000001772 14353331212 016673 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. notifications: jira_options: link label github: description: "Apache Log4cxx is a C++ port of Apache Log4j" homepage: http://logging.apache.org/log4cxx labels: - apache - logging - cpp features: issues: true apache-log4cxx-1.1.0/CMakeLists.txt000644 001750 001750 00000034343 14424033655 017731 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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}") # 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(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++17, if available # This *should* fallback to an older standard if it is not available if( NOT "${CMAKE_CXX_STANDARD}") set(CMAKE_CXX_STANDARD 17) endif() # Don't allow for compiler-specific extensions set(CMAKE_CXX_EXTENSIONS OFF) # 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 log4cxxTargets 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-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(WIN32 AND BUILD_SHARED_LIBS AND LOG4CXX_INSTALL_PDB) INSTALL(FILES $ DESTINATION ${CMAKE_INSTALL_BINDIR} CONFIGURATIONS RelWithDebInfo Debug ) ENDIF() if(UNIX) # Support for pkg-config in consuming projects 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}/liblog4cxx.pc" ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblog4cxx.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}/liblog4cxx-qt.pc" ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblog4cxx-qt.pc" DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) endif(LOG4CXX_QT_SUPPORT) endif(UNIX) # Support for find_package(log4cxx) in consuming CMake projects using # target_include_directories(myApplication PRIVATE $) # target_link_libraries( myApplication PRIVATE log4cxx) install(EXPORT log4cxxTargets FILE log4cxxConfig.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/log4cxx ) # Support for find_package(log4cxx 0.11) in consuming CMake projects include(CMakePackageConfigHelpers) write_basic_package_version_file("${CMAKE_CURRENT_BINARY_DIR}/log4cxxConfigVersion.cmake" VERSION ${PROJECT_VERSION} COMPATIBILITY SameMinorVersion ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/log4cxxConfigVersion.cmake" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/log4cxx ) if(LOG4CXX_QT_SUPPORT) install(EXPORT log4cxx-qtTargets FILE log4cxx-qtConfig.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/log4cxx-qt ) # Support for find_package(log4cxx 0.11) in consuming CMake projects include(CMakePackageConfigHelpers) write_basic_package_version_file("${CMAKE_CURRENT_BINARY_DIR}/log4cxx-qtConfigVersion.cmake" VERSION ${PROJECT_VERSION} COMPATIBILITY SameMinorVersion ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/log4cxx-qtConfigVersion.cmake" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/log4cxx-qt ) endif(LOG4CXX_QT_SUPPORT) # # Get the varaibles from the 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( THREAD_IMPL DIRECTORY src DEFINITION THREAD_IMPL ) get_directory_property( SMART_PTR_IMPL DIRECTORY src DEFINITION SMART_PTR_IMPL ) get_directory_property( MUTEX_IMPL DIRECTORY src DEFINITION MUTEX_IMPL ) get_directory_property( SHARED_MUTEX_IMPL DIRECTORY src DEFINITION SHARED_MUTEX_IMPL ) get_directory_property( ATOMIC_IMPL DIRECTORY src DEFINITION ATOMIC_IMPL ) 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 ) foreach(varName HAS_STD_LOCALE HAS_ODBC HAS_MBSRTOWCS HAS_WCSTOMBS HAS_FWIDE HAS_LIBESMTP HAS_SYSLOG HAS_FMT) 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() # # Package and sign if Apache maintainer # option(APACHE_MAINTAINER "Apache maintainer" OFF) if(APACHE_MAINTAINER) set(CPACK_SOURCE_PACKAGE_FILE_NAME "apache-log4cxx-${LOG4CXX_RELEASE_VERSION}") set(CPACK_SOURCE_GENERATOR "TGZ;ZIP") set(CPACK_SOURCE_IGNORE_FILES ".git/;build/;.vs/;out/;CMakeLists.txt.user;src/main/abi-symbols/*;src/test/resources/output/") include(CPack) add_custom_target( dist COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} -- package_source COMMAND ${CMAKE_COMMAND} -E sha512sum "apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz" > "apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz.sha512" COMMAND ${CMAKE_COMMAND} -E sha512sum "apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip" > "apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip.sha512" COMMAND gpg -ab --yes "apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz" > "apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz.asc" COMMAND gpg -ab --yes "apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip" > "apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip.asc" ) endif() # # Check for any fatal configuration errors # # # Output configuration information # Similar to APR CMake configuration # message(STATUS "") message(STATUS "") message(STATUS "log4cxx configuration summary:") message(STATUS "") message(STATUS " C++ standard: ................... : ${CMAKE_CXX_STANDARD}") message(STATUS " Build shared library ............ : ${BUILD_SHARED_LIBS}") message(STATUS " Build tests ..................... : ${BUILD_TESTING}") message(STATUS " Build site ...................... : ${BUILD_SITE}") message(STATUS " Install prefix .................. : ${CMAKE_INSTALL_PREFIX}") message(STATUS " C++ compiler .................... : ${CMAKE_CXX_COMPILER}") message(STATUS " std::make_unique found? ......... : ${STD_MAKE_UNIQUE_IMPL}") message(STATUS " std::basic_string ok? .. : ${STD_LIB_HAS_UNICODE_STRING}") 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}") endif() if(APPLE) message(STATUS " log4cxx cfstring API ............ : ${LOG4CXX_CFSTRING}") endif() message(STATUS " logchar type .................... : ${LOG4CXX_CHAR}") message(STATUS " charset ......................... : ${LOG4CXX_CHARSET}") message(STATUS " syslog .......................... : ${HAS_SYSLOG}") message(STATUS " Networking support .............. : ${LOG4CXX_NETWORKING_SUPPORT}") message(STATUS " Qt support ...................... : ${LOG4CXX_QT_SUPPORT}") message(STATUS "C++ version and Boost settings:") message(STATUS " Prefer boost: ................... : ${PREFER_BOOST}") message(STATUS " thread implementation ........... : ${THREAD_IMPL}") message(STATUS " thread_local support? ........... : ${HAS_THREAD_LOCAL}") message(STATUS " mutex implementation ............ : ${MUTEX_IMPL}") message(STATUS " shared_ptr implementation ....... : ${SMART_PTR_IMPL}") message(STATUS " shared_mutex implementation ..... : ${SHARED_MUTEX_IMPL}") message(STATUS " atomic implementation ........... : ${ATOMIC_IMPL}") message(STATUS " filesystem implementation ....... : ${FILESYSTEM_IMPL}") 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 " SocketHubAppender ............... : ${LOG4CXX_NETWORKING_SUPPORT}") message(STATUS " SyslogAppender .................. : ${LOG4CXX_NETWORKING_SUPPORT}") 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.1.0/.astylerc000644 001750 001750 00000001714 14354342764 017022 0ustar00robertrobert000000 000000 ## # Why am I here? # # This file exists to document which settings have been used to reformat the code in general the # last time and to somewhat describe main aspects of the code style in use. It's NOT intended to get # applied whenever any piece of code is changed! Instead, it IS OK to not follow these settings for # some pieces of code, if it makes those pieces more readable in the end. Some pieces of code simply # can not be described properly using automatic formatting rules. # # Example invocation: # # astyle --project src/main/include/*.h src/main/cpp/*.cpp # astyle --project src/test/cpp/*.h src/test/cpp/*.cpp # --add-braces --align-pointer=type --align-reference=type --break-blocks --break-one-line-headers --convert-tabs --indent=force-tab=4 --indent-after-parens --indent-classes --indent-col1-comments --indent-preproc-block --indent-preproc-define --indent-switches --lineend=linux --pad-comma --pad-header --pad-oper --style=break --suffix=none apache-log4cxx-1.1.0/.gitignore000644 001750 001750 00000000757 14354342764 017171 0ustar00robertrobert000000 000000 .deps .dirstamp *.lo *.m4 *.o *.swp ar-lib !configuration-samples.md depcomp install-sh liblog4cxx.pc libtool ltmain.sh Makefile Makefile.in missing pom.xml.releaseBackup release.properties autom4te.cache/ .vs/ out/ src/**/__history/ src/main/cpp/.libs/ src/main/cpp/liblog4cxx.la src/main/include/log4cxx/log4cxx.h src/main/include/log4cxx/private/log4cxx_private.h src/site/doxy/Doxyfile src/site/doxy/manual/ src/test/cpp/Testing/ src/test/resources/org/ src/test/resources/output/ target/ apache-log4cxx-1.1.0/sonar-project.properties000644 001750 001750 00000002307 14353331212 022057 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. sonar.projectKey=log4cxx sonar.organization=apache # This is the name and version displayed in the SonarCloud UI. #sonar.projectName=logging-log4cxx #sonar.projectVersion=1.0 # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. sonar.sources=src/main/cpp,src/main/include,build/src/main # Encoding of the source code. Default is default system encoding #sonar.sourceEncoding=UTF-8 sonar.tests=src/test apache-log4cxx-1.1.0/NOTICE000644 001750 001750 00000000250 14354344574 016072 0ustar00robertrobert000000 000000 Apache 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.1.0/src/000755 001750 001750 00000000000 14424433605 015750 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/000755 001750 001750 00000000000 14424433605 016727 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/CMakeLists.txt000644 001750 001750 00000001452 14354342764 021500 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/cpp/000755 001750 001750 00000000000 14424433605 017511 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/mdctestcase.cpp000644 001750 001750 00000003145 14354342764 022526 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/000755 001750 001750 00000000000 14424433605 020466 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/util/absolutedateandtimefilter.h000644 001750 001750 00000002111 14353331212 026046 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class AbsoluteDateAndTimeFilter : public Filter { public: AbsoluteDateAndTimeFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_ABS_DATE_TIME_FILTER_H apache-log4cxx-1.1.0/src/test/cpp/util/filenamefilter.h000644 001750 001750 00000002232 14353331212 023614 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/test/cpp/util/compare.h000644 001750 001750 00000002342 14353331212 022256 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { 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.1.0/src/test/cpp/util/transformer.cpp000644 001750 001750 00000014371 14353331212 023532 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/linenumberfilter.h000644 001750 001750 00000002061 14353331212 024174 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class LineNumberFilter : public Filter { public: LineNumberFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_LINE_NUMBER_FILTER_H apache-log4cxx-1.1.0/src/test/cpp/util/controlfilter.cpp000644 001750 001750 00000001760 14353331212 024054 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/xmltimestampfilter.cpp000644 001750 001750 00000001767 14353331212 025127 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/transformer.h000644 001750 001750 00000003103 14353331212 023166 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/test/cpp/util/absolutedateandtimefilter.cpp000644 001750 001750 00000001754 14353331212 026415 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/controlfilter.h000644 001750 001750 00000002162 14353331212 023516 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class ControlFilter : public Filter { public: ControlFilter(); ControlFilter& operator<<(const std::string& allowedPattern); }; } #endif //_LOG4CXX_TESTS_UTIL_CONTROL_FILTER_H apache-log4cxx-1.1.0/src/test/cpp/util/xmlthreadfilter.cpp000644 001750 001750 00000001737 14353331212 024370 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/binarycompare.h000644 001750 001750 00000002044 14353331212 023462 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { namespace util { class BinaryCompare { private: /** * Class can not be constructed. */ BinaryCompare(); public: static void compare(const char* filename1, const char* filename2); }; } } apache-log4cxx-1.1.0/src/test/cpp/util/threadfilter.h000644 001750 001750 00000002032 14353331212 023301 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class ThreadFilter : public Filter { public: ThreadFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_THREAD_FILTER_H apache-log4cxx-1.1.0/src/test/cpp/util/relativetimefilter.cpp000644 001750 001750 00000001716 14353331212 025067 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/filenamefilter.cpp000644 001750 001750 00000002524 14353331212 024153 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/relativetimefilter.h000644 001750 001750 00000002054 14353331212 024530 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class RelativeTimeFilter : public Filter { public: RelativeTimeFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_REL_TIME_FILTER_H apache-log4cxx-1.1.0/src/test/cpp/util/CMakeLists.txt000644 001750 001750 00000002755 14354342764 023246 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/cpp/util/linenumberfilter.cpp000644 001750 001750 00000002044 14353331212 024530 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/filter.h000644 001750 001750 00000003626 14354342764 022142 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/test/cpp/util/xmltimestampfilter.h000644 001750 001750 00000002073 14353331212 024563 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class XMLTimestampFilter : public Filter { public: XMLTimestampFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_XML_TIMESTAMP_FILTER_H apache-log4cxx-1.1.0/src/test/cpp/util/iso8601filter.cpp000644 001750 001750 00000001670 14353331212 023505 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/xmlfilenamefilter.cpp000644 001750 001750 00000002257 14353331212 024677 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/absolutetimefilter.cpp000644 001750 001750 00000001716 14353331212 025072 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/absolutetimefilter.h000644 001750 001750 00000002054 14353331212 024533 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class AbsoluteTimeFilter : public Filter { public: AbsoluteTimeFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_ABS_TIME_FILTER_H apache-log4cxx-1.1.0/src/test/cpp/util/xmlthreadfilter.h000644 001750 001750 00000002054 14353331212 024026 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class XMLThreadFilter : public Filter { public: XMLThreadFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_XML_THREAD_FILTER_H apache-log4cxx-1.1.0/src/test/cpp/util/xmllineattributefilter.cpp000644 001750 001750 00000002012 14353331212 025757 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/utilfilter.cpp000644 001750 001750 00000002124 14353331212 023344 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/compare.cpp000644 001750 001750 00000010032 14353331212 022604 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/iso8601filter.h000644 001750 001750 00000002042 14353331212 023144 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class ISO8601Filter : public Filter { public: ISO8601Filter(); }; } #endif //_LOG4CXX_TESTS_UTIL_ISO_8601_FILTER_H apache-log4cxx-1.1.0/src/test/cpp/util/xmllineattributefilter.h000644 001750 001750 00000002122 14353331212 025426 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class XMLLineAttributeFilter : public Filter { public: XMLLineAttributeFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_XML_LINE_ATTRIBUTE_FILTER_H apache-log4cxx-1.1.0/src/test/cpp/util/binarycompare.cpp000644 001750 001750 00000005056 14353331212 024023 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/threadfilter.cpp000644 001750 001750 00000001706 14353331212 023643 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/util/xmlfilenamefilter.h000644 001750 001750 00000002154 14353331212 024340 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/test/cpp/hierarchytest.cpp000644 001750 001750 00000003555 14353331212 023073 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/abts.cpp000644 001750 001750 00000023400 14424032606 021141 0ustar00robertrobert000000 000000 /* 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) { // subsuite->name = (const char*) memcpy(calloc(p - suite_name + 1, 1), // suite_name, p - suite_name); int length = p - suite_name + 1; 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(ts->tail->name.c_str())) { return; } ss = ts->tail; tc.failed = 0; tc.suite = ss; ss->num_test++; update_status(); if (verbose) fprintf(stdout, " %s\n", name); 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, "%-15s\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, "%-15s\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.1.0/src/test/cpp/leveltestcase.cpp000644 001750 001750 00000006411 14353331212 023052 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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" #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(); 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.1.0/src/test/cpp/insertwide.h000644 001750 001750 00000002266 14353331212 022035 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 || LOG4CXX_CFSTRING_API std::ostream& operator<<(std::ostream& os, const std::basic_string& str); #endif #endif apache-log4cxx-1.1.0/src/test/cpp/testutil.h000644 001750 001750 00000001704 14353331212 021531 0ustar00robertrobert000000 000000 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/000755 001750 001750 00000000000 14424433605 021153 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/helpers/stringhelpertestcase.cpp000644 001750 001750 00000006646 14353331212 026125 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/propertiestestcase.cpp000644 001750 001750 00000022707 14353331212 025607 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/transcodertestcase.cpp000644 001750 001750 00000024006 14353331212 025551 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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" 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 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); 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 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( 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); } 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, 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.1.0/src/test/cpp/helpers/messagebuffertest.cpp000644 001750 001750 00000014274 14353331212 025375 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #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); #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(); 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()); } #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_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()); } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(MessageBufferTest); apache-log4cxx-1.1.0/src/test/cpp/helpers/syslogwritertest.cpp000644 001750 001750 00000002446 14353331212 025332 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/cacheddateformattestcase.cpp000644 001750 001750 00000046264 14353331212 026675 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/charsetdecodertestcase.cpp000644 001750 001750 00000006127 14424032606 026374 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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" #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(decode8); 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 decode8() { 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); } }; LOGUNIT_TEST_SUITE_REGISTRATION(CharsetDecoderTestCase); apache-log4cxx-1.1.0/src/test/cpp/helpers/timezonetestcase.cpp000644 001750 001750 00000006366 14354342764 025267 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/localechanger.cpp000644 001750 001750 00000003175 14424032606 024450 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/test/cpp/helpers/absolutetimedateformattestcase.cpp000644 001750 001750 00000013011 14353331212 030143 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/CMakeLists.txt000644 001750 001750 00000003652 14354342764 023730 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/cpp/helpers/threadutilitytestcase.cpp000644 001750 001750 00000006214 14424032606 026305 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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_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"), []() {} ); t.join(); LOGUNIT_ASSERT_EQUAL( num_pre, 1 ); LOGUNIT_ASSERT_EQUAL( num_started, 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.1.0/src/test/cpp/helpers/inetaddresstestcase.cpp000644 001750 001750 00000004730 14353331212 025714 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/localechanger.h000644 001750 001750 00000003012 14353331212 024077 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/test/cpp/helpers/casttestcase.cpp000644 001750 001750 00000004263 14354342764 024361 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/charsetencodertestcase.cpp000644 001750 001750 00000021543 14353331212 026401 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 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); #if APR_HAS_THREADS LOGUNIT_TEST(thread1); #endif 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()); } #if APR_HAS_THREADS class ThreadPackage { public: ThreadPackage(CharsetEncoderPtr& enc, int repetitions) : p(), passCount(0), failCount(0), enc(enc), repetitions(repetitions) { } void await() { std::unique_lock sync(lock); condition.wait(sync); } void signalAll() { std::unique_lock sync(lock); condition.notify_all(); } void fail() { apr_atomic_inc32(&failCount); } void pass() { apr_atomic_inc32(&passCount); } apr_uint32_t getFail() { return apr_atomic_read32(&failCount); } apr_uint32_t getPass() { return apr_atomic_read32(&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&); Pool p; std::mutex lock; std::condition_variable condition; volatile apr_uint32_t passCount; volatile apr_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"))); ThreadPackage* package = new ThreadPackage(enc, THREAD_REPS); { for (int i = 0; i < THREAD_COUNT; i++) { threads[i] = std::thread(&ThreadPackage::run, package); } } // // 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()); delete package; } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(CharsetEncoderTestCase); apache-log4cxx-1.1.0/src/test/cpp/helpers/stringtokenizertestcase.cpp000644 001750 001750 00000007645 14353331212 026660 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/cyclicbuffertestcase.cpp000644 001750 001750 00000010105 14353331212 026040 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/filewatchdogtest.cpp000644 001750 001750 00000003442 14353331212 025212 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/datetimedateformattestcase.cpp000644 001750 001750 00000015750 14353331212 027256 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/test/cpp/helpers/relativetimedateformattestcase.cpp000644 001750 001750 00000004572 14353331212 030154 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/optionconvertertestcase.cpp000644 001750 001750 00000013571 14353331212 026652 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/helpers/iso8601dateformattestcase.cpp000644 001750 001750 00000011324 14353331212 026564 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/encodingtest.cpp000644 001750 001750 00000011335 14354342764 022715 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/consoleappendertestcase.cpp000644 001750 001750 00000003406 14353331212 025125 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/l7dtestcase.cpp000644 001750 001750 00000006316 14354342764 022454 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/logunit.h000644 001750 001750 00000016761 14354342764 021365 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 || LOG4CXX_CFSTRING_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.1.0/src/test/cpp/fileappendertestcase.h000644 001750 001750 00000002216 14353331212 024045 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/ndctestcase.cpp000644 001750 001750 00000005304 14354342764 022526 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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(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.1.0/src/test/cpp/nt/000755 001750 001750 00000000000 14424433605 020132 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/nt/CMakeLists.txt000644 001750 001750 00000000204 14353331212 022656 0ustar00robertrobert000000 000000 add_executable(eventlogtests nteventlogappendertestcase.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} eventlogtests PARENT_SCOPE) apache-log4cxx-1.1.0/src/test/cpp/nt/nteventlogappendertestcase.cpp000644 001750 001750 00000006172 14353331212 026274 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/test/cpp/appenderskeletontestcase.cpp000644 001750 001750 00000003035 14353331212 025305 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/benchmark/000755 001750 001750 00000000000 14424433605 021443 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/benchmark/benchmark.cpp000644 001750 001750 00000017041 14424033175 024102 0ustar00robertrobert000000 000000 #include #include #include #include #include #include #include #include #include using namespace log4cxx; 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 true; } 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 { } }; IMPLEMENT_LOG4CXX_OBJECT(NullWriterAppender) #if defined(LOG4CXX_VERSION_MINOR) && (0 < LOG4CXX_VERSION_MAJOR || 11 < LOG4CXX_VERSION_MINOR) LOG4CXX_PTR_DEF(NullWriterAppender); #else #define LOG4CXX_HAS_FMT 0 template class log4cxx::helpers::ObjectPtrT; typedef log4cxx::helpers::ObjectPtrT NullWriterAppenderPtr; #endif class benchmarker : public ::benchmark::Fixture { public: LoggerPtr m_logger; void SetupLogger() { m_logger = Logger::getLogger(LOG4CXX_STR("bench_logger")); m_logger->removeAllAppenders(); m_logger->setAdditivity(false); m_logger->setLevel(Level::getInfo()); PatternLayoutPtr pattern(new PatternLayout); pattern->setConversionPattern(LOG4CXX_STR("%m%n")); NullWriterAppenderPtr nullWriter(new NullWriterAppender); nullWriter->setName(LOG4CXX_STR("NullWriterAppender")); nullWriter->setLayout(pattern); m_logger->addAppender(nullWriter); } void SetUp(const ::benchmark::State& state) { std::setlocale( LC_ALL, "" ); /* Set locale for C functions */ std::locale::global(std::locale("")); /* set locale for C++ functions */ SetupLogger(); } void TearDown(const ::benchmark::State& state) { } 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; } }; BENCHMARK_DEFINE_F(benchmarker, logDisabledTrace)(benchmark::State& state) { m_logger->setLevel(Level::getDebug()); for (auto _ : state) { LOG4CXX_TRACE( m_logger, LOG4CXX_STR("This is a static string to see what happens")); } } BENCHMARK_REGISTER_F(benchmarker, logDisabledTrace)->Name("Logging disabled trace")->MinWarmUpTime(benchmarker::warmUpSeconds()); BENCHMARK_REGISTER_F(benchmarker, logDisabledTrace)->Name("Logging disabled trace")->Threads(benchmarker::threadCount()); BENCHMARK_DEFINE_F(benchmarker, logDisabledDebug)(benchmark::State& state) { m_logger->setLevel(Level::getInfo()); for (auto _ : state) { LOG4CXX_DEBUG(m_logger, LOG4CXX_STR("This is a static string to see what happens")); } } BENCHMARK_REGISTER_F(benchmarker, logDisabledDebug)->Name("Logging disabled debug"); BENCHMARK_DEFINE_F(benchmarker, logStaticString)(benchmark::State& state) { m_logger->setLevel(Level::getInfo()); for (auto _ : state) { LOG4CXX_INFO( m_logger, LOG4CXX_STR("This is a static string to see what happens")); } } BENCHMARK_REGISTER_F(benchmarker, logStaticString)->Name("Logging info static string"); BENCHMARK_DEFINE_F(benchmarker, logEnabledDebug)(benchmark::State& state) { m_logger->setLevel( Level::getDebug() ); for (auto _ : state) { LOG4CXX_DEBUG( m_logger, LOG4CXX_STR("This is a static string to see what happens")); } } BENCHMARK_REGISTER_F(benchmarker, logEnabledDebug)->Name("Logging enabled debug static string"); BENCHMARK_DEFINE_F(benchmarker, logEnabledTrace)(benchmark::State& state) { m_logger->setLevel( Level::getTrace() ); for (auto _ : state) { LOG4CXX_DEBUG( m_logger, LOG4CXX_STR("This is a static string to see what happens")); } } BENCHMARK_REGISTER_F(benchmarker, logEnabledTrace)->Name("Logging enabled trace static string"); #if LOG4CXX_HAS_FMT BENCHMARK_DEFINE_F(benchmarker, logStaticStringFMT)(benchmark::State& state) { for (auto _ : state) { LOG4CXX_INFO_FMT(m_logger, "This is a static string to see what happens"); } } BENCHMARK_REGISTER_F(benchmarker, logStaticStringFMT)->Name("Logging static string with FMT"); BENCHMARK_DEFINE_F(benchmarker, logIntValueFMT)(benchmark::State& state) { int x = 0; for (auto _ : state) { LOG4CXX_INFO_FMT( m_logger, "Hello m_logger: msg number {}", ++x); } } BENCHMARK_REGISTER_F(benchmarker, logIntValueFMT)->Name("Logging int value with FMT"); BENCHMARK_REGISTER_F(benchmarker, logIntValueFMT)->Name("Logging int value with FMT")->Threads(benchmarker::threadCount()); #endif BENCHMARK_DEFINE_F(benchmarker, logIntValueStream)(benchmark::State& state) { int x = 0; for (auto _ : state) { LOG4CXX_INFO( m_logger, "Hello m_logger: msg number " << ++x); } } BENCHMARK_REGISTER_F(benchmarker, logIntValueStream)->Name("Logging int value with std::ostream"); BENCHMARK_REGISTER_F(benchmarker, logIntValueStream)->Name("Logging int value with std::ostream")->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); PatternLayoutPtr pattern(new PatternLayout); pattern->setConversionPattern( conversionPattern ); auto logger = Logger::getLogger( LOG4CXX_STR("bench_logger") ); logger->getAppender(LOG4CXX_STR("NullWriterAppender"))->setLayout(pattern); int x = 0; for (auto _ : state) { LOG4CXX_INFO( logger, LOG4CXX_STR("Hello m_logger: msg number ") << ++x); } } BENCHMARK_CAPTURE(logWithConversionPattern, NoFormat, LOG4CXX_STR("%m%n"))->Name("NoFormat pattern: %m%n"); BENCHMARK_CAPTURE(logWithConversionPattern, DateOnly, LOG4CXX_STR("[%d] %m%n"))->Name("DateOnly pattern: [%d] %m%n"); BENCHMARK_CAPTURE(logWithConversionPattern, DateClassLevel, LOG4CXX_STR("[%d] [%c] [%p] %m%n"))->Name("DateClassLevel pattern: [%d] [%c] [%p] %m%n"); static void SetAsyncAppender(const benchmark::State& state) { LoggerPtr logger = Logger::getLogger( LOG4CXX_STR("bench_logger") ); logger->removeAllAppenders(); logger->setAdditivity( false ); logger->setLevel( Level::getInfo() ); PatternLayoutPtr pattern(new PatternLayout); pattern->setConversionPattern(LOG4CXX_STR("%m%n")); NullWriterAppenderPtr nullWriter(new NullWriterAppender); nullWriter->setLayout( pattern ); AsyncAppenderPtr asyncAppender = AsyncAppenderPtr(new AsyncAppender()); asyncAppender->addAppender(nullWriter); asyncAppender->setBufferSize(5); helpers::Pool p; asyncAppender->activateOptions(p); logger->addAppender(asyncAppender); } BENCHMARK_REGISTER_F(benchmarker, logIntValueStream)->Name("Logging int value with std::ostream to AsyncAppender")->Setup(SetAsyncAppender); BENCHMARK_REGISTER_F(benchmarker, logIntValueStream)->Name("Logging int value with std::ostream to AsyncAppender")->Threads(benchmarker::threadCount()); BENCHMARK_MAIN(); apache-log4cxx-1.1.0/src/test/cpp/benchmark/CMakeLists.txt000644 001750 001750 00000005737 14353331212 024207 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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) find_package(fmt QUIET) if(fmt_FOUND) set(LOG4CXX_HAS_FMT 1) else() set(LOG4CXX_HAS_FMT 0) 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) 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(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 ${CMAKE_CURRENT_LIST_DIR} $) target_link_libraries(benchmark PRIVATE log4cxx ${APR_LIBRARIES} ${APR_SYSTEM_LIBS} Threads::Threads fmt::fmt benchmark::benchmark benchmark::benchmark_main) apache-log4cxx-1.1.0/src/test/cpp/logunit.cpp000644 001750 001750 00000013705 14354342764 021713 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 || LOG4CXX_CFSTRING_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.1.0/src/test/cpp/patternlayouttest.cpp000644 001750 001750 00000036130 14354342764 024042 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/customlogger/000755 001750 001750 00000000000 14424433605 022223 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/customlogger/xlogger.h000644 001750 001750 00000006204 14354342764 024054 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { 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(); LoggerPtr makeNewLoggerInstance( log4cxx::helpers::Pool& pool, const LogString& name) const override; }; 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(log4cxx::helpers::Pool& pool, const LogString& name1) : Logger(pool, name1) {} /** 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.1.0/src/test/cpp/customlogger/CMakeLists.txt000644 001750 001750 00000001635 14353331212 024760 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/cpp/customlogger/xlogger.cpp000644 001750 001750 00000005377 14354342764 024421 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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() { } LoggerPtr XFactory::makeNewLoggerInstance(log4cxx::helpers::Pool& pool, const LogString& name) const { return LoggerPtr(new XLogger(pool, name)); } apache-log4cxx-1.1.0/src/test/cpp/customlogger/xloggertestcase.cpp000644 001750 001750 00000004610 14354342764 026142 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/test/cpp/defaultinit/000755 001750 001750 00000000000 14424433605 022021 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/defaultinit/testcase3.cpp000644 001750 001750 00000003454 14353331212 024421 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/defaultinit/testcase2.cpp000644 001750 001750 00000003524 14353331212 024416 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/test/cpp/defaultinit/CMakeLists.txt000644 001750 001750 00000001675 14353331212 024562 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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(defaultinittestcase testcase1.cpp testcase2.cpp testcase3.cpp testcase4.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} defaultinittestcase PARENT_SCOPE) apache-log4cxx-1.1.0/src/test/cpp/defaultinit/testcase4.cpp000644 001750 001750 00000003616 14353331212 024422 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/test/cpp/defaultinit/testcase1.cpp000644 001750 001750 00000002517 14353331212 024416 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/CMakeLists.txt000644 001750 001750 00000016047 14424032606 022255 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 hierarchytest hierarchythresholdtestcase jsonlayouttest l7dtestcase leveltestcase loggertestcase mdctestcase minimumtestcase ndctestcase patternlayouttest propertyconfiguratortest rollingfileappendertestcase streamtestcase locationtest locationdisabledtest ) 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() 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) add_subdirectory(customlogger) 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(xml) 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) foreach(testName IN LISTS ALL_LOG4CXX_TESTS) 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} ) 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.1.0/src/test/cpp/vectorappender.cpp000644 001750 001750 00000002306 14354342764 023246 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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*/) { std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) ); vector.push_back(event); } void VectorAppender::close() { if (m_priv->closed) { return; } m_priv->closed = true; } apache-log4cxx-1.1.0/src/test/cpp/fmttest.cpp000644 001750 001750 00000013677 14424032606 021715 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/net/000755 001750 001750 00000000000 14424433605 020277 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/net/socketappendertestcase.cpp000644 001750 001750 00000005247 14354342764 025565 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; #if APR_HAS_THREADS /** 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); #endif apache-log4cxx-1.1.0/src/test/cpp/net/telnetappendertestcase.cpp000644 001750 001750 00000005450 14354342764 025564 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; #if APR_HAS_THREADS /** 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_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( 1000 ) ); 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(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(TelnetAppenderTestCase); #endif apache-log4cxx-1.1.0/src/test/cpp/net/socketservertestcase.h000644 001750 001750 00000001701 14353331212 024712 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/test/cpp/net/smtpappendertestcase.cpp000644 001750 001750 00000007234 14424032606 025243 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 namespace log4cxx { 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); //LOGUNIT_TEST(testValid); 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"); } void testValid() { xml::DOMConfigurator::configure("input/xml/smtpAppenderValid.xml"); auto root = Logger::getRootLogger(); LOG4CXX_INFO(root, "Hello, World."); LOG4CXX_ERROR(root, "Sending Message"); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SMTPAppenderTestCase); apache-log4cxx-1.1.0/src/test/cpp/net/xmlsocketappendertestcase.cpp000644 001750 001750 00000003510 14424033175 026264 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; #if APR_HAS_THREADS /** 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); #endif apache-log4cxx-1.1.0/src/test/cpp/net/socketserverstarter.cpp000644 001750 001750 00000011520 14353331212 025116 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/net/syslogappendertestcase.cpp000644 001750 001750 00000002733 14354342764 025612 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/net/CMakeLists.txt000644 001750 001750 00000002336 14424032606 023037 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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(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.1.0/src/test/cpp/fileappendertestcase.cpp000644 001750 001750 00000007353 14353331212 024407 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/appenderskeletontestcase.h000644 001750 001750 00000002162 14353331212 024752 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/autoconfiguretestcase.cpp000644 001750 001750 00000010523 14354342764 024633 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/filter/000755 001750 001750 00000000000 14424433605 020776 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/filter/loggermatchfiltertest.cpp000644 001750 001750 00000006512 14353331212 026100 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/filter/levelrangefiltertest.cpp000644 001750 001750 00000011165 14353331212 025730 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/filter/levelmatchfiltertest.cpp000644 001750 001750 00000007740 14353331212 025734 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/filter/CMakeLists.txt000644 001750 001750 00000002121 14354342764 023541 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/cpp/filter/locationinfofiltertest.cpp000644 001750 001750 00000007243 14424032606 026276 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/filter/mapfiltertest.cpp000644 001750 001750 00000012053 14353331212 024356 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/filter/stringmatchfiltertest.cpp000644 001750 001750 00000010065 14353331212 026125 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/filter/denyallfiltertest.cpp000644 001750 001750 00000003313 14353331212 025230 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/filter/andfiltertest.cpp000644 001750 001750 00000012706 14353331212 024350 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/db/000755 001750 001750 00000000000 14424433605 020076 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/db/CMakeLists.txt000644 001750 001750 00000000214 14424032606 022627 0ustar00robertrobert000000 000000 add_executable(odbcappendertestcase odbcappendertestcase.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} odbcappendertestcase PARENT_SCOPE) apache-log4cxx-1.1.0/src/test/cpp/db/odbcappendertestcase.cpp000644 001750 001750 00000005255 14424032606 024767 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/propertyconfiguratortest.cpp000644 001750 001750 00000007303 14353331212 025417 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/streamtestcase.cpp000644 001750 001750 00000051714 14353331212 023244 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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_CFSTRING_API) #define __FORCE_INSTANCE #endif #include #include #include "vectorappender.h" #include #include #include #include "insertwide.h" #include "logunit.h" #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); LOGUNIT_TEST(testULogStreamCFString); LOGUNIT_TEST(testULogStreamCFString2); #endif LOGUNIT_TEST_SUITE_END(); VectorAppenderPtr vectorAppender; 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); 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 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()); } 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.1.0/src/test/cpp/xml/000755 001750 001750 00000000000 14424433605 020311 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/xml/xmllayouttest.cpp000644 001750 001750 00000026642 14353331212 023755 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/xml/xlevel.cpp000644 001750 001750 00000004143 14353331212 022306 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/xml/xmllayouttestcase.cpp000644 001750 001750 00000022645 14354342764 024627 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/xml/customleveltestcase.cpp000644 001750 001750 00000006355 14353331212 025114 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/test/cpp/xml/CMakeLists.txt000644 001750 001750 00000002006 14353331212 023037 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/cpp/xml/xlevel.h000644 001750 001750 00000003616 14353331212 021757 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { 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.1.0/src/test/cpp/xml/domtestcase.cpp000644 001750 001750 00000015644 14354342764 023351 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/rolling/000755 001750 001750 00000000000 14424433605 021157 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/rolling/filterbasedrollingtest.cpp000644 001750 001750 00000010474 14353331212 026434 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::xml; 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() { DOMConfigurator::configure( "./input/rolling/filter1.xml" /*, LogManager::getLoggerRepository() */); common(LOG4CXX_STR("output/filterBased-test1")); } /** * 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.1.0/src/test/cpp/rolling/rollingfileappenderpropertiestest.cpp000644 001750 001750 00000016740 14354342764 030744 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::xml; 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.1.0/src/test/cpp/rolling/CMakeLists.txt000644 001750 001750 00000002242 14354342764 023726 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/cpp/rolling/manualrollingtest.cpp000644 001750 001750 00000026120 14353331212 025420 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::xml; 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.1.0/src/test/cpp/rolling/timebasedrollingtest.cpp000644 001750 001750 00000055470 14354342764 026131 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/rolling/filenamepatterntestcase.cpp000644 001750 001750 00000013104 14353331212 026564 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/rolling/sizebasedrollingtest.cpp000644 001750 001750 00000030136 14354342764 026135 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::xml; 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.1.0/src/test/cpp/minimumtestcase.cpp000644 001750 001750 00000013116 14354342764 023435 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/testchar.h000644 001750 001750 00000002227 14353331212 021472 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/test/cpp/jsonlayouttest.cpp000644 001750 001750 00000030661 14354342764 023341 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/multithreadtest.cpp000644 001750 001750 00000006021 14354342764 023445 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 using log4cxx::Logger; using log4cxx::LoggerPtr; using log4cxx::LogManager; class NullWriterAppender : public log4cxx::AppenderSkeleton { public: NullWriterAppender() {} virtual void close() {} virtual bool requiresLayout() const { return false; } virtual void append(const log4cxx::spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) { // Do nothing but discard the data } }; 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 a test message that has some data" ); if ( distribution(gen) == x ) { 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(); std::shared_ptr nullWriter( new NullWriterAppender() ); Logger::getRootLogger()->addAppender( nullWriter ); } 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.1.0/src/test/cpp/throughput/000755 001750 001750 00000000000 14424433605 021722 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/throughput/throughput-main.cpp000644 001750 001750 00000015313 14354342764 025573 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 "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::unique_lock 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::unique_lock 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):"); 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:"); for ( uint64_t result : results ) { LOG4CXX_INFO_FMT(console, "{}", result ); } return 0; } apache-log4cxx-1.1.0/src/test/cpp/throughput/log4cxxbenchmarker.h000644 001750 001750 00000006021 14353331212 025654 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/test/cpp/throughput/CMakeLists.txt000644 001750 001750 00000005466 14353331212 024465 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/cpp/throughput/log4cxxbenchmarker.cpp000644 001750 001750 00000013627 14354342764 026240 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #include namespace log4cxx { 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"); } } 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.1.0/src/test/cpp/writerappendertestcase.cpp000644 001750 001750 00000002027 14353331212 024775 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/varia/000755 001750 001750 00000000000 14424433605 020613 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/varia/levelmatchfiltertestcase.cpp000644 001750 001750 00000011711 14354342764 026415 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/varia/errorhandlertestcase.cpp000644 001750 001750 00000010700 14354342764 025547 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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(); 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(); 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.1.0/src/test/cpp/varia/CMakeLists.txt000644 001750 001750 00000002113 14353331212 023340 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 ) 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.1.0/src/test/cpp/varia/levelrangefiltertestcase.cpp000644 001750 001750 00000016100 14354342764 026412 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/locationdisabledtest.cpp000644 001750 001750 00000003512 14353331212 024406 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/rollingfileappendertestcase.cpp000644 001750 001750 00000002712 14353331212 025770 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/filetestcase.cpp000644 001750 001750 00000012376 14353331212 022671 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #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(); 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/patternLayout.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.1.0/src/test/cpp/asyncappendertestcase.cpp000644 001750 001750 00000023406 14354342764 024621 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 "vectorappender.h" #include #include "appenderskeletontestcase.h" #include #include #include #include #include "testchar.h" #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::unique_lock 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); #if APR_HAS_THREADS /** * 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(test3); LOGUNIT_TEST(testBadAppender); LOGUNIT_TEST(testLocationInfoTrue); LOGUNIT_TEST(testConfiguration); 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 whether appenders embedded within an AsyncAppender are also // closed void test3() { size_t LEN = 200; LoggerPtr root = Logger::getRootLogger(); VectorAppenderPtr vectorAppender = VectorAppenderPtr(new VectorAppender()); AsyncAppenderPtr asyncAppender = AsyncAppenderPtr(new AsyncAppender()); asyncAppender->setName(LOG4CXX_STR("async-test3")); asyncAppender->addAppender(vectorAppender); root->addAppender(asyncAppender); for (size_t i = 0; i < LEN; i++) { LOG4CXX_DEBUG(root, "message" << i); } asyncAppender->close(); root->debug(LOG4CXX_TEST_STR("m2")); const std::vector& v = vectorAppender->getVector(); LOGUNIT_ASSERT_EQUAL(LEN, v.size()); LOGUNIT_ASSERT_EQUAL(true, vectorAppender->isClosed()); } /** * 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( 10 ) ); LOG4CXX_INFO(root, "Message"); auto& v = vectorAppender->getVector(); LOGUNIT_ASSERT(0 < v.size()); } /** * Tests non-blocking behavior. */ void testLocationInfoTrue() { BlockableVectorAppenderPtr blockableAppender = BlockableVectorAppenderPtr(new BlockableVectorAppender()); blockableAppender->setName(LOG4CXX_STR("async-blockableVector")); AsyncAppenderPtr async = AsyncAppenderPtr(new AsyncAppender()); async->setName(LOG4CXX_STR("async-testLocationInfoTrue")); async->addAppender(blockableAppender); async->setBufferSize(5); async->setLocationInfo(true); async->setBlocking(false); Pool p; async->activateOptions(p); LoggerPtr rootLogger = Logger::getRootLogger(); rootLogger->addAppender(async); { std::unique_lock sync(blockableAppender->getBlocker()); for (int i = 0; i < 140; i++) { LOG4CXX_INFO(rootLogger, "Hello, World"); std::this_thread::sleep_for( std::chrono::milliseconds( 1 ) ); } LOG4CXX_ERROR(rootLogger, "That's all folks."); } async->close(); const std::vector& events = blockableAppender->getVector(); LOGUNIT_ASSERT(events.size() > 0); LoggingEventPtr initialEvent = events[0]; LoggingEventPtr discardEvent = events[events.size() - 1]; 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()); } 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()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(AsyncAppenderTestCase); #endif apache-log4cxx-1.1.0/src/test/cpp/abts_tests.h000644 001750 001750 00000001635 14353331212 022032 0ustar00robertrobert000000 000000 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/test/cpp/pattern/000755 001750 001750 00000000000 14424433605 021166 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/cpp/pattern/num343patternconverter.h000644 001750 001750 00000002447 14354342764 025734 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { 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.1.0/src/test/cpp/pattern/patternparsertestcase.cpp000644 001750 001750 00000021303 14424032606 026313 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 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 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 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++) { int fieldStart = 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.1.0/src/test/cpp/pattern/CMakeLists.txt000644 001750 001750 00000001756 14354342764 023746 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/cpp/pattern/num343patternconverter.cpp000644 001750 001750 00000002641 14354342764 026263 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/pattern/colorstartpatternconvertertest.cpp000644 001750 001750 00000017460 14424032606 030320 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/fileappendertest.cpp000644 001750 001750 00000004765 14353331212 023557 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/vectorappender.h000644 001750 001750 00000003362 14354342764 022716 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { /** 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; /** 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 vector; } void close() override; bool isClosed() const { return m_priv->closed; } bool requiresLayout() const override { return false; } }; typedef std::shared_ptr VectorAppenderPtr; } apache-log4cxx-1.1.0/src/test/cpp/locationtest.cpp000644 001750 001750 00000003443 14353331212 022721 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/writerappendertestcase.h000644 001750 001750 00000002226 14353331212 024443 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/decodingtest.cpp000644 001750 001750 00000011044 14353331212 022661 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 "logunit.h" // // 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(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-16 decoding. */ void testUtf16() { const wchar_t witness[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x0400, 0x0020, 0x00B9, 0 }; testImpl(LOG4CXX_STR("UTF-16.txt"), witness); } /** * Test utf-16be decoding. */ void testUtf16BE() { const wchar_t witness[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x0400, 0x0020, 0x00B9, 0 }; testImpl(LOG4CXX_STR("UTF-16BE.txt"), witness); } /** * Test utf16-le decoding. */ void testUtf16LE() { const wchar_t witness[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x0400, 0x0020, 0x00B9, 0 }; testImpl(LOG4CXX_STR("UTF-16LE.txt"), witness); } 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.1.0/src/test/cpp/abts.h000644 001750 001750 00000006436 14354342764 020633 0ustar00robertrobert000000 000000 /* 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 #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.1.0/src/test/cpp/hierarchythresholdtestcase.cpp000644 001750 001750 00000007371 14354342764 025663 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/test/cpp/loggertestcase.cpp000644 001750 001750 00000035236 14354342764 023250 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 "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; } }; 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(testTrace); LOGUNIT_TEST(testIsTraceEnabled); 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 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)); } protected: static LogString MSG; LoggerPtr logger; AppenderPtr a1; AppenderPtr a2; }; LogString LoggerTestCase::MSG(LOG4CXX_STR("M")); LOGUNIT_TEST_SUITE_REGISTRATION(LoggerTestCase); apache-log4cxx-1.1.0/src/test/resources/000755 001750 001750 00000000000 14424433605 020741 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/L7D_fr.properties000644 001750 001750 00000001751 14353331212 024130 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/000755 001750 001750 00000000000 14424433605 022100 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/patternLayout3.properties000644 001750 001750 00000002164 14353331212 027147 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/fmtLayout1.properties000644 001750 001750 00000002117 14354342764 026273 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/socketServer3.properties000644 001750 001750 00000002203 14353331212 026745 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/propertiestestcase.properties000644 001750 001750 00000002517 14353331212 030143 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/socketServer2.properties000644 001750 001750 00000002204 14353331212 026745 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/location1.properties000644 001750 001750 00000002134 14353331212 026077 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/propertiestestcase-lf.properties000644 001750 001750 00000001610 14353331212 030533 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout6.properties000644 001750 001750 00000002152 14353331212 027147 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/fmtLayout10.properties000644 001750 001750 00000002134 14354342764 026352 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/hierarchyThreshold1.properties000644 001750 001750 00000002043 14353331212 030121 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/hierarchyThreshold7.properties000644 001750 001750 00000002104 14353331212 030125 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/socketServer4.properties000644 001750 001750 00000002216 14353331212 026752 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout10.properties000644 001750 001750 00000002136 14353331212 027224 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/fmtLayout1_expanded.properties000644 001750 001750 00000002137 14354342764 030145 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout11.properties000644 001750 001750 00000002134 14353331212 027223 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/socketServer7.properties000644 001750 001750 00000002221 14353331212 026751 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout1.properties000644 001750 001750 00000002123 14353331212 027140 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/xml/000755 001750 001750 00000000000 14424433605 022700 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/fallback1.xml000644 001750 001750 00000004365 14354342764 025261 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/log4j.dtd000644 001750 001750 00000015076 14353331212 024415 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/DOMTestCase1.xml000644 001750 001750 00000003427 14354342764 025573 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/customLevel4.xml000644 001750 001750 00000002574 14353331212 026010 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/DOMTestCase4.xml000644 001750 001750 00000002534 14353331212 025555 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/customLevel3.xml000644 001750 001750 00000003225 14353331212 026001 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/filters.LevelMatchFilter.test4.2.xml000644 001750 001750 00000003007 14353331212 031455 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/filters.LevelMatchFilter.test4.1.xml000644 001750 001750 00000003007 14353331212 031454 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/filters.LevelMatchFilter.test4.3.xml000644 001750 001750 00000003010 14353331212 031450 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/filters.LevelMatchFilter.test4.0.xml000644 001750 001750 00000003010 14353331212 031445 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/smtpAppender1.xml000644 001750 001750 00000003043 14353331212 026135 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/customLogger2.xml000644 001750 001750 00000003251 14353331212 026147 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/DOMTestCase3.xml000644 001750 001750 00000002532 14353331212 025552 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/odbcAppenderDSN-Log4cxxTest.xml000644 001750 001750 00000004400 14424433562 030543 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/customLevel1.xml000644 001750 001750 00000002540 14353331212 025776 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/DOMTestCase2.xml000644 001750 001750 00000003406 14353331212 025552 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/filters.LevelMatchFilter.test4.4.xml000644 001750 001750 00000003010 14353331212 031451 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/customLevel2.xml000644 001750 001750 00000003124 14353331212 025776 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/asyncAppender1.xml000644 001750 001750 00000002515 14353331212 026272 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/fallback2.xml000644 001750 001750 00000005027 14354342764 025256 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/defaultInit.xml000644 001750 001750 00000002374 14353331212 025670 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/customLogger1.xml000644 001750 001750 00000002626 14353331212 026153 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/xml/fluent-bit.xml000644 001750 001750 00000002311 14424033175 025466 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/rolling/000755 001750 001750 00000000000 14424433605 023546 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/rolling/time1.xml000644 001750 001750 00000003434 14353331212 025303 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/rolling/rollingFileAppenderFromProperties.properties000644 001750 001750 00000003045 14353331212 034504 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/rolling/obsoleteERFA1.properties000644 001750 001750 00000002643 14353331212 030214 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/rolling/filter1.xml000644 001750 001750 00000004164 14353331212 025633 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/rolling/obsoleteDRFA1.properties000644 001750 001750 00000002604 14353331212 030210 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/rolling/obsoleteRFA1.properties000644 001750 001750 00000002630 14354342764 030122 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/socketServer5.properties000644 001750 001750 00000002216 14353331212 026753 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/hierarchyThreshold6.properties000644 001750 001750 00000002045 14353331212 030130 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/ndc/000755 001750 001750 00000000000 14424433605 022644 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/ndc/NDC1.properties000644 001750 001750 00000002463 14353331212 025444 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout2.properties000644 001750 001750 00000002156 14353331212 027147 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/hierarchyThreshold8.properties000644 001750 001750 00000002046 14353331212 030133 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/autoConfigureTest.properties000644 001750 001750 00000002142 14353331212 027657 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/hierarchyThreshold2.properties000644 001750 001750 00000002045 14353331212 030124 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/hierarchyThreshold3.properties000644 001750 001750 00000002045 14353331212 030125 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout9.properties000644 001750 001750 00000002135 14353331212 027153 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout4.properties000644 001750 001750 00000002151 14353331212 027144 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout8.properties000644 001750 001750 00000002140 14353331212 027146 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/defaultInit3.properties000644 001750 001750 00000002037 14353331212 026543 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/l7d1.properties000644 001750 001750 00000002114 14353331212 024753 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/socketServer1.properties000644 001750 001750 00000002171 14353331212 026747 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/hierarchyThreshold5.properties000644 001750 001750 00000002044 14353331212 030126 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/locationdisabled.properties000644 001750 001750 00000002152 14353331212 027506 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/socketServer8.properties000644 001750 001750 00000002221 14353331212 026752 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/propertiestestcase-crlf.properties000644 001750 001750 00000001633 14353331212 031065 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/decoding/000755 001750 001750 00000000000 14424433605 023654 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/input/decoding/UTF-16LE.txt000644 001750 001750 00000000020 14353331212 025500 0ustar00robertrobert000000 000000 A0 N apache-log4cxx-1.1.0/src/test/resources/input/decoding/UTF-16.txt000644 001750 001750 00000000022 14353331212 025261 0ustar00robertrobert000000 000000 A0 N apache-log4cxx-1.1.0/src/test/resources/input/decoding/UTF-8.txt000644 001750 001750 00000000020 14353331212 025200 0ustar00robertrobert000000 000000 A؅԰আ七Ѐ ¹apache-log4cxx-1.1.0/src/test/resources/input/decoding/latin1.txt000644 001750 001750 00000000010 14353331212 025564 0ustar00robertrobert000000 000000 A????? apache-log4cxx-1.1.0/src/test/resources/input/decoding/UTF-16BE.txt000644 001750 001750 00000000020 14353331212 025466 0ustar00robertrobert000000 000000 A0 N apache-log4cxx-1.1.0/src/test/resources/input/decoding/ascii.txt000644 001750 001750 00000000010 14353331212 025464 0ustar00robertrobert000000 000000 A????? ?apache-log4cxx-1.1.0/src/test/resources/input/patternLayout.mdc.1.properties000644 001750 001750 00000002124 14353331212 027761 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/propertiestestcase-mixed.properties000644 001750 001750 00000001606 14353331212 031245 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout7.properties000644 001750 001750 00000002157 14353331212 027155 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/hierarchyThreshold4.properties000644 001750 001750 00000002044 14353331212 030125 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout5.properties000644 001750 001750 00000002173 14353331212 027151 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/socketServer6.properties000644 001750 001750 00000002221 14353331212 026750 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout14.properties000644 001750 001750 00000002125 14353331212 027226 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout12.properties000644 001750 001750 00000002136 14353331212 027226 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/input/patternLayout13.properties000644 001750 001750 00000002130 14353331212 027221 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/witness/000755 001750 001750 00000000000 14424433605 022435 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/patternLayout.13000644 001750 001750 00000000416 14354342764 025465 0ustar00robertrobert000000 000000 DEBUG - 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.1.0/src/test/resources/witness/patternLayout.9000644 001750 001750 00000000547 14353331212 025400 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/xmlLayout.3000644 001750 001750 00000001246 14353331212 024512 0ustar00robertrobert000000 000000 hi]]>]]> hi]]>]]> apache-log4cxx-1.1.0/src/test/resources/witness/patternLayout.1000644 001750 001750 00000000264 14353331212 025364 0ustar00robertrobert000000 000000 DEBUG - 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.1.0/src/test/resources/witness/hierarchyThreshold.8000644 001750 001750 00000000342 14353331212 026350 0ustar00robertrobert000000 000000 TRACE HierarchyThresholdTestCase = m0 DEBUG HierarchyThresholdTestCase = m1 INFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.1.0/src/test/resources/witness/patternLayout.4000644 001750 001750 00000000561 14353331212 025367 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/encoding/000755 001750 001750 00000000000 14424433605 024223 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/encoding/latin1.log000644 001750 001750 00000000053 14353331212 026104 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - INFO - A????? apache-log4cxx-1.1.0/src/test/resources/witness/encoding/UTF-16BE.log000644 001750 001750 00000000126 14353331212 026006 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - INFO - A0 N apache-log4cxx-1.1.0/src/test/resources/witness/encoding/UTF-8.log000644 001750 001750 00000000063 14353331212 025520 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - ¹ INFO - A؅԰আ七Ѐ apache-log4cxx-1.1.0/src/test/resources/witness/encoding/ascii.log000644 001750 001750 00000000053 14353331212 026004 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - ? INFO - A????? apache-log4cxx-1.1.0/src/test/resources/witness/encoding/UTF-16.log000644 001750 001750 00000000130 14353331212 025572 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - INFO - A0 N apache-log4cxx-1.1.0/src/test/resources/witness/encoding/UTF-16LE.log000644 001750 001750 00000000126 14353331212 026020 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - INFO - A0 N apache-log4cxx-1.1.0/src/test/resources/witness/NDCMatchFilter_deny000644 001750 001750 00000002225 14353331212 026117 0ustar00robertrobert000000 000000 pass 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.1.0/src/test/resources/witness/patternLayout.6000644 001750 001750 00000000561 14353331212 025371 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/patternLayout.12000644 001750 001750 00000000751 14353331212 025447 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/dom.A1.1000644 001750 001750 00000000707 14353331212 023532 0ustar00robertrobert000000 000000 DEBUG 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.1.0/src/test/resources/witness/l7d.1000644 001750 001750 00000002157 14353331212 023202 0ustar00robertrobert000000 000000 T1 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.1.0/src/test/resources/witness/hierarchyThreshold.3000644 001750 001750 00000000114 14353331212 026340 0ustar00robertrobert000000 000000 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.1.0/src/test/resources/witness/xmlLayout.null000644 001750 001750 00000000772 14353331212 025325 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/customLevel.3000644 001750 001750 00000000052 14353331212 025010 0ustar00robertrobert000000 000000 TRACE xml.CustomLevelTestCase - Message 5 apache-log4cxx-1.1.0/src/test/resources/witness/patternLayout.7000644 001750 001750 00000000561 14353331212 025372 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/socketServer.2000644 001750 001750 00000003666 14353331212 025202 0ustar00robertrobert000000 000000 TRACE 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.1.0/src/test/resources/witness/patternLayout.5000644 001750 001750 00000000561 14353331212 025370 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/socketServer.5000644 001750 001750 00000003501 14353331212 025171 0ustar00robertrobert000000 000000 TRACE 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.1.0/src/test/resources/witness/LevelRangeFilter_neutral000644 001750 001750 00000005234 14353331212 027300 0ustar00robertrobert000000 000000 DEBUG - 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.1.0/src/test/resources/witness/xmlLayout.mdc.1000644 001750 001750 00000000440 14353331212 025245 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/socketServer.7000644 001750 001750 00000003666 14353331212 025207 0ustar00robertrobert000000 000000 TRACE 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.1.0/src/test/resources/witness/xmlLayout.mdc.2000644 001750 001750 00000000534 14353331212 025252 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/socketServer.1000644 001750 001750 00000003435 14353331212 025173 0ustar00robertrobert000000 000000 TRACE 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.1.0/src/test/resources/witness/location1-good000644 001750 001750 00000000045 14353331212 025166 0ustar00robertrobert000000 000000 DEBUG(locationtest.cpp) - Message -1 apache-log4cxx-1.1.0/src/test/resources/witness/xmlLayout.1000644 001750 001750 00000005225 14353331212 024511 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/simple000644 001750 001750 00000000750 14353331212 023643 0ustar00robertrobert000000 000000 FATAL - 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.1.0/src/test/resources/witness/patternLayout.mdc.2000644 001750 001750 00000000727 14353331212 026133 0ustar00robertrobert000000 000000 starting 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.1.0/src/test/resources/witness/customLogger.1000644 001750 001750 00000000432 14353331212 025160 0ustar00robertrobert000000 000000 TRACE 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.1.0/src/test/resources/witness/socketServer.6000644 001750 001750 00000003666 14353331212 025206 0ustar00robertrobert000000 000000 TRACE 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.1.0/src/test/resources/witness/hierarchyThreshold.1000644 001750 001750 00000000000 14353331212 026330 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/patternLayout.2000644 001750 001750 00000000562 14353331212 025366 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/fallback1000644 001750 001750 00000000610 14353331212 024165 0ustar00robertrobert000000 000000 FALLBACK - 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.1.0/src/test/resources/witness/socketServer.3000644 001750 001750 00000003666 14353331212 025203 0ustar00robertrobert000000 000000 TRACE 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.1.0/src/test/resources/witness/patternLayout.11000644 001750 001750 00000000600 14353331212 025437 0ustar00robertrobert000000 000000 DEBUG [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.1.0/src/test/resources/witness/socketServer.8000644 001750 001750 00000003743 14353331212 025204 0ustar00robertrobert000000 000000 TRACE 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.1.0/src/test/resources/witness/patternLayout.3000644 001750 001750 00000000561 14353331212 025366 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/rolling/000755 001750 001750 00000000000 14424433605 024103 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test4.2000644 001750 001750 00000000102 14353331212 025777 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test1.0000644 001750 001750 00000000000 14353331212 025767 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test1.2000644 001750 001750 00000000102 14353331212 025774 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test5.1000644 001750 001750 00000000102 14353331212 025777 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test5.0000644 001750 001750 00000000041 14353331212 026000 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---6 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test2.1000644 001750 001750 00000000102 14353331212 025774 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test5.2000644 001750 001750 00000000102 14353331212 026000 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test6.0000644 001750 001750 00000000041 14353331212 026001 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---6 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test3.3000644 001750 001750 00000000041 14353331212 026001 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---4 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test4.3000644 001750 001750 00000000102 14353331212 026000 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---4 TimeBasedRollingTest - Hello---5 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/sbr-test3.1.gz000644 001750 001750 00000000104 14353331212 026415 0ustar00robertrobert000000 000000 (hAsbr-test3.1H5 ,#82L,38β,`bdapache-log4cxx-1.1.0/src/test/resources/witness/rolling/sbr-test3.0.gz000644 001750 001750 00000000104 14353331212 026414 0ustar00robertrobert000000 000000 $hAsbr-test3.0H54 ,#82L,38β,O dapache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test4.1000644 001750 001750 00000000102 14353331212 025776 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/sbr-test2.0000644 001750 001750 00000000144 14353331212 026000 0ustar00robertrobert000000 000000 Hello--10 Hello--11 Hello--12 Hello--13 Hello--14 Hello--15 Hello--16 Hello--17 Hello--18 Hello--19 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test2.3000644 001750 001750 00000000041 14353331212 026000 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---4 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/sbr-test3.log000644 001750 001750 00000000062 14353331212 026422 0ustar00robertrobert000000 000000 Hello--20 Hello--21 Hello--22 Hello--23 Hello--24 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/sbr-test4.log000644 001750 001750 00000000372 14353331212 026427 0ustar00robertrobert000000 000000 Hello---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.1.0/src/test/resources/witness/rolling/tbr-test2.2000644 001750 001750 00000000102 14353331212 025775 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test1.3000644 001750 001750 00000000041 14353331212 025777 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---4 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test1.1000644 001750 001750 00000000102 14353331212 025773 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test4.0000644 001750 001750 00000000041 14353331212 025777 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---6 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test5.3000644 001750 001750 00000000102 14353331212 026001 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---4 TimeBasedRollingTest - Hello---5 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/tbr-test2.0000644 001750 001750 00000000000 14353331212 025770 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/sbr-test2.1000644 001750 001750 00000000144 14353331212 026001 0ustar00robertrobert000000 000000 Hello---0 Hello---1 Hello---2 Hello---3 Hello---4 Hello---5 Hello---6 Hello---7 Hello---8 Hello---9 apache-log4cxx-1.1.0/src/test/resources/witness/rolling/sbr-test2.log000644 001750 001750 00000000062 14353331212 026421 0ustar00robertrobert000000 000000 Hello--20 Hello--21 Hello--22 Hello--23 Hello--24 apache-log4cxx-1.1.0/src/test/resources/witness/ndc/000755 001750 001750 00000000000 14424433605 023201 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/ndc/NDC.1000644 001750 001750 00000000637 14353331212 023665 0ustar00robertrobert000000 000000 DEBUG null - m1 INFO null - m2 WARN null - m3 ERROR null - m4 FATAL null - m5 DEBUG n1 - m1 INFO n1 - m2 WARN n1 - m3 ERROR n1 - m4 FATAL n1 - m5 DEBUG n1 n2 n3 - m1 INFO n1 n2 n3 - m2 WARN n1 n2 n3 - m3 ERROR n1 n2 n3 - m4 FATAL n1 n2 n3 - m5 DEBUG n1 n2 - m1 INFO n1 n2 - m2 WARN n1 n2 - m3 ERROR n1 n2 - m4 FATAL n1 n2 - m5 DEBUG null - m1 INFO null - m2 WARN null - m3 ERROR null - m4 FATAL null - m5 apache-log4cxx-1.1.0/src/test/resources/witness/socketServer.4000644 001750 001750 00000003470 14353331212 025175 0ustar00robertrobert000000 000000 TRACE 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.1.0/src/test/resources/witness/location1-disabled000644 001750 001750 00000000036 14353331212 026005 0ustar00robertrobert000000 000000 DEBUG[?](?)-1|?| - Message -1 apache-log4cxx-1.1.0/src/test/resources/witness/patternLayout.14000644 001750 001750 00000000606 14353331212 025450 0ustar00robertrobert000000 000000 DEBUG 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.1.0/src/test/resources/witness/customLevel.2000644 001750 001750 00000000322 14353331212 025007 0ustar00robertrobert000000 000000 DEBUG 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.1.0/src/test/resources/witness/NDCMatchFilter_accept000644 001750 001750 00000001103 14353331212 026411 0ustar00robertrobert000000 000000 pass 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.1.0/src/test/resources/witness/hierarchyThreshold.5000644 001750 001750 00000000226 14353331212 026346 0ustar00robertrobert000000 000000 INFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.1.0/src/test/resources/witness/LevelMatchFilter_accept000644 001750 001750 00000000405 14353331212 027060 0ustar00robertrobert000000 000000 DEBUG - 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.1.0/src/test/resources/witness/patternLayout.mdc.1000644 001750 001750 00000000055 14353331212 026124 0ustar00robertrobert000000 000000 DEBUG - Hello World {{key1,va11}{key2,va12}} apache-log4cxx-1.1.0/src/test/resources/witness/dom.A2.2000644 001750 001750 00000000676 14353331212 023541 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/customLevel.4000644 001750 001750 00000000322 14353331212 025011 0ustar00robertrobert000000 000000 DEBUG 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.1.0/src/test/resources/witness/patternLayout.8000644 001750 001750 00000000547 14353331212 025377 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/LevelMatchFilter_deny000644 001750 001750 00000001754 14353331212 026570 0ustar00robertrobert000000 000000 INFO - 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.1.0/src/test/resources/witness/xmlLayout.2000644 001750 001750 00000010527 14353331212 024513 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/test/resources/witness/dom.A1.2000644 001750 001750 00000000707 14353331212 023533 0ustar00robertrobert000000 000000 DEBUG 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.1.0/src/test/resources/witness/hierarchyThreshold.7000644 001750 001750 00000000342 14353331212 026347 0ustar00robertrobert000000 000000 TRACE HierarchyThresholdTestCase = m0 DEBUG HierarchyThresholdTestCase = m1 INFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.1.0/src/test/resources/witness/hierarchyThreshold.2000644 001750 001750 00000000046 14353331212 026343 0ustar00robertrobert000000 000000 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.1.0/src/test/resources/witness/hierarchyThreshold.6000644 001750 001750 00000000274 14353331212 026352 0ustar00robertrobert000000 000000 DEBUG HierarchyThresholdTestCase = m1 INFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.1.0/src/test/resources/witness/dom.A2.1000644 001750 001750 00000000676 14353331212 023540 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/LevelRangeFilter_accept000644 001750 001750 00000005234 14353331212 027065 0ustar00robertrobert000000 000000 DEBUG - 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.1.0/src/test/resources/witness/customLogger.2000644 001750 001750 00000000057 14353331212 025164 0ustar00robertrobert000000 000000 TRACE customLogger.XLoggerTestCase - Message 0 apache-log4cxx-1.1.0/src/test/resources/witness/hierarchyThreshold.4000644 001750 001750 00000000161 14353331212 026343 0ustar00robertrobert000000 000000 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.1.0/src/test/resources/witness/threadnametestcase.1000644 001750 001750 00000000025 14424032606 026354 0ustar00robertrobert000000 000000 FooName Test message apache-log4cxx-1.1.0/src/test/resources/witness/patternLayout.10000644 001750 001750 00000000751 14353331212 025445 0ustar00robertrobert000000 000000 [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.1.0/src/test/resources/witness/customLevel.1000644 001750 001750 00000000322 14353331212 025006 0ustar00robertrobert000000 000000 DEBUG 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.1.0/src/test/resources/L7D_fr_CH.properties000644 001750 001750 00000001545 14353331212 024503 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/test/resources/L7D_en_US.properties000644 001750 001750 00000001603 14353331212 024526 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.1.0/src/cmake/000755 001750 001750 00000000000 14424433605 017030 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/cmake/FindAPR.cmake000644 001750 001750 00000005370 14353331212 021252 0ustar00robertrobert000000 000000 # 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() 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() endif() find_package_handle_standard_args(APR APR_INCLUDE_DIR APR_LIBRARIES) apache-log4cxx-1.1.0/src/cmake/win32_target_environment_path.cmake000644 001750 001750 00000002641 14354342764 026014 0ustar00robertrobert000000 000000 # 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}\;) 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.1.0/src/cmake/pthread/000755 001750 001750 00000000000 14424433605 020457 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/cmake/pthread/test-pthread-setname.cpp000644 001750 001750 00000000126 14353331212 025210 0ustar00robertrobert000000 000000 #include int main(){ pthread_t tid; pthread_setname_np(tid, "name"); } apache-log4cxx-1.1.0/src/cmake/pthread/log4cxx-pthread.cmake000644 001750 001750 00000000570 14353331212 024470 0ustar00robertrobert000000 000000 include(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.1.0/src/cmake/pthread/test-pthread-getname.cpp000644 001750 001750 00000000170 14353331212 025173 0ustar00robertrobert000000 000000 #include int main(){ pthread_t tid; char buffer[16]; pthread_getname_np(tid, buffer, sizeof(buffer)); } apache-log4cxx-1.1.0/src/cmake/FindAPR-Util.cmake000644 001750 001750 00000005220 14353331212 022157 0ustar00robertrobert000000 000000 # 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.1.0/src/cmake/FindODBC.cmake000644 001750 001750 00000002777 14424032606 021353 0ustar00robertrobert000000 000000 # 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 'yes' if found 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) else() set(odbc_FOUND 0) endif() #message("odbc_FOUND=${odbc_FOUND}") if(odbc_FOUND) 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() 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.1.0/src/cmake/SQLAllocHandleTest.cpp000644 001750 001750 00000000551 14424032606 023117 0ustar00robertrobert000000 000000 // 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.1.0/src/cmake/boost-fallback/000755 001750 001750 00000000000 14424433605 021713 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/cmake/boost-fallback/test-boostatomic.cpp000644 001750 001750 00000000131 14353331212 025702 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ boost::atomic b; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/test-stdsharedptr.cpp000644 001750 001750 00000000167 14353331212 026077 0ustar00robertrobert000000 000000 #include struct foo{ int x; }; int main(int argc, char** argv){ std::shared_ptr fooptr; return 0; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/boost-std-configuration.h.cmake000644 001750 001750 00000002332 14354342764 027735 0ustar00robertrobert000000 000000 #ifndef BOOST_STD_CONFIGURATION_H #define BOOST_STD_CONFIGURATION_H #cmakedefine01 STD_SHARED_MUTEX_FOUND #cmakedefine01 Boost_SHARED_MUTEX_FOUND #cmakedefine01 STD_FILESYSTEM_FOUND #cmakedefine01 Boost_FILESYSTEM_FOUND #cmakedefine01 STD_EXPERIMENTAL_FILESYSTEM_FOUND #if STD_SHARED_MUTEX_FOUND #include namespace ${NAMESPACE_ALIAS} { typedef std::shared_mutex shared_mutex; template using shared_lock = std::shared_lock; } #elif Boost_SHARED_MUTEX_FOUND #include namespace ${NAMESPACE_ALIAS} { typedef boost::shared_mutex shared_mutex; template using shared_lock = boost::shared_lock; } #endif #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.1.0/src/cmake/boost-fallback/test-boostthread.cpp000644 001750 001750 00000000136 14353331212 025702 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ boost::thread th; return 0; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/test-stdmutex.cpp000644 001750 001750 00000000123 14353331212 025235 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ std::mutex mutex; return 0; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/test-boostmutex.cpp000644 001750 001750 00000000140 14353331212 025570 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ boost::mutex mutex; return 0; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/test-boostsharedmutex.cpp000644 001750 001750 00000000162 14353331212 026763 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ boost::shared_mutex mtx; return 0; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/test-boostfilesystem.cpp000644 001750 001750 00000000141 14354342764 026632 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ boost::filesystem::path p; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/test-stdthread.cpp000644 001750 001750 00000000122 14353331212 025341 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ std::thread th; return 0; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/test-stdexpfilesystem.cpp000644 001750 001750 00000000157 14354342764 027022 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ std::experimental::filesystem::path p; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/boost-fallback.cmake000644 001750 001750 00000013167 14424032606 025604 0ustar00robertrobert000000 000000 #include(${CMAKE_MODULE_PATH}/FindPackageHandleStandardArgs.cmake) # Checks for classes in std::, falling back to boost if the requested # classes are not available # # Available classes to check for: # thread # mutex # shared_mutex # filesystem # # Variables set: # ${prefix}_ #function(_boost_fallback_thread) # try_compile(HAS_STD_THREAD "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" # "${CMAKE_CURRENT_LIST_DIR}/test-stdthread.cpp") # find_package(boost_thread COMPONENTS thread) #endfunction() ## check for boost fallback instead of std:: classes ## arg1: prefix for variables to set ## arg2: list of classes to check for #function(boost_fallback prefix classes) #endfunction() # # This module checks for C++ standard classes and their boost counterparts # # Thread variables set: # STD_THREAD_FOUND - if std::thread is found # Boost_THREAD_FOUND - if boost::thread is found # # Mutex variables set: # STD_MUTEX_FOUND - if std::mutex is found # STD_SHARED_MUTEX_FOUND - if std::shared_mutex is found # Boost_MUTEX_FOUND - if boost::mutex is found # Boost_SHARED_MUTEX_FOUND - if boost::shared_mutex is found # # Smart pointer variables set: # STD_SHARED_PTR_FOUND - if std::shared_ptr is found # Boost_SHARED_PTR_FOUND - if boost::shared_ptr is found # # 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_THREAD_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-stdthread.cpp") try_compile(STD_MUTEX_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-stdmutex.cpp") try_compile(STD_SHARED_MUTEX_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-stdsharedmutex.cpp") try_compile(STD_SHARED_PTR_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-stdsharedptr.cpp") try_compile(STD_ATOMIC_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-stdatomic.cpp") 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") # We need to have all three boost components in order to run our tests # Boost thread requires chrono and atomic to work find_package(Boost COMPONENTS thread chrono atomic) if( ${Boost_FOUND} ) try_compile(Boost_SHARED_PTR_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-boostsharedptr.cpp") try_compile(Boost_MUTEX_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-boostmutex.cpp") try_compile(Boost_SHARED_MUTEX_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-boostsharedmutex.cpp" LINK_LIBRARIES Threads::Threads Boost::thread) try_compile(Boost_ATOMIC_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-boostatomic.cpp") endif( ${Boost_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} ) # Link the target with the appropriate boost libraries(if required) function(boostfallback_link target) if(NOT ${STD_THREAD_FOUND}) if(${Boost_THREAD_FOUND}) find_package(Boost COMPONENTS thread) target_link_libraries( ${target} PUBLIC Boost::thread) endif() endif() if(NOT ${STD_SHARED_MUTEX_FOUND}) if(${Boost_SHARED_MUTEX_FOUND}) find_package(Boost COMPONENTS thread) target_link_libraries( ${target} PUBLIC Boost::thread) endif() endif() endfunction() # Check for standard headers that we need, fall back to boost if they're not found set(NAMESPACE_ALIAS log4cxx) option(PREFER_BOOST "Prefer Boost over std:: equivalents" OFF) if( ${STD_THREAD_FOUND} AND NOT ${PREFER_BOOST} ) set( THREAD_IMPL "std::thread" ) elseif( ${Boost_THREAD_FOUND} ) set( THREAD_IMPL "boost::thread" ) else() set( THREAD_IMPL "NONE" ) endif() if( ${STD_MUTEX_FOUND} AND NOT ${PREFER_BOOST} ) set( MUTEX_IMPL "std::mutex" ) elseif( ${Boost_MUTEX_FOUND} ) set( MUTEX_IMPL "boost::mutex" ) else() set( MUTEX_IMPL "NONE" ) endif() if( ${STD_SHARED_PTR_FOUND} AND NOT ${PREFER_BOOST} ) set( SMART_PTR_IMPL "std::shared_ptr" ) elseif( ${Boost_SHARED_PTR_FOUND} ) set( SMART_PTR_IMPL "boost::shared_ptr" ) else() set( SMART_PTR_IMPL "NONE" ) endif() if( ${STD_SHARED_MUTEX_FOUND} AND NOT ${PREFER_BOOST} ) set( SHARED_MUTEX_IMPL "std::shared_mutex" ) elseif( ${Boost_SHARED_MUTEX_FOUND} ) set( SHARED_MUTEX_IMPL "boost::shared_mutex" ) else() set( SHARED_MUTEX_IMPL "NONE" ) endif() if( ${STD_ATOMIC_FOUND} AND NOT ${PREFER_BOOST} ) set( ATOMIC_IMPL "std::atomic" ) elseif( ${Boost_ATOMIC_FOUND} ) set( ATOMIC_IMPL "boost::atomic" ) else() set( ATOMIC_IMPL "NONE" ) 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.1.0/src/cmake/boost-fallback/test-boostsharedptr.cpp000644 001750 001750 00000000206 14353331212 026425 0ustar00robertrobert000000 000000 #include struct foo{ int x; }; int main(int argc, char** argv){ boost::shared_ptr fooptr; return 0; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/test-stdsharedmutex.cpp000644 001750 001750 00000000142 14353331212 026425 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ std::shared_mutex shared; return 0; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/test-stdatomic.cpp000644 001750 001750 00000000114 14353331212 025347 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ std::atomic b; } apache-log4cxx-1.1.0/src/cmake/boost-fallback/test-stdfilesystem.cpp000644 001750 001750 00000000124 14354342764 026277 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ std::filesystem::path p; } apache-log4cxx-1.1.0/src/cmake/FindESMTP.cmake000644 001750 001750 00000005030 14424032606 021515 0ustar00robertrobert000000 000000 # 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.1.0/src/cmake/compiler-features/000755 001750 001750 00000000000 14424433605 022456 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/cmake/compiler-features/test-unicode.cpp000644 001750 001750 00000000634 14424032606 025564 0ustar00robertrobert000000 000000 /* 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.1.0/src/cmake/compiler-features/test-thread-local.cpp000644 001750 001750 00000000263 14424032606 026473 0ustar00robertrobert000000 000000 #include std::string& getCurrentThreadVar() { thread_local std::string thread_id_string; return thread_id_string; } int main(){ getCurrentThreadVar() = "name"; } apache-log4cxx-1.1.0/src/cmake/compiler-features/check-compiler-support.cmake000644 001750 001750 00000001621 14424032606 030053 0ustar00robertrobert000000 000000 # This module checks compiler and standard library support # # Does the compiler support thread_local? try_compile(HAS_THREAD_LOCAL "${CMAKE_BINARY_DIR}/Testing/thread-local-test" "${CMAKE_CURRENT_LIST_DIR}/test-thread-local.cpp" CXX_STANDARD 11 ) # 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.1.0/src/cmake/compiler-features/test-make-unique.cpp000644 001750 001750 00000000134 14424032606 026352 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ std::make_unique(5); return 0; } apache-log4cxx-1.1.0/src/cmake/compiler-features/makeunique.h.cmake000644 001750 001750 00000000561 14424032606 026050 0ustar00robertrobert000000 000000 #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.1.0/src/cmake/projectVersionDetails.cmake000644 001750 001750 00000000403 14424037303 024344 0ustar00robertrobert000000 000000 # 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.1.0.0) set(log4cxx_ABI_VER 15) apache-log4cxx-1.1.0/src/main/000755 001750 001750 00000000000 14424433605 016674 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/cpp-qt/000755 001750 001750 00000000000 14424433605 020100 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/cpp-qt/configuration.cpp000644 001750 001750 00000010102 14424032606 023441 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 namespace log4cxx { namespace qt { using log4cxx::helpers::LogLog; static std::unique_ptr watcher; static QString configFilename; static void loadXMLFile(const QString& path){ QFileInfo fi(configFilename); if(!fi.exists()){ return; } log4cxx::xml::DOMConfigurator::configure(path.toStdString()); } static void loadPropertiesFile(const QString& path){ QFileInfo fi(configFilename); if(!fi.exists()){ return; } log4cxx::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::spi::ConfigurationStatus Configuration::tryLoadFile(const QString& filename){ log4cxx::spi::ConfigurationStatus stat =log4cxx::spi::ConfigurationStatus::NotConfigured; bool isXML = false; if(filename.endsWith(".xml")){ stat = log4cxx::xml::DOMConfigurator::configure(filename.toStdString()); isXML = true; }else if(filename.endsWith(".properties")){ stat = log4cxx::PropertyConfigurator::configure(filename.toStdString()); } if( stat == log4cxx::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); QString debugMsg = LOG4CXX_STR("Checking file "); debugMsg.append(canidate_str); LogLog::debug(debugMsg.toStdString()); if (candidate.exists()) { log4cxx::spi::ConfigurationStatus configStatus = tryLoadFile(canidate_str); if( configStatus == log4cxx::spi::ConfigurationStatus::Configured ){ return {configStatus, canidate_str}; } LogLog::debug("Unable to load file: trying next"); } } } return {log4cxx::spi::ConfigurationStatus::NotConfigured, QString()}; } } //namespace helpers } //namespace log4cxx apache-log4cxx-1.1.0/src/main/cpp-qt/CMakeLists.txt000644 001750 001750 00000003054 14354342764 022651 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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(LOG4CXX_QT_SUPPORT "Qt support/integration" OFF) # 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 configure_log4cxx) 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} ) endif( LOG4CXX_QT_SUPPORT) apache-log4cxx-1.1.0/src/main/cpp-qt/messagehandler.cpp000644 001750 001750 00000003604 14353331212 023561 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { namespace qt { void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message ) { log4cxx::LoggerPtr qtLogger = log4cxx::Logger::getLogger( context.category ); log4cxx::spi::LocationInfo location( context.file, log4cxx::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.1.0/src/main/CMakeLists.txt000644 001750 001750 00000002363 14353331212 021430 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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_QT_SUPPORT) target_include_directories(log4cxx-qt PUBLIC $ ) endif(LOG4CXX_QT_SUPPORT) apache-log4cxx-1.1.0/src/main/include/000755 001750 001750 00000000000 14424433605 020317 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/CMakeLists.txt000644 001750 001750 00000013222 14424032606 023053 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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(WIN32) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/log4cxx/version_info.h.in ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/version_info.h @ONLY ) set(LOG4CXX_CHAR "utf-8" CACHE STRING "Interal character representation, choice of utf-8, wchar_t(default), unichar") set_property(CACHE LOG4CXX_CHAR PROPERTY STRINGS "utf-8" "wchar_t" "unichar") set(LOGCHAR_IS_UNICHAR 0) set(LOGCHAR_IS_WCHAR 1) set(LOGCHAR_IS_UTF8 0) else() set(LOG4CXX_CHAR "utf-8" CACHE STRING "Interal character representation, choice of utf-8 (default), wchar_t, unichar") set_property(CACHE LOG4CXX_CHAR PROPERTY STRINGS "utf-8" "wchar_t" "unichar") set(LOGCHAR_IS_UNICHAR 0) set(LOGCHAR_IS_WCHAR 0) set(LOGCHAR_IS_UTF8 1) endif() # Configure log4cxx.h 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) elseif(${LOG4CXX_CHAR} STREQUAL "utf-8") 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_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() # Configure log4cxx_private.h set(LOG4CXX_CHARSET "locale" CACHE STRING "LogString characters, choice of locale (default), utf-8, ISO-8859-1, US-ASCII, EBCDIC") set_property(CACHE LOG4CXX_CHARSET PROPERTY STRINGS "locale" "utf-8" "ISO-8859-1" "US-ASCII" "EBCDIC") 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_FUNCTION_EXISTS(mbsrtowcs HAS_MBSRTOWCS) CHECK_FUNCTION_EXISTS(wcstombs HAS_WCSTOMBS) CHECK_FUNCTION_EXISTS(fwide HAS_FWIDE) CHECK_FUNCTION_EXISTS(syslog HAS_SYSLOG) if(UNIX) set(CMAKE_REQUIRED_LIBRARIES "pthread") CHECK_SYMBOL_EXISTS(pthread_sigmask "signal.h" HAS_PTHREAD_SIGMASK) # 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(UNIX) foreach(varName HAS_THREAD_LOCAL HAS_STD_LOCALE HAS_ODBC HAS_MBSRTOWCS HAS_WCSTOMBS HAS_FWIDE HAS_LIBESMTP HAS_SYSLOG 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 ) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/log4cxx/private/log4cxx_private.h.in ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/private/log4cxx_private.h @ONLY ) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/log4cxx/log4cxx.h.in ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/log4cxx.h @ONLY ) configure_file(${LOG4CXX_SOURCE_DIR}/src/cmake/boost-fallback/boost-std-configuration.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/private/boost-std-configuration.h ) # Provide the dependencies add_custom_target(configure_log4cxx COMMAND "${CMAKE_COMMAND}" -E echo "Checking configuration" ) apache-log4cxx-1.1.0/src/main/include/log4cxx/000755 001750 001750 00000000000 14424433605 021707 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/version_info.h.in000644 001750 001750 00000000562 14353331212 025160 0ustar00robertrobert000000 000000 // 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.1.0/src/main/include/log4cxx/asyncappender.h000644 001750 001750 00000012501 14354342764 024722 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #include #include #include #if defined(NON_BLOCKING) #include #endif namespace log4cxx { LOG4CXX_LIST_DEF(LoggingEventList, log4cxx::spi::LoggingEventPtr); /** The AsyncAppender lets users log events asynchronously. It uses a bounded buffer to store logging events.

The AsyncAppender will collect the events sent to it and then dispatch them to all the appenders that are attached to it. You can attach multiple appenders to an AsyncAppender.

The AsyncAppender uses a separate thread to serve the events in its bounded buffer.

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; /** * Set appender properties by name. * @param option property name. * @param value property value. */ 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.1.0/src/main/include/log4cxx/writerappender.h000644 001750 001750 00000012666 14354342764 025135 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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: LogString getEncoding() const; void setEncoding(const LogString& value); void setOption(const LogString& option, const LogString& value) override; /**

Sets the Writer where the log output will go. The specified Writer must be opened by the user and be writable.

The java.io.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::helpers::WriterPtr& writer); const log4cxx::helpers::WriterPtr getWriter() const; bool requiresLayout() const override; protected: /** Actual writing occurs here. */ virtual void subAppend(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p); /** Write a footer as produced by the embedded layout's Layout#appendFooter method. */ virtual void writeFooter(log4cxx::helpers::Pool& p); /** Write a header as produced by the embedded layout's Layout#appendHeader method. */ virtual void writeHeader(log4cxx::helpers::Pool& p); /** * Set the writer. Mutex must already be held. */ void setWriterInternal(const log4cxx::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.1.0/src/main/include/log4cxx/ndc.h000644 001750 001750 00000027256 14354342764 022647 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** the ndc class 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.

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 had a distinctive stamp. this is where ndcs come into play.

note that ndcs are managed on a per thread basis. ndc operations such as #push, #pop, #clear and #getDepth affect the ndc of the current thread only. ndcs of other threads remain unaffected.

for example, a servlet can build a per client request ndc consisting the clients host name and other information contained in the the request. cookies are another source of distinctive information. to build an ndc one uses the #push operation. simply put,

  • contexts can be nested.

  • when entering a context, call ndc.push. as a side effect, if there is no nested diagnostic context for the current thread, this method will create it.

  • when leaving a context, call ndc.pop.

  • when exiting a thread make sure to call #remove .

there is no penalty for forgetting to match each push operation with a corresponding pop, except the obvious mismatch between the real application context and the context set in the ndc.

if configured to do so, PatternLayout and TTCCLayout instances automatically retrieve the nested diagnostic context for the current thread without any user intervention. hence, even if a servlet is serving multiple clients simultaneously, the logs emanating from the same code (belonging to the same logger) can still be distinguished because each client request will have a different ndc tag.

heavy duty systems should call the #remove method when leaving the run method of a thread. this ensures that the memory used by the thread can be freed by the java garbage collector. there is a mechanism to lazily remove references to dead threads. in practice, this means that you can be a little sloppy and sometimes forget to call #remove before exiting a thread. */ class LOG4CXX_EXPORT NDC { public: /** * Pair of Message and FullMessage. */ typedef std::pair DiagnosticContext; typedef std::stack Stack; /** Creates a nested diagnostic context. Since java performs no automatic cleanup of objects when a scope is left, in log4j push() and pop() must be used to manage the NDC. For convenience, log4cxx provides an NDC constructor and destructor which simply call the push() and pop() methods, allowing for automatic cleanup when the current scope ends. @param message The new diagnostic context information. @see The #push method. */ NDC(const std::string& message); /** Removes the topmost element from the NDC stack. @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(); /** Pop top value off stack. @return top value. */ static LogString pop(); /** Pop top value off stack. @param buf to which top value is appended. @return true if NDC contained at least one value. */ static bool pop(std::string& buf); /** Looks at the last diagnostic context at the top of this NDC 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 innermost diagnostic context. */ static LogString peek(); /** Get top value without removing value. @param buf to which top value is appended. @return true if NDC contained at least one value. */ static bool peek(std::string& buf); /** Push new diagnostic context information for the current thread.

The contents of the message parameter is determined solely by the client. @param message The new diagnostic context information. */ static void push(const std::string& message); /** Push new diagnostic context information for the current thread.

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

Each thread that created a diagnostic context by calling #push should call this method before exiting. Otherwise, the memory used by the thread cannot be reclaimed by the VM.

As this is such an important problem in heavy duty systems and because it is difficult to always guarantee that the remove method is called before exiting a thread, this method has been augmented to lazily remove references to dead threads. In practice, this means that you can be a little sloppy and occasionally forget to call #remove before exiting a thread. However, you must call remove sometime. If you never call it, then your application is sure to run out of memory. */ static void remove(); #if LOG4CXX_WCHAR_T_API /** Creates a nested diagnostic context. Since java performs no automatic cleanup of objects when a scope is left, in log4j push() and pop() must be used to manage the NDC. For convenience, log4cxx provides an NDC constructor and destructor which simply call the push() and pop() methods, allowing for automatic cleanup when the current scope ends. @param message The new diagnostic context information. @see The #push method. */ NDC(const std::wstring& message); /** Push new diagnostic context information for the current thread.

The contents of the message parameter is determined solely by the client. @param message The new diagnostic context information. */ static void push(const std::wstring& message); /** * Appends the current NDC content to the provided string. * @param dst destination. * @return true if NDC value set. */ 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 /** Creates a nested diagnostic context. Since java performs no automatic cleanup of objects when a scope is left, in log4j push() and pop() must be used to manage the NDC. For convenience, log4cxx provides an NDC constructor and destructor which simply call the push() and pop() methods, allowing for automatic cleanup when the current scope ends. @param message The new diagnostic context information. @see The #push method. */ NDC(const std::basic_string& message); /** Push new diagnostic context information for the current thread.

The contents of the message parameter is determined solely by the client. @param message The new diagnostic context information. */ static void push(const std::basic_string& message); /** * Appends the current NDC content to the provided string. * @param dst destination. * @return true if NDC value set. */ static bool peek(std::basic_string& 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::basic_string& dst); #endif #if LOG4CXX_CFSTRING_API /** Creates a nested diagnostic context. Since java performs no automatic cleanup of objects when a scope is left, in log4j push() and pop() must be used to manage the NDC. For convenience, log4cxx provides an NDC constructor and destructor which simply call the push() and pop() methods, allowing for automatic cleanup when the current scope ends. @param message The new diagnostic context information. @see The #push method. */ NDC(const CFStringRef& message); /** Push new diagnostic context information for the current thread.

The contents of the message parameter is determined solely by the client. @param message The new diagnostic context information. */ static void push(const CFStringRef& message); /** * Gets the current NDC value. * @param dst destination. * @return true if NDC value set. */ static bool peek(CFStringRef& dst); /** * Gets and removes the current NDC value. * @param dst destination. * @return true if NDC value set. */ static bool pop(CFStringRef& dst); #endif private: NDC(const NDC&); NDC& operator=(const NDC&); static LogString& getMessage(DiagnosticContext& ctx); static LogString& getFullMessage(DiagnosticContext& ctx); }; // class NDC; } // namespace log4cxx #endif // _LOG4CXX_NDC_H apache-log4cxx-1.1.0/src/main/include/log4cxx/file.h000644 001750 001750 00000012317 14354342764 023012 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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 /** * 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::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::helpers::Pool& p) const; /** * Determines last modification date. * @param p pool. * @return length of file. */ log4cxx_time_t lastModified(log4cxx::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::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::helpers::Pool& p) const; /** * Delete file. * @param p pool. * @return true if file successfully deleted. */ bool deleteFile(log4cxx::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::helpers::Pool& p) const; /** * Get path of parent directory. * @param p pool. * @return path of parent directory. */ LogString getParent(log4cxx::helpers::Pool& p) const; /** * Make directories recursively. * @param p pool. * @return true if all requested directories existed or have been created. */ bool mkdirs(log4cxx::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::helpers::Pool& p) const; }; } // namespace log4cxx #define LOG4CXX_FILE(name) log4cxx::File(name) #endif // _LOG4CXX_FILE_H apache-log4cxx-1.1.0/src/main/include/log4cxx/defaultconfigurator.h000644 001750 001750 00000010616 14354342764 026142 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** * 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 filenamse 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::spi::ConfigurationStatus tryLoadFile(const LogString& filename); }; // class DefaultConfigurator } // namespace log4cxx #endif //_LOG4CXX_DEFAULT_CONFIGURATOR_H apache-log4cxx-1.1.0/src/main/include/log4cxx/helpers/000755 001750 001750 00000000000 14424433605 023351 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/helpers/timezone.h000644 001750 001750 00000003420 14354342764 025362 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/stringtokenizer.h000644 001750 001750 00000003005 14354342764 026770 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/propertyresourcebundle.h000644 001750 001750 00000003741 14354342764 030364 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/messagebuffer.h000644 001750 001750 00000052217 14354342764 026356 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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); /** * 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& (); /** * 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_CFSTRING_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& (); /** * 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& (); /** * 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); /** * 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 || 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 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); #endif #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. */ 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); /** * 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 || LOG4CXX_CFSTRING_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.1.0/src/main/include/log4cxx/helpers/xml.h000644 001750 001750 00000006472 14354342764 024342 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/fileoutputstream.h000644 001750 001750 00000004044 14354342764 027147 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::helpers::Pool& p); }; LOG4CXX_PTR_DEF(FileOutputStream); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_FILEOUTPUTSTREAM_H apache-log4cxx-1.1.0/src/main/include/log4cxx/helpers/datagramsocket.h000644 001750 001750 00000006651 14354342764 026532 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/bytearrayoutputstream.h000644 001750 001750 00000003645 14354342764 030240 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/datetimedateformat.h000644 001750 001750 00000002721 14353331212 027357 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/classregistration.h000644 001750 001750 00000002465 14353331212 027261 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/strftimedateformat.h000644 001750 001750 00000003342 14354342764 027437 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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.1.0/src/main/include/log4cxx/helpers/systemerrwriter.h000644 001750 001750 00000003262 14354342764 027026 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/properties.h000644 001750 001750 00000014210 14354342764 025723 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/strictmath.h000644 001750 001750 00000002634 14353331212 025701 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/outputstreamwriter.h000644 001750 001750 00000003777 14354342764 027560 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/writer.h000644 001750 001750 00000003077 14354342764 025054 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/filewatchdog.h000644 001750 001750 00000003702 14354342764 026173 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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*/; protected: FileWatchdog(const File& filename); virtual void doOnChange() = 0; void checkAndConfigure(); const File& file(); public: /** Set the delay to observe between each check of the file changes. */ void setDelay(long delay1); void start(); 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.1.0/src/main/include/log4cxx/helpers/cyclicbuffer.h000644 001750 001750 00000005124 14354342764 026173 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/resourcebundle.h000644 001750 001750 00000005102 14354342764 026550 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/system.h000644 001750 001750 00000003041 14353331212 025034 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/datagrampacket.h000644 001750 001750 00000007230 14354342764 026503 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/class.h000644 001750 001750 00000003017 14354342764 024637 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace helpers { class Object; class LOG4CXX_EXPORT Class { public: virtual ~Class(); virtual Object* newInstance() const; LogString toString() const; 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.1.0/src/main/include/log4cxx/helpers/outputstream.h000644 001750 001750 00000003160 14354342764 026305 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/simpledateformat.h000644 001750 001750 00000004355 14354342764 027100 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace helpers { namespace SimpleDateFormatImpl { class PatternToken; } LOG4CXX_LIST_DEF(PatternTokenList, log4cxx::helpers::SimpleDateFormatImpl::PatternToken*); /** * Concrete class for formatting and parsing dates in a * locale-sensitive manner. */ class LOG4CXX_EXPORT SimpleDateFormat : 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 */ SimpleDateFormat(const LogString& pattern); SimpleDateFormat(const LogString& pattern, const std::locale* locale); ~SimpleDateFormat(); virtual void format(LogString& s, log4cxx_time_t tm, log4cxx::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.1.0/src/main/include/log4cxx/helpers/exception.h000644 001750 001750 00000022130 14354342764 025525 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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 IOException& src); IOException& operator=(const IOException&); private: static LogString formatMessage(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.1.0/src/main/include/log4cxx/helpers/bytearrayinputstream.h000644 001750 001750 00000004523 14354342764 030033 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/aprinitializer.h000644 001750 001750 00000005620 14354342764 026562 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 extern "C" { typedef struct apr_thread_mutex_t apr_thread_mutex_t; typedef struct apr_threadkey_t apr_threadkey_t; struct apr_pool_t; } #include #include namespace log4cxx { namespace helpers { class FileWatchdog; class APRInitializer { public: static log4cxx_time_t initialize(); static apr_pool_t* getRootPool(); 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 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.1.0/src/main/include/log4cxx/helpers/onlyonceerrorhandler.h000644 001750 001750 00000005636 14354342764 030001 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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() LOG4CXX_CAST_ENTRY(spi::OptionHandler) LOG4CXX_CAST_ENTRY(spi::ErrorHandler) END_LOG4CXX_CAST_MAP() OnlyOnceErrorHandler(); ~OnlyOnceErrorHandler(); /** Does not do anything. */ void setLogger(const LoggerPtr& logger) override; /** No options to activate. */ void activateOptions(helpers::Pool& p) override; 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; }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_ONLY_ONCE_ERROR_HANDLER_H apache-log4cxx-1.1.0/src/main/include/log4cxx/helpers/threadspecificdata.h000644 001750 001750 00000003531 14354342764 027342 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace helpers { /** * This class contains all the thread-specific * data in use by log4cxx. */ class LOG4CXX_EXPORT ThreadSpecificData { public: ThreadSpecificData(); ~ThreadSpecificData(); /** * Gets current thread specific data. * @return thread specific data, may be null. */ static ThreadSpecificData* getCurrentData(); /** * Release this ThreadSpecficData if empty. */ void recycle(); static void put(const LogString& key, const LogString& val); static void push(const LogString& val); static void inherit(const log4cxx::NDC::Stack& stack); log4cxx::NDC::Stack& getStack(); log4cxx::MDC::Map& getMap(); private: static ThreadSpecificData& getDataNoThreads(); static ThreadSpecificData* createCurrentData(); LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(ThreadSpecificDataPrivate, m_priv) }; } // namespace helpers } // namespace log4cxx #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/helpers/object.h000644 001750 001750 00000012722 14354342764 025003 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #define DECLARE_LOG4CXX_CLAZZ_OBJECT(object)\ public:\ class Clazz##object : public helpers::Class\ {\ public:\ Clazz##object() : helpers::Class() {}\ virtual ~Clazz##object() {}\ virtual log4cxx::LogString getName() const { return LOG4CXX_STR(#object); } \ };\ static const helpers::Class& getStaticClass(); \ static const log4cxx::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::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::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::helpers::ClassRegistration& registerClass(); #define IMPLEMENT_LOG4CXX_OBJECT(object)\ const ::log4cxx::helpers::Class& object::getClass() const { return getStaticClass(); }\ const ::log4cxx::helpers::Class& object::getStaticClass() { \ static Clazz##object theClass; \ return theClass; \ } \ const log4cxx::helpers::ClassRegistration& object::registerClass() { \ static log4cxx::helpers::ClassRegistration classReg(object::getStaticClass); \ return classReg; \ }\ namespace log4cxx { namespace classes { \ const ::log4cxx::helpers::ClassRegistration& object##Registration = object::registerClass(); \ } } #define IMPLEMENT_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(object, class)\ const log4cxx::helpers::Class& object::getClass() const { return getStaticClass(); }\ const log4cxx::helpers::Class& object::getStaticClass() { \ static class theClass; \ return theClass; \ } \ const log4cxx::helpers::ClassRegistration& object::registerClass() { \ static log4cxx::helpers::ClassRegistration classReg(object::getStaticClass); \ return classReg; \ }\ namespace log4cxx { namespace classes { \ const log4cxx::helpers::ClassRegistration& object##Registration = object::registerClass(); \ } } namespace log4cxx { 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.1.0/src/main/include/log4cxx/helpers/bufferedwriter.h000644 001750 001750 00000003423 14354342764 026552 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/serversocket.h000644 001750 001750 00000003376 14354342764 026261 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/fileinputstream.h000644 001750 001750 00000005311 14354342764 026744 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/bytebuffer.h000644 001750 001750 00000003160 14354342764 025666 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/charsetdecoder.h000644 001750 001750 00000005724 14353331212 026501 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/absolutetimedateformat.h000644 001750 001750 00000002507 14353331212 030262 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/transcoder.h000644 001750 001750 00000016707 14354342764 025710 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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::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::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_CFSTRING_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); }; } } #define LOG4CXX_ENCODE_CHAR(var, src) \ std::string var; \ log4cxx::helpers::Transcoder::encode(src, var) #define LOG4CXX_DECODE_CHAR(var, src) \ log4cxx::LogString var; \ log4cxx::helpers::Transcoder::decode(src, var) #define LOG4CXX_DECODE_CFSTRING(var, src) \ log4cxx::LogString var; \ log4cxx::helpers::Transcoder::decode(src, var) #define LOG4CXX_ENCODE_CFSTRING(var, src) \ CFStringRef var = log4cxx::helpers::Transcoder::encode(src) #if LOG4CXX_LOGCHAR_IS_WCHAR #define LOG4CXX_ENCODE_WCHAR(var, src) \ const std::wstring& var = src #define LOG4CXX_DECODE_WCHAR(var, src) \ const log4cxx::LogString& var = src #else #define LOG4CXX_ENCODE_WCHAR(var, src) \ std::wstring var; \ log4cxx::helpers::Transcoder::encode(src, var) #define LOG4CXX_DECODE_WCHAR(var, src) \ log4cxx::LogString var; \ log4cxx::helpers::Transcoder::decode(src, var) #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR #define LOG4CXX_ENCODE_UNICHAR(var, src) \ const std::basic_string& var = src #define LOG4CXX_DECODE_UNICHAR(var, src) \ const log4cxx::LogString& var = src #else #define LOG4CXX_ENCODE_UNICHAR(var, src) \ std::basic_string var; \ log4cxx::helpers::Transcoder::encode(src, var) #define LOG4CXX_DECODE_UNICHAR(var, src) \ log4cxx::LogString var; \ log4cxx::helpers::Transcoder::decode(src, var) #endif #endif //_LOG4CXX_HELPERS_TRANSCODER_H apache-log4cxx-1.1.0/src/main/include/log4cxx/helpers/locale.h000644 001750 001750 00000003034 14354342764 024770 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/relativetimedateformat.h000644 001750 001750 00000002731 14353331212 030256 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::helpers::Pool& p) const; private: log4cxx_time_t startTime; }; } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_RELATIVE_TIME_DATE_FORMAT_H apache-log4cxx-1.1.0/src/main/include/log4cxx/helpers/loader.h000644 001750 001750 00000002462 14353331212 024764 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/socketoutputstream.h000644 001750 001750 00000003610 14354342764 027516 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/inputstream.h000644 001750 001750 00000003705 14353331212 026072 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/threadutility.h000644 001750 001750 00000010321 14354342764 026421 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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" namespace log4cxx { 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: ThreadUtility(); log4cxx::helpers::ThreadStartPre preStartFunction(); log4cxx::helpers::ThreadStarted threadStartedFunction(); log4cxx::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::helpers::ThreadStartPre pre_start = preStartFunction(); log4cxx::helpers::ThreadStarted thread_start = threadStartedFunction(); log4cxx::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.1.0/src/main/include/log4cxx/helpers/inetaddress.h000644 001750 001750 00000005120 14354342764 026034 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/integer.h000644 001750 001750 00000002417 14353331212 025153 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/dateformat.h000644 001750 001750 00000004730 14353331212 025644 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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::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.1.0/src/main/include/log4cxx/helpers/tchar.h000644 001750 001750 00000016260 14353331212 024620 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/main/include/log4cxx/helpers/iso8601dateformat.h000644 001750 001750 00000002773 14353331212 026703 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/cacheddateformat.h000644 001750 001750 00000013045 14354342764 027012 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace pattern { class LOG4CXX_EXPORT CachedDateFormat : public log4cxx::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::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::helpers::DateFormatPtr& formatter, log4cxx::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::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::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::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.1.0/src/main/include/log4cxx/helpers/systemoutwriter.h000644 001750 001750 00000003251 14354342764 027043 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/charsetencoder.h000644 001750 001750 00000006501 14353331212 026505 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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); } 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.1.0/src/main/include/log4cxx/helpers/socket.h000644 001750 001750 00000004410 14354342764 025020 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/reader.h000644 001750 001750 00000003376 14353331212 024765 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/inputstreamreader.h000644 001750 001750 00000005420 14363267433 027267 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 namespace log4cxx { namespace helpers { // Instantiate template pointer types passed as parameters LOG4CXX_INSTANTIATE_EXPORTED_PTR(InputStream); LOG4CXX_INSTANTIATE_EXPORTED_PTR(CharsetDecoder); /** * 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.1.0/src/main/include/log4cxx/helpers/optionconverter.h000644 001750 001750 00000013257 14354342764 027001 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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); /** If value is "true", then true is returned. If value is "false", then true is returned. Otherwise, default is returned.

Case of value is unimportant. */ static bool toBoolean(const LogString& value, bool dEfault); static int toInt(const LogString& value, int dEfault); static long toFileSize(const LogString& value, long dEfault); 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.1.0/src/main/include/log4cxx/helpers/transform.h000644 001750 001750 00000004150 14353331212 025525 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace helpers { /** Utility class for transforming strings. */ class LOG4CXX_EXPORT Transform { public: /** * This method takes a string which may contain HTML tags (ie, * <b>, <table>, etc) and replaces 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. * @return The input string with the characters '<' and '>' replaced with * &lt; and &gt; respectively. * */ static void appendEscapingTags( LogString& buf, const LogString& input); /** * Ensures that embeded CDEnd strings (]]>) are handled properly * within 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.1.0/src/main/include/log4cxx/helpers/stringhelper.h000644 001750 001750 00000003761 14354342764 026246 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::helpers::Pool& pool, LogString& dst); static void toString(int64_t i, log4cxx::helpers::Pool& pool, LogString& dst); static void toString(size_t i, log4cxx::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.1.0/src/main/include/log4cxx/helpers/date.h000644 001750 001750 00000004164 14353331212 024434 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/syslogwriter.h000644 001750 001750 00000002742 14354342764 026313 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/loglog.h000644 001750 001750 00000006232 14354342764 025017 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 namespace log4cxx { 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) LogLog(); LogLog(const LogLog&); LogLog& operator=(const LogLog&); static LogLog& getInstance(); public: ~LogLog(); /** 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) { \ log4cxx::helpers::LogLog::debug(log) ; } #define LOGLOG_WARN(log) { \ log4cxx::helpers::LogLog::warn(log) ; } #define LOGLOG_ERROR(log) { \ log4cxx::helpers::LogLog::warn(log); } #endif //_LOG4CXX_HELPERS_LOG_LOG_H apache-log4cxx-1.1.0/src/main/include/log4cxx/helpers/pool.h000644 001750 001750 00000003034 14353331212 024463 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::helpers::Pool&); Pool& operator=(const Pool&); }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_POOL_H apache-log4cxx-1.1.0/src/main/include/log4cxx/helpers/threadlocal.h000644 001750 001750 00000004161 14353331212 025776 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/helpers/appenderattachableimpl.h000644 001750 001750 00000006071 14354342764 030226 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #include #include namespace log4cxx { 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. * @param pool pool, must be longer-lived than instance. */ AppenderAttachableImpl(Pool& pool); ~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::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.1.0/src/main/include/log4cxx/appenderskeleton.h000644 001750 001750 00000011410 14424033175 025416 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** * 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::helpers::Pool& p) = 0; void doAppendImpl(const spi::LoggingEventPtr& event, log4cxx::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(); /** Derived appenders should override this method if option structure requires it. */ void activateOptions(helpers::Pool& /* pool */) override {} 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.1.0/src/main/include/log4cxx/logmanager.h000644 001750 001750 00000017166 14354342764 024216 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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}. * When the LogManager class is loaded * into memory the default initialization procedure is inititated. */ 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 DefaultLoggerFactory 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); /** Does the logger \c name exist in the hierarchy? */ 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 DefaultLoggerFactory 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); /** Does the logger \c name exist in the hierarchy? */ 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 DefaultLoggerFactory 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); /** Does the logger \c name exist in the hierarchy? */ 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 DefaultLoggerFactory 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); /** Does the logger \c name exist in the hierarchy? */ static LoggerPtr exists(const CFStringRef& name); #endif /** Retrieve the \c name Logger instance from the {@link spi::LoggerRepository LoggerRepository} using DefaultLoggerFactory 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); /** Does the logger \c name exist in the hierarchy? */ 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}61 to their default. */ static void resetConfiguration(); }; // class LogManager } // namespace log4cxx #endif //_LOG4CXX_LOG_MANAGER_H apache-log4cxx-1.1.0/src/main/include/log4cxx/nt/000755 001750 001750 00000000000 14424433605 022330 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/nt/nteventlogappender.h000644 001750 001750 00000005640 14354342764 026421 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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(); void activateOptions(helpers::Pool& p) override; void close() override; 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.1.0/src/main/include/log4cxx/nt/outputdebugstringappender.h000644 001750 001750 00000003000 14354342764 030016 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/nt/EventLogCategories.mc000644 001750 001750 00000002016 14353331212 026371 0ustar00robertrobert000000 000000 ; ; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, ; software distributed under the License is distributed on an ; "AS IS" BASIS, WITHOUT 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.1.0/src/main/include/log4cxx/spi/000755 001750 001750 00000000000 14424433605 022502 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/spi/loggingevent.h000644 001750 001750 00000013520 14354342764 025353 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace helpers { class ObjectOutputStream; } namespace spi { LOG4CXX_LIST_DEF(KeySet, LogString); /** The internal representation of logging events. When an affirmative decision is made to log then a LoggingEvent instance is created. This instance is passed around to the different log4cxx components.

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; /** For serialization only */ LoggingEvent(); /** Instantiate a LoggingEvent from the supplied parameters.

Except timeStamp all the other fields of LoggingEvent are filled when actually needed.

@param logger The logger of this event. @param level The level of this event. @param message The message of this event. @param location location of logging request. */ LoggingEvent(const LogString& logger, const LevelPtr& level, const LogString& message, const log4cxx::spi::LocationInfo& location); ~LoggingEvent(); /** Return the level of this event. */ const LevelPtr& getLevel() const; /** Return the name of the logger. */ const LogString& getLoggerName() const; /** Return the message for this logging event. */ const LogString& getMessage() const; /** Return the message for this logging event. */ const LogString& getRenderedMessage() const; /**Returns the time when the application started, in microseconds elapsed since 01.01.1970. */ static log4cxx_time_t getStartTime(); /** Return the threadName of this event. */ const LogString& getThreadName() const; /** * Get the user name of the thread. The default name is (noname) if * Log4cxx is unable to retrieve the name using a platform-specific call. */ const LogString& getThreadUserName() const; /** The number of microseconds elapsed from 01.01.1970 until logging event was created. */ log4cxx_time_t getTimeStamp() const; std::chrono::time_point getChronoTimeStamp() const; /* Return the file where this log statement was written. */ const log4cxx::spi::LocationInfo& getLocationInformation() const; /** * This method appends the NDC for this event to passed string. It will return the * correct content even if the event was generated in a different * thread or even on a different machine. The NDC#get method * should never be called directly. * * @param dest destination for NDC, unchanged if NDC is not set. * @return true if NDC is set. */ bool getNDC(LogString& dest) const; /** * Appends the the context corresponding to the key parameter. * If there is a local MDC copy, possibly because we are in a logging * server or running inside AsyncAppender, then we search for the key in * MDC copy, if a value is found it is returned. Otherwise, if the search * in MDC copy returns an empty result, then the current thread's * MDC is used. * *

* Note that both the local MDC copy and the current thread's MDC * are searched. *

* @param key key. * @param dest string to which value, if any, is appended. * @return true if key had a corresponding value. */ bool getMDC(const LogString& key, LogString& dest) const; /** * Returns the set of of the key values in the MDC for the event. * The returned set is unmodifiable by the caller. * * @return Set an unmodifiable set of the MDC keys. * */ KeySet getMDCKeySet() const; /** Obtain a copy of this thread's MDC prior to serialization or asynchronous logging. */ void getMDCCopy() const; /** * Return a previously set property. * @param key key. * @param dest string to which value, if any, is appended. * @return true if key had a corresponding value. */ bool getProperty(const LogString& key, LogString& dest) const; /** * Returns the set of of the key values in the properties * for the event. The returned set is unmodifiable by the caller. * * @return Set an unmodifiable set of the property keys. */ KeySet getPropertyKeySet() const; /** * Set a string property using a key and a string value. since 1.3 */ 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&); static const LogString& getCurrentThreadName(); static const LogString& getCurrentThreadUserName(); }; LOG4CXX_PTR_DEF(LoggingEvent); LOG4CXX_LIST_DEF(LoggingEventList, LoggingEventPtr); } } #endif //_LOG4CXX_SPI_LOGGING_EVENT_H apache-log4cxx-1.1.0/src/main/include/log4cxx/spi/configurator.h000644 001750 001750 00000003424 14354342764 025367 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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) /** 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 The hierarchy to operation upon. */ virtual ConfigurationStatus doConfigure(const File& configFileName, spi::LoggerRepositoryPtr repository) = 0; protected: Configurator(); private: Configurator(const Configurator&); Configurator& operator=(const Configurator&); }; LOG4CXX_PTR_DEF(Configurator); } } #endif // _LOG4CXX_SPI_CONFIGURATOR_H apache-log4cxx-1.1.0/src/main/include/log4cxx/spi/defaultrepositoryselector.h000644 001750 001750 00000003256 14354342764 030215 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/spi/repositoryselector.h000644 001750 001750 00000003471 14353331212 026630 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/spi/hierarchyeventlistener.h000644 001750 001750 00000003116 14354342764 027451 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class Logger; class Appender; namespace spi { /** Listen to events occuring within a Hierarchy.*/ class LOG4CXX_EXPORT HierarchyEventListener : public virtual log4cxx::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.1.0/src/main/include/log4cxx/spi/optionhandler.h000644 001750 001750 00000004253 14354342764 025534 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/spi/rootlogger.h000644 001750 001750 00000003622 14353331212 025031 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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(log4cxx::helpers::Pool& pool, const LevelPtr level); ~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.1.0/src/main/include/log4cxx/spi/triggeringeventevaluator.h000644 001750 001750 00000003234 14353331212 027773 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/spi/appenderattachable.h000644 001750 001750 00000004453 14354342764 026477 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #include namespace log4cxx { 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.1.0/src/main/include/log4cxx/spi/loggerrepository.h000644 001750 001750 00000007137 14354342764 026311 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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) virtual ~LoggerRepository() {} /** Add a {@link spi::HierarchyEventListener HierarchyEventListener} event to the repository. */ virtual void addHierarchyEventListener(const HierarchyEventListenerPtr& listener) = 0; /** * 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; virtual LoggerPtr getLogger(const LogString& name) = 0; virtual LoggerPtr getLogger(const LogString& name, const spi::LoggerFactoryPtr& factory) = 0; 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.1.0/src/main/include/log4cxx/spi/filter.h000644 001750 001750 00000007774 14354342764 024166 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::spi::FilterPtr getNext() const; void setNext(const log4cxx::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 }; /** Usually filters options become active when set. We provide a default do-nothing implementation for convenience. */ void activateOptions(helpers::Pool& p) override; 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.1.0/src/main/include/log4cxx/spi/loggerfactory.h000644 001750 001750 00000002543 14354342764 025535 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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: DECLARE_ABSTRACT_LOG4CXX_OBJECT(LoggerFactory) virtual ~LoggerFactory() {} virtual LoggerPtr makeNewLoggerInstance(helpers::Pool& pool, const LogString& name) const = 0; }; } // namespace spi } // namesapce log4cxx #endif //_LOG4CXX_SPI_LOGGERFACTORY_H apache-log4cxx-1.1.0/src/main/include/log4cxx/spi/errorhandler.h000644 001750 001750 00000007044 14354342764 025356 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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; }; LOG4CXX_PTR_DEF(ErrorHandler); } //namespace spi } //namespace log4cxx #endif //_LOG4CXX_SPI_ERROR_HANDLER_H apache-log4cxx-1.1.0/src/main/include/log4cxx/spi/location/000755 001750 001750 00000000000 14424433605 024312 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/spi/location/locationinfo.h000644 001750 001750 00000010745 14354342764 027165 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #if __cpp_lib_string_view || (_MSVC_LANG >= 201703L) #include #define LOG4CXX_HAS_STRING_VIEW #else #include #endif #if defined(_WIN32) #define LOG4CXX_SHORT_FILENAME_SPLIT_CHAR '\\' #else #define LOG4CXX_SHORT_FILENAME_SPLIT_CHAR '/' #endif namespace log4cxx { 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(); #ifdef LOG4CXX_HAS_STRING_VIEW static constexpr const char* calcShortFileName(const char* fileName){ std::string_view view(fileName); // If the separator is not found, rfind will return -1. Adding 1 to // that will have it pointing at fileName, which is a good fallback. return fileName + view.rfind(LOG4CXX_SHORT_FILENAME_SPLIT_CHAR) + 1; } #else static const char* calcShortFileName(const char* fileName){ const char* location = strrchr(fileName, LOG4CXX_SHORT_FILENAME_SPLIT_CHAR); return location == nullptr ? fileName : location + 1; } #endif /** * 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__ "" #endif #define LOG4CXX_LOCATION ::log4cxx::spi::LocationInfo(__FILE__, \ ::log4cxx::spi::LocationInfo::calcShortFileName(__FILE__), \ __LOG4CXX_FUNC__, \ __LINE__) #else #define LOG4CXX_LOCATION ::log4cxx::spi::LocationInfo::getLocationUnavailable() #endif // LOG4CXX_LOCATION #endif //_LOG4CXX_SPI_LOCATION_LOCATIONINFO_H apache-log4cxx-1.1.0/src/main/include/log4cxx/layout.h000644 001750 001750 00000004753 14354342764 023415 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** 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::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::helpers::Pool& p); /** Append the footer for the layout format. The base class does nothing. */ virtual void appendFooter(LogString& output, log4cxx::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, TTCCLayout, PatternLayout all return true. The {@link xml::XMLLayout XMLLayout} returns false. */ virtual bool ignoresThrowable() const = 0; }; LOG4CXX_PTR_DEF(Layout); } #endif // _LOG4CXX_LAYOUT_H apache-log4cxx-1.1.0/src/main/include/log4cxx/propertyconfigurator.h000644 001750 001750 00000032040 14354342764 026375 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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. See {@link PropertyConfigurator#doConfigure doConfigure} for the expected format.

It is sometimes useful to see how log4cxx is reading configuration files. You can enable log4cxx internal logging by defining the log4j.debug variable.

At class initialization time class, the file log4j.properties will be searched in the current directory. If the file can be found, then it will be fed to the {@link PropertyConfigurator#configure(const File& configFilename) configure} method.

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.

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 java.home system property is set to /home/xyz, then every occurrence of the sequence ${java.home} will be interpreted as /home/xyz. */ 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() LOG4CXX_CAST_ENTRY(spi::Configurator) END_LOG4CXX_CAST_MAP() PropertyConfigurator(); virtual ~PropertyConfigurator(); /** Read configuration from a file. The existing configuration is not cleared nor reset. If you require a different behavior, then call {@link LogManager#resetConfiguration resetConfiguration} method before calling doConfigure.

The configuration file consists of statements in the format key=value. The syntax of different configuration elements are discussed below.

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.

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
		

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 user manual for the meaning of the additivity flag.

Logger Factories

The usage of custom logger factories is discouraged and no longer documented.

Example

An example configuration is given below. Other configuration file examples are given in the examples folder.


		# 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 TTCC, using the
		# ISO8061 date format with context printing enabled.
		log4j.appender.A2=RollingFileAppender
		log4j.appender.A2.MaxFileSize=10MB
		log4j.appender.A2.MaxBackupIndex=1
		log4j.appender.A2.layout=TTCCLayout
		log4j.appender.A2.layout.ContextPrinting=enabled
		log4j.appender.A2.layout.DateFormat=ISO8601

		# 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
		

Refer to the setOption method in each Appender and Layout for class specific options.

Use the # or ! characters at the beginning of a line for comments.

@param configFileName The name of the configuration file where the configuration information is stored. @param hierarchy The hierarchy to operation upon. */ spi::ConfigurationStatus doConfigure(const File& configFileName, spi::LoggerRepositoryPtr hierarchy) override; /** Read configuration options from file configFilename. */ static spi::ConfigurationStatus configure(const File& configFilename); /** 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); /** Read the configuration file configFilename if it exists. Moreover, a thread will be created that will periodically check if configFilename has been created or modified. The period is determined by the delay argument. If a change or file creation is detected, then configFilename is read to configure log4j. @param configFilename A 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); /** Read configuration options from properties. See {@link PropertyConfigurator#doConfigure doConfigure} for the expected format. */ static spi::ConfigurationStatus configure(helpers::Properties& properties); /** Read configuration options from properties. See {@link PropertyConfigurator#doConfigure doConfigure} 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.1.0/src/main/include/log4cxx/provisionnode.h000644 001750 001750 00000002166 14353331212 024753 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class Logger; typedef std::shared_ptr LoggerPtr; typedef std::vector ProvisionNode; } // namespace log4cxx #endif //_LOG4CXX_PROVISION_NODE_H apache-log4cxx-1.1.0/src/main/include/log4cxx/net/000755 001750 001750 00000000000 14424433605 022475 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/net/smtpappender.h000644 001750 001750 00000022703 14424032606 025350 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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: ~~~{.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::helpers::Pool& p); /** Use evaluator passed as parameter as the spi::TriggeringEventEvaluator for this net::SMTPAppender. */ SMTPAppender(spi::TriggeringEventEvaluatorPtr evaluator); ~SMTPAppender(); /** Set options */ void setOption(const LogString& option, const LogString& value) override; /** Activate the specified options, such as the smtp host, the recipient, from, etc. */ 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::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::spi::TriggeringEventEvaluatorPtr getEvaluator() const; /** * Sets the triggering evaluator. * @param trigger triggering evaluator. */ void setEvaluator(log4cxx::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.1.0/src/main/include/log4cxx/net/telnetappender.h000644 001750 001750 00000007641 14354342764 025677 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #include #include #include #include namespace log4cxx { namespace helpers { class ByteBuffer; } namespace net { typedef log4cxx::helpers::SocketPtr Connection; LOG4CXX_LIST_DEF(ConnectionList, Connection); /**

The TelnetAppender is a log4cxx appender that specializes in writing to a read-only socket. The output is provided in a telnet-friendly way so that a log can be monitored over TCP/IP. Clients using telnet connect to the socket and receive log data. This is handy for remote monitoring, especially when monitoring a servlet.

Here is a list of the available configuration options:
Name Requirement Description Sample Value
Port optional This parameter determines the port to use for announcing log events. The default port is 23 (telnet). 5875
*/ class LOG4CXX_EXPORT TelnetAppender : public AppenderSkeleton { class SocketHandler; friend class SocketHandler; 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(); /** This appender requires a layout to format the text to the attached client(s). */ bool requiresLayout() const override { return true; } LogString getEncoding() const; void setEncoding(const LogString& value); /** all of the options have been set, create the socket handler and wait for connections. */ void activateOptions(helpers::Pool& p) override; /** Set options */ void setOption(const LogString& option, const LogString& value) override; /** Returns value of the Port option. */ int getPort() const; /** The Port option takes a positive integer representing the port where the server is waiting for connections. */ void setPort(int port1); /** shuts down the appender. */ void close() override; protected: /** Handles a log event. For this appender, that means writing the message to each connected client. */ void append(const spi::LoggingEventPtr& event, helpers::Pool& p) override; //---------------------------------------------------------- SocketHandler: private: // prevent copy and assignment statements TelnetAppender(const TelnetAppender&); TelnetAppender& operator=(const TelnetAppender&); void write(log4cxx::helpers::ByteBuffer&); void writeStatus(const log4cxx::helpers::SocketPtr& socket, const LogString& msg, log4cxx::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.1.0/src/main/include/log4cxx/net/syslogappender.h000644 001750 001750 00000011157 14354342764 025721 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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; /** This method returns immediately as options are activated when they are set. */ void activateOptions(helpers::Pool& p) override; 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.1.0/src/main/include/log4cxx/net/socketappenderskeleton.h000644 001750 001750 00000010753 14354342764 027437 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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); /** Connect 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(); void setOption(const LogString& option, const LogString& value) override; protected: SocketAppenderSkeleton(std::unique_ptr priv); virtual void setSocket(log4cxx::helpers::SocketPtr& socket, log4cxx::helpers::Pool& p) = 0; virtual void cleanUp(log4cxx::helpers::Pool& p) = 0; virtual int getDefaultDelay() const = 0; virtual int getDefaultPort() const = 0; private: void connect(log4cxx::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.1.0/src/main/include/log4cxx/net/xmlsocketappender.h000644 001750 001750 00000012530 14424033175 026375 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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.1.0/src/main/include/log4cxx/filter/000755 001750 001750 00000000000 14424433605 023174 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/filter/levelrangefilter.h000644 001750 001750 00000007530 14354342764 026713 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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(); /** Set options */ 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.1.0/src/main/include/log4cxx/filter/levelmatchfilter.h000644 001750 001750 00000005607 14354342764 026716 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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(); /** Set options */ 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.1.0/src/main/include/log4cxx/filter/locationinfofilter.h000644 001750 001750 00000005300 14354342764 027244 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::spi::Filter { struct LocationInfoFilterPrivate; public: DECLARE_LOG4CXX_OBJECT(LocationInfoFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LocationInfoFilter) LOG4CXX_CAST_ENTRY_CHAIN(log4cxx::spi::Filter) END_LOG4CXX_CAST_MAP() LocationInfoFilter(); ~LocationInfoFilter(); 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.1.0/src/main/include/log4cxx/filter/loggermatchfilter.h000644 001750 001750 00000006003 14354342764 027055 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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(); /** Set options */ 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.1.0/src/main/include/log4cxx/filter/denyallfilter.h000644 001750 001750 00000003756 14354342764 026225 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/filter/andfilter.h000644 001750 001750 00000006412 14354342764 025327 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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::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.1.0/src/main/include/log4cxx/filter/stringmatchfilter.h000644 001750 001750 00000005466 14354342764 027120 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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(); /** Set options */ 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.1.0/src/main/include/log4cxx/filter/propertyfilter.h000644 001750 001750 00000004143 14354342764 026450 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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::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.1.0/src/main/include/log4cxx/filter/mapfilter.h000644 001750 001750 00000004576 14354342764 025353 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace filter { /** * A Filter that operates on a Map and can be used like in the following example: *

 * <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::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::spi::Filter) END_LOG4CXX_CAST_MAP() MapFilter(); ~MapFilter(); /** Set options */ 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.1.0/src/main/include/log4cxx/filter/expressionfilter.h000644 001750 001750 00000007536 14354342764 026774 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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::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.1.0/src/main/include/log4cxx/db/000755 001750 001750 00000000000 14424433605 022274 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/db/odbcappender.h000644 001750 001750 00000021614 14424433562 025101 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #include #include namespace log4cxx { namespace db { class LOG4CXX_EXPORT SQLException : public log4cxx::helpers::Exception { public: SQLException(short fHandleType, void* hInput, const char* prolog, log4cxx::helpers::Pool& p); SQLException(const char* msg); SQLException(const SQLException& src); private: const char* formatMessage(short fHandleType, void* hInput, const char* prolog, log4cxx::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(); /** Set options */ 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::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::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::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::helpers::Pool& p); #endif static void encode(unsigned short** dest, const LogString& src, log4cxx::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.1.0/src/main/include/log4cxx/db/dbappender.h000644 001750 001750 00000015060 14424037161 024550 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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(); /** Set options */ 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.1.0/src/main/include/log4cxx/config/000755 001750 001750 00000000000 14424433605 023154 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/config/propertysetter.h000644 001750 001750 00000006533 14354342764 026456 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace helpers { class Object; // Instantiate template pointer type passed as parameter LOG4CXX_INSTANTIATE_EXPORTED_PTR(Object); LOG4CXX_PTR_DEF(Object); 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::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::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::helpers::Pool& p); void activate(log4cxx::helpers::Pool& p); }; // class PropertySetter } // namespace config; } // namespace log4cxx #endif //_LOG4CXX_CONFIG_PROPERTYSETTER_H apache-log4cxx-1.1.0/src/main/include/log4cxx/private/000755 001750 001750 00000000000 14424433605 023361 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/private/patternconverter_priv.h000644 001750 001750 00000002714 14354342764 030212 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/private/datagramsocket_priv.h000644 001750 001750 00000003011 14354342764 027565 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace helpers { struct DatagramSocket::DatagramSocketPriv { DatagramSocketPriv() : address(), localAddress(), port(0), localPort(0) { } DatagramSocketPriv(int localPort1) : address(), localAddress(), port(0), localPort(0) { } DatagramSocketPriv(int localPort1, InetAddressPtr localAddress1) : address(), localAddress(), port(0), localPort(0) { } 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.1.0/src/main/include/log4cxx/private/nteventlogappender_priv.h000644 001750 001750 00000000000 14354342764 030473 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/private/action_priv.h000644 001750 001750 00000002405 14354342764 026057 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace rolling { struct Action::ActionPrivate { ActionPrivate() : complete(false), interrupted(false), pool() {} virtual ~ActionPrivate(){} /** * Is action complete. */ bool complete; /** * Is action interrupted. */ bool interrupted; log4cxx::helpers::Pool pool; std::mutex mutex; }; } } #endif /* LOG4CXX_ACTION_PRIVATE_H */ apache-log4cxx-1.1.0/src/main/include/log4cxx/private/fileappender_priv.h000644 001750 001750 00000003551 14354342764 027243 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/private/odbcappender_priv.h000644 001750 001750 00000006472 14424033175 027227 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 namespace log4cxx { namespace db { struct ODBCAppender::ODBCAppenderPriv : public AppenderSkeleton::AppenderSkeletonPrivate { ODBCAppenderPriv() : AppenderSkeletonPrivate() , connection(0) , env(0) , preparedStatement(0) , bufferSize(1) , timeZone(helpers::TimeZone::getDefault()) {} /** * 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 }; } } #endif /* LOG4CXX_ODBCAPPENDER_PRIV */ apache-log4cxx-1.1.0/src/main/include/log4cxx/private/writerappender_priv.h000644 001750 001750 00000004567 14354342764 027650 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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" #ifndef _LOG4CXX_WRITERAPPENDER_PRIV_H #define _LOG4CXX_WRITERAPPENDER_PRIV_H namespace log4cxx { struct WriterAppender::WriterAppenderPriv : public AppenderSkeleton::AppenderSkeletonPrivate { WriterAppenderPriv() : AppenderSkeletonPrivate(), immediateFlush(true) {} WriterAppenderPriv(const LayoutPtr& layout1, log4cxx::helpers::WriterPtr& writer1) : AppenderSkeletonPrivate(layout1), immediateFlush(true), writer(writer1) { } WriterAppenderPriv(const LayoutPtr& layout1) : AppenderSkeletonPrivate(layout1), immediateFlush(true) { } /** 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::helpers::WriterPtr writer; }; } #endif /* _LOG4CXX_WRITERAPPENDER_PRIV_H */ apache-log4cxx-1.1.0/src/main/include/log4cxx/private/string_c11.h000644 001750 001750 00000003431 14424032606 025501 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.1.0/src/main/include/log4cxx/private/socketappenderskeleton_priv.h000644 001750 001750 00000004326 14354342764 031362 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 namespace log4cxx { namespace net { struct SocketAppenderSkeleton::SocketAppenderSkeletonPriv : public AppenderSkeletonPrivate { SocketAppenderSkeletonPriv(int defaultPort, int reconnectionDelay) : AppenderSkeletonPrivate(), remoteHost(), address(), port(defaultPort), reconnectionDelay(reconnectionDelay), locationInfo(false), thread() {} SocketAppenderSkeletonPriv(helpers::InetAddressPtr address, int defaultPort, int reconnectionDelay) : AppenderSkeletonPrivate(), remoteHost(), address(address), port(defaultPort), reconnectionDelay(reconnectionDelay), locationInfo(false), thread() {} SocketAppenderSkeletonPriv(const LogString& host, int port, int delay) : AppenderSkeletonPrivate(), remoteHost(host), address(helpers::InetAddress::getByName(host)), port(port), reconnectionDelay(delay), locationInfo(false), thread() {} /** 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; }; } // namespace net } // namespace log4cxx #endif /* LOG4CXX_SOCKETAPPENDERSKELETON_PRIVATE_H */ apache-log4cxx-1.1.0/src/main/include/log4cxx/private/aprsocket.h000644 001750 001750 00000002622 14354342764 025536 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/private/socket_priv.h000644 001750 001750 00000002315 14354342764 026072 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace helpers { struct Socket::SocketPrivate{ /** 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.1.0/src/main/include/log4cxx/private/appenderskeleton_priv.h000644 001750 001750 00000004155 14354342764 030151 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::helpers::Pool pool; mutable std::recursive_mutex mutex; }; } #endif /* _LOG4CXX_APPENDERSKELETON_PRIV */ apache-log4cxx-1.1.0/src/main/include/log4cxx/private/aprserversocket.h000644 001750 001750 00000002461 14354342764 026766 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/private/aprdatagramsocket.h000644 001750 001750 00000003223 14354342764 027235 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/private/serversocket_priv.h000644 001750 001750 00000002170 14354342764 027320 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace helpers { struct ServerSocket::ServerSocketPrivate{ ServerSocketPrivate() : timeout(0){} int timeout; }; } } #endif /* LOG4CXX_HELPERS_SERVERSOCKET_PRIV_H */ apache-log4cxx-1.1.0/src/main/include/log4cxx/private/log4cxx_private.h.in000644 001750 001750 00000004321 14424032606 027255 0ustar00robertrobert000000 000000 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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_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.1.0/src/main/include/log4cxx/private/syslogappender_priv.h000644 001750 001750 00000006146 14354342764 027647 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { 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.1.0/src/main/include/log4cxx/private/rollingpolicybase_priv.h000644 001750 001750 00000002716 14354342764 030330 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { namespace rolling{ struct RollingPolicyBase::RollingPolicyBasePrivate { /** * 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.1.0/src/main/include/log4cxx/private/filter_priv.h000644 001750 001750 00000002102 14354342764 026061 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace spi { struct Filter::FilterPrivate { virtual ~FilterPrivate(){} /** Points to the next filter in the filter chain. */ FilterPtr next; }; } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/xml/000755 001750 001750 00000000000 14424433605 022507 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/xml/domconfigurator.h000644 001750 001750 00000022020 14354342764 026065 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 extern "C" { struct apr_xml_doc; struct apr_xml_elem; } namespace log4cxx { 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, virtual public helpers::Object { public: ~DOMConfigurator(); protected: typedef std::map AppenderMap; /** Used internally to parse appenders by IDREF name. */ AppenderPtr findAppenderByName( log4cxx::helpers::Pool& p, log4cxx::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::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* appenderRef, apr_xml_doc* doc, AppenderMap& appenders); /** Used internally to parse an appender element. */ AppenderPtr parseAppender( log4cxx::helpers::Pool& p, log4cxx::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::helpers::Pool& p, log4cxx::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::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, std::vector& filters); /** Used internally to parse a logger element. */ void parseLogger( log4cxx::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* loggerElement, apr_xml_doc* doc, AppenderMap& appenders); /** Used internally to parse the logger factory element. */ void parseLoggerFactory( log4cxx::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* factoryElement); /** Used internally to parse the logger factory element. */ log4cxx::helpers::ObjectPtr parseTriggeringPolicy( log4cxx::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* factoryElement); /** Used internally to parse the logger factory element. */ log4cxx::rolling::RollingPolicyPtr parseRollingPolicy( log4cxx::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* factoryElement); /** Used internally to parse the root logger element. */ void parseRoot(log4cxx::helpers::Pool& p, log4cxx::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::helpers::Pool& p, log4cxx::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::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* layout_element); /** Used internally to parse a level element. */ void parseLevel( log4cxx::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, LoggerPtr logger, bool isRoot); void setParameter( log4cxx::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* elem, log4cxx::config::PropertySetter& propSetter); /** Used internally to configure the log4cxx framework from an in-memory representation of an XML document. */ void parse( log4cxx::helpers::Pool& p, log4cxx::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::helpers::Pool& p); /** A static version of #doConfigure. */ static spi::ConfigurationStatus configure(const std::string& filename); #if LOG4CXX_WCHAR_T_API static spi::ConfigurationStatus configure(const std::wstring& filename); #endif #if LOG4CXX_UNICHAR_API static spi::ConfigurationStatus configure(const std::basic_string& filename); #endif #if LOG4CXX_CFSTRING_API static spi::ConfigurationStatus configure(const CFStringRef& filename); #endif /** Like #configureAndWatch(const std::string& configFilename, long delay) except that the default delay as defined by log4cxx::helpers::FileWatchdog#DEFAULT_DELAY is used. @param configFilename A log4j configuration file in XML format. */ static spi::ConfigurationStatus configureAndWatch(const std::string& configFilename); #if LOG4CXX_WCHAR_T_API static spi::ConfigurationStatus configureAndWatch(const std::wstring& configFilename); #endif #if LOG4CXX_UNICHAR_API static spi::ConfigurationStatus configureAndWatch(const std::basic_string& configFilename); #endif #if LOG4CXX_CFSTRING_API 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. @param configFilename A log4j 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 static spi::ConfigurationStatus configureAndWatch(const std::wstring& configFilename, long delay); #endif #if LOG4CXX_UNICHAR_API static spi::ConfigurationStatus configureAndWatch(const std::basic_string& configFilename, long delay); #endif #if LOG4CXX_CFSTRING_API static spi::ConfigurationStatus configureAndWatch(const CFStringRef& configFilename, long delay); #endif /** Interpret the XML file pointed by filename and set up log4cxx accordingly.

The configuration is done relative to the hierarchy parameter. @param filename The file to parse. @param repository The hierarchy to operation upon. */ spi::ConfigurationStatus doConfigure(const File& filename, spi::LoggerRepositoryPtr repository) override; protected: static LogString getAttribute( log4cxx::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_XML_DOM_CONFIGURATOR_H apache-log4cxx-1.1.0/src/main/include/log4cxx/xml/xmllayout.h000644 001750 001750 00000006763 14354342764 024741 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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(); /** No options to activate. */ void activateOptions(helpers::Pool& /* p */) override { } /** Set options */ 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.1.0/src/main/include/log4cxx/rolling/000755 001750 001750 00000000000 14424433605 023355 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/rolling/filerenameaction.h000644 001750 001750 00000003052 14354342764 027042 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::helpers::Pool& pool) const override; }; LOG4CXX_PTR_DEF(FileRenameAction); } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/rolling/zipcompressaction.h000644 001750 001750 00000004174 14354342764 027317 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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.1.0/src/main/include/log4cxx/rolling/timebasedrollingpolicy.h000755 001750 001750 00000020062 14354342764 030304 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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(); 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; void setOption(const LogString& option, const LogString& value) override; protected: log4cxx::pattern::PatternMap getFormatSpecifiers() const override; private: /** * Generate mmap file */ int createMMapFile(const std::string& lastfilename, log4cxx::helpers::Pool& pool); /** * Detect if the mmap file is empty */ bool isMapFileEmpty(log4cxx::helpers::Pool& pool); /** * init MMapFile */ void initMMapFile(const LogString& lastFileName, log4cxx::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::helpers::Pool& pool); }; LOG4CXX_PTR_DEF(TimeBasedRollingPolicy); } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/rolling/multiprocessrollingfileappender.h000644 001750 001750 00000010560 14354342764 032236 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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(); 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) override; protected: /** Actual writing occurs here. */ void subAppend(const spi::LoggingEventPtr& event, helpers::Pool& p) override; bool rolloverInternal(log4cxx::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::helpers::Pool& p); friend class CountingOutputStream; }; LOG4CXX_PTR_DEF(MultiprocessRollingFileAppender); } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/rolling/manualtriggeringpolicy.h000644 001750 001750 00000004273 14354342764 030322 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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; void activateOptions(helpers::Pool&) override; void setOption(const LogString& option, const LogString& value) override; }; } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/rolling/rollingfileappender.h000644 001750 001750 00000016464 14354342764 027575 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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); void setOption( const LogString& option, const LogString& value ) override; /** Prepares RollingFileAppender for use. */ void activateOptions(helpers::Pool& 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(log4cxx::helpers::Pool& p); protected: /** Actual writing occurs here. */ void subAppend(const spi::LoggingEventPtr& event, helpers::Pool& p) override; bool rolloverInternal(log4cxx::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.1.0/src/main/include/log4cxx/rolling/action.h000644 001750 001750 00000003533 14354342764 025016 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace rolling { /** * A file system action performed as part of a rollover event. */ class Action : public virtual log4cxx::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::helpers::Pool& pool) const = 0; void run(log4cxx::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.1.0/src/main/include/log4cxx/rolling/gzcompressaction.h000644 001750 001750 00000004206 14354342764 027131 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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.1.0/src/main/include/log4cxx/rolling/rollingpolicy.h000644 001750 001750 00000005635 14354342764 026434 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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::helpers::Pool& pool) = 0; }; LOG4CXX_PTR_DEF(RollingPolicy); } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/rolling/rollingpolicybase.h000644 001750 001750 00000006206 14354342764 027262 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace rolling { LOG4CXX_LIST_DEF(PatternConverterList, log4cxx::pattern::PatternConverterPtr); LOG4CXX_LIST_DEF(FormattingInfoList, log4cxx::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(); void activateOptions(log4cxx::helpers::Pool& p) override; virtual log4cxx::pattern::PatternMap getFormatSpecifiers() const = 0; 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::pattern::PatternConverterPtr getIntegerPatternConverter() const; log4cxx::pattern::PatternConverterPtr getDatePatternConverter() const; }; LOG4CXX_PTR_DEF(RollingPolicyBase); } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/rolling/fixedwindowrollingpolicy.h000644 001750 001750 00000007774 14354342764 030712 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::helpers::Pool& p) const; public: FixedWindowRollingPolicy(); ~FixedWindowRollingPolicy(); void activateOptions(helpers::Pool& p) override; 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: log4cxx::pattern::PatternMap getFormatSpecifiers() const override; }; LOG4CXX_PTR_DEF(FixedWindowRollingPolicy); } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/rolling/filterbasedtriggeringpolicy.h000644 001750 001750 00000006067 14354342764 031334 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 namespace log4cxx { class File; namespace helpers { class Pool; } namespace rolling { // Instantiate template pointer types passed as parameters LOG4CXX_INSTANTIATE_EXPORTED_PTR(log4cxx::spi::Filter); /** * 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(); /** * Prepares the instance for use. */ void activateOptions(helpers::Pool&) override; void setOption(const LogString& option, const LogString& value) override; }; LOG4CXX_PTR_DEF(FilterBasedTriggeringPolicy); } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/rolling/triggeringpolicy.h000644 001750 001750 00000004417 14354342764 027124 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/rolling/rolloverdescription.h000644 001750 001750 00000004775 14354342764 027662 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace rolling { class RolloverDescription : public log4cxx::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.1.0/src/main/include/log4cxx/rolling/sizebasedtriggeringpolicy.h000644 001750 001750 00000004522 14354342764 031013 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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); void activateOptions(helpers::Pool&) override; void setOption(const LogString& option, const LogString& value) override; }; LOG4CXX_PTR_DEF(SizeBasedTriggeringPolicy); } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/htmllayout.h000644 001750 001750 00000006264 14354342764 024301 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** 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; /** No options to activate. */ void activateOptions(helpers::Pool& /* p */) override {} /** Set options */ 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.1.0/src/main/include/log4cxx/consoleappender.h000644 001750 001750 00000005323 14354342764 025253 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** * ConsoleAppender appends log events to stdout or * stderr using a layout specified by the user. The * default target is stdout. */ 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; void activateOptions(helpers::Pool& p) override; 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.1.0/src/main/include/log4cxx/fileappender.h000644 001750 001750 00000014377 14354342764 024541 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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; /**

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; 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::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::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.1.0/src/main/include/log4cxx/mdc.h000644 001750 001750 00000016533 14354342764 022642 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** The MDC class is similar to the {@link log4cxx::NDC NDC} class except that it is based on a map instead of a stack. It provides mapped diagnostic contexts. 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. */ 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 key * @param value value. */ MDC(const std::string& key, const std::string& value); ~MDC(); /** * Put a context value (the o parameter) as identified * with the key parameter into the current thread's * context map. * *

If the current thread does not have a context map it is * created as a side effect. * @param key key * @param value value. */ static void put(const std::string& key, const std::string& value); /** * Put a context value (the o parameter) as identified * with the key parameter into the current thread's * context map. * *

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 key. * @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 key. * @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 key * @param value value. */ MDC(const std::wstring& key, const std::wstring& value); /** * Put a context value (the o parameter) as identified * with the key parameter into the current thread's * context map. * *

If the current thread does not have a context map it is * created as a side effect. * @param key key * @param value value. */ 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 key. * @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 key. * @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 key * @param value value. */ MDC(const std::basic_string& key, const std::basic_string& value); /** * Put a context value (the o parameter) as identified * with the key parameter into the current thread's * context map. * *

If the current thread does not have a context map it is * created as a side effect. * @param key key * @param value 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 key. * @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 key. * @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 key * @param value value. */ MDC(const CFStringRef& key, const CFStringRef& value); /** * Put a context value (the o parameter) as identified * with the key parameter into the current thread's * context map. * *

If the current thread does not have a context map it is * created as a side effect. * @param key key * @param value value. */ 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 key. * @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 key. * @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 key. * @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. */ 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.1.0/src/main/include/log4cxx/jsonlayout.h000644 001750 001750 00000006611 14424033175 024271 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** 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::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; /** Returns the content type output by this layout, i.e "application/json". */ LogString getContentType() const override; void activateOptions(helpers::Pool& /* p */) override; /** Set options */ 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.1.0/src/main/include/log4cxx/varia/000755 001750 001750 00000000000 14424433605 023011 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/varia/fallbackerrorhandler.h000644 001750 001750 00000006142 14354342764 027343 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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, public virtual helpers::Object { 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; /** No options to activate. */ void activateOptions(helpers::Pool& p) override; 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; }; LOG4CXX_PTR_DEF(FallbackErrorHandler); } // namespace varia } // namespace log4cxx #endif //_LOG4CXX_VARIA_FALLBACK_ERROR_HANDLER_H apache-log4cxx-1.1.0/src/main/include/log4cxx/defaultloggerfactory.h000644 001750 001750 00000002711 14354342764 026304 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class Logger; typedef std::shared_ptr LoggerPtr; 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() LoggerPtr makeNewLoggerInstance(helpers::Pool& pool, const LogString& name) const override; }; } // namespace log4cxx #endif //_LOG4CXX_DEFAULT_LOGGER_FACTORY_H apache-log4cxx-1.1.0/src/main/include/log4cxx/fmtlayout.h000644 001750 001750 00000021552 14354342764 024120 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** * 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"
		
@return A byte array in SimpleLayout format. */ void format(LogString& output, const spi::LoggingEventPtr& event, helpers::Pool& pool) const override; bool ignoresThrowable() const override { return true; } void activateOptions(helpers::Pool& /* p */) override; 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.1.0/src/main/include/log4cxx/logger.h000644 001750 001750 00000251307 14354342764 023356 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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 log4cxx::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. @param pool lifetime of pool must be longer than logger. @param name The name of the logger. */ Logger(helpers::Pool& pool, const LogString& name); ~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 log4cxx::spi::LoggingEventPtr& event, log4cxx::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 location of source of logging request. */ void debug(const std::string& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_DEBUG. */ void debug(const std::wstring& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_DEBUG. */ void debug(const std::basic_string& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_DEBUG. */ void debug(const CFStringRef& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_ERROR. */ void error(const std::string& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_ERROR. */ void error(const std::wstring& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_ERROR. */ void error(const std::basic_string& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_ERROR. */ void error(const CFStringRef& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_FATAL. */ void fatal(const std::string& msg, const log4cxx::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_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 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 location of source of logging request. See also #LOG4CXX_FATAL. */ void fatal(const std::wstring& msg, const log4cxx::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_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 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 location of source of logging request. See also #LOG4CXX_FATAL. */ void fatal(const std::basic_string& msg, const log4cxx::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_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 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 location of source of logging request. See also #LOG4CXX_FATAL. */ void fatal(const CFStringRef& msg, const log4cxx::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_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 level to log. @param message message. @param location location of source of logging request. */ void forcedLog(const LevelPtr& level, const std::string& message, const log4cxx::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to attached appender(s). without further checks. @param level the level to log. @param message message. */ 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 level to log. @param message message. @param location location of source of logging request. */ void forcedLog(const LevelPtr& level, const std::wstring& message, const log4cxx::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to attached appender(s). without further checks. @param level the level to log. @param message message. */ void forcedLog(const LevelPtr& level, const std::wstring& message) const; #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API /** Add a new logging event containing \c message and \c location to attached appender(s). without further checks. @param level the level to log. @param message message. @param location location of source of logging request. */ void forcedLog(const LevelPtr& level, const std::basic_string& message, const log4cxx::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to attached appender(s). without further checks. @param level the level to log. @param message message. */ 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 level to log. @param message message. @param location location of source of logging request. */ void forcedLog(const LevelPtr& level, const CFStringRef& message, const log4cxx::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to attached appender(s). without further checks. @param level the level to log. @param message message. */ 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 level to log. @param message the message string to log. @param location location of the logging statement. */ void forcedLogLS(const LevelPtr& level, const LogString& message, const log4cxx::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::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::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::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::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::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::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 location of source of logging request. See also #LOG4CXX_INFO. */ void info(const std::string& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_INFO. */ void info(const std::wstring& msg, const log4cxx::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 location of source of logging request. */ void info(const std::basic_string& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_INFO. */ void info(const CFStringRef& msg, const log4cxx::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->forcedLog(log4cxx::Level::getDebug(), "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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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 location of source of logging request. See also #LOG4CXX_WARN. */ void warn(const std::wstring& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_WARN. */ void warn(const std::basic_string& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_WARN. */ void warn(const CFStringRef& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_WARN. */ void warn(const std::string& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_TRACE. */ void trace(const std::wstring& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_TRACE. */ void trace(const std::basic_string& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_TRACE. */ void trace(const CFStringRef& msg, const log4cxx::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 location of source of logging request. See also #LOG4CXX_TRACE. */ void trace(const std::string& msg, const log4cxx::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); } /** @addtogroup LoggingMacros Logging macros @{ */ #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::MDC mdc_("stacktrace", LOG4CXX_EOL + boost::stacktrace::to_string(boost::stacktrace::stacktrace())); #elif __has_include() #include #define LOG4CXX_STACKTRACE ::log4cxx::MDC mdc_("stacktrace", LOG4CXX_EOL + std::stacktrace::to_string(std::stacktrace::stacktrace())); #elif __has_include() #include #define LOG4CXX_STACKTRACE ::log4cxx::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 /** 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 level to log. @param message the message string to log. */ #define LOG4CXX_LOG(logger, level, message) do { \ if (logger->isEnabledFor(level)) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(level, oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing libfmt formatted ... to attached appender(s) if this logger is enabled for \c events. @param logger the logger to be used. @param level the level to log. @param ... The format string and message to log */ #define LOG4CXX_LOG_FMT(logger, level, ...) do { \ if (logger->isEnabledFor(level)) {\ logger->forcedLog(level, fmt::format( __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 level to log. @param message the message string to log in the internal encoding. */ #define LOG4CXX_LOGLS(logger, level, message) do { \ if (logger->isEnabledFor(level)) {\ ::log4cxx::helpers::LogCharMessageBuffer oss_; \ logger->forcedLog(level, oss_.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. @param logger the logger that has the enabled status. @param message a valid r-value expression of an operator<<(std::basic::ostream&. ...) overload.

Example: ~~~{.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() ); ~~~ */ #define LOG4CXX_DEBUG(logger, message) do { \ if (LOG4CXX_UNLIKELY(::log4cxx::Logger::isDebugEnabledFor(logger))) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getDebug(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing libfmt formatted ... to attached appender(s) if \c logger is enabled for DEBUG events. @param logger the logger to be used. @param ... The format string and message to log */ #define LOG4CXX_DEBUG_FMT(logger, ...) do { \ if (LOG4CXX_UNLIKELY(::log4cxx::Logger::isDebugEnabledFor(logger))) {\ logger->forcedLog(::log4cxx::Level::getDebug(), fmt::format( __VA_ARGS__ ), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_DEBUG(logger, message) #define LOG4CXX_DEBUG_FMT(logger, ...) #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. @param logger the logger that has the enabled status. @param message a valid r-value expression of an operator<<(std::basic::ostream&. ...) overload.

Example: ~~~{.cpp} LOG4CXX_TRACE(m_log, "AddVertex:" << " p " << p[j] << " n " << n << ' ' << color); ~~~ */ #define LOG4CXX_TRACE(logger, message) do { \ if (LOG4CXX_UNLIKELY(::log4cxx::Logger::isTraceEnabledFor(logger))) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getTrace(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing libfmt formatted ... to attached appender(s) if \c logger is enabled for TRACE events. @param logger the logger to be used. @param ... The format string and message to log */ #define LOG4CXX_TRACE_FMT(logger, ...) do { \ if (LOG4CXX_UNLIKELY(::log4cxx::Logger::isTraceEnabledFor(logger))) {\ logger->forcedLog(::log4cxx::Level::getTrace(), fmt::format( __VA_ARGS__ ), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_TRACE(logger, message) #define LOG4CXX_TRACE_FMT(logger, ...) #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. @param logger the logger that has the enabled status. @param message a valid r-value expression of an operator<<(std::basic::ostream&. ...) overload.

Example: ~~~{.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() ); ~~~ */ #define LOG4CXX_INFO(logger, message) do { \ if (::log4cxx::Logger::isInfoEnabledFor(logger)) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getInfo(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing libfmt formatted ... to attached appender(s) if \c logger is enabled for INFO events. @param logger the logger to be used. @param ... The format string and message to log */ #define LOG4CXX_INFO_FMT(logger, ...) do { \ if (::log4cxx::Logger::isInfoEnabledFor(logger)) {\ logger->forcedLog(::log4cxx::Level::getInfo(), fmt::format( __VA_ARGS__ ), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_INFO(logger, message) #define LOG4CXX_INFO_FMT(logger, ...) #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. @param logger the logger to be used. @param message the message string to log.

Example: ~~~{.cpp} catch (const std::exception& ex) { LOG4CXX_WARN(m_log, ex.what() << ": in " << m_task->GetParamFilePath()); } ~~~ */ #define LOG4CXX_WARN(logger, message) do { \ if (::log4cxx::Logger::isWarnEnabledFor(logger)) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getWarn(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing libfmt formatted ... to attached appender(s) if \c logger is enabled for WARN events. @param logger the logger to be used. @param ... The format string and message to log */ #define LOG4CXX_WARN_FMT(logger, ...) do { \ if (::log4cxx::Logger::isWarnEnabledFor(logger)) {\ logger->forcedLog(::log4cxx::Level::getWarn(), fmt::format( __VA_ARGS__ ), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_WARN(logger, message) #define LOG4CXX_WARN_FMT(logger, ...) #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. @param logger the logger to be used. @param message the message string to log.

Example: ~~~{.cpp} catch (std::exception& ex) { LOG4CXX_ERROR(m_log, ex.what() << " in AddScanData"); } ~~~ */ #define LOG4CXX_ERROR(logger, message) do { \ if (::log4cxx::Logger::isErrorEnabledFor(logger)) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getError(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing libfmt formatted ... to attached appender(s) if \c logger is enabled for ERROR events. @param logger the logger to be used. @param ... The format string and message to log */ #define LOG4CXX_ERROR_FMT(logger, ...) do { \ if (::log4cxx::Logger::isErrorEnabledFor(logger)) {\ logger->forcedLog(::log4cxx::Level::getError(), fmt::format( __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 the message string to log. */ #define LOG4CXX_ASSERT(logger, condition, message) do { \ if (!(condition) && ::log4cxx::Logger::isErrorEnabledFor(logger)) {\ ::log4cxx::helpers::MessageBuffer oss_; \ LOG4CXX_STACKTRACE \ logger->forcedLog(::log4cxx::Level::getError(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** If \c condition is not true, add a new logging event containing libfmt formatted \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 ... The format string and message to log */ #define LOG4CXX_ASSERT_FMT(logger, condition, ...) do { \ if (!(condition) && ::log4cxx::Logger::isErrorEnabledFor(logger)) {\ LOG4CXX_STACKTRACE \ logger->forcedLog(::log4cxx::Level::getError(), fmt::format( __VA_ARGS__ ), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_ERROR(logger, message) #define LOG4CXX_ERROR_FMT(logger, ...) #define LOG4CXX_ASSERT(logger, condition, message) #define LOG4CXX_ASSERT_FMT(logger, condition, ...) #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. @param logger the logger to be used. @param message the message string to log.

Example: ~~~{.cpp} LOG4CXX_FATAL(m_log, m_renderSystem->getName() << " is not supported"); ~~~ */ #define LOG4CXX_FATAL(logger, message) do { \ if (::log4cxx::Logger::isFatalEnabledFor(logger)) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getFatal(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing libfmt formatted ... to attached appender(s) if \c logger is enabled for FATAL events. @param logger the logger to be used. @param ... The format string and message to log */ #define LOG4CXX_FATAL_FMT(logger, ...) do { \ if (::log4cxx::Logger::isFatalEnabledFor(logger)) {\ logger->forcedLog(::log4cxx::Level::getFatal(), fmt::format( __VA_ARGS__ ), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_FATAL(logger, message) #define LOG4CXX_FATAL_FMT(logger, ...) #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 level to log. @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 level to log. @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 level to log. @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 level to log. @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.1.0/src/main/include/log4cxx/log4cxx.h.in000644 001750 001750 00000010157 14424032606 024055 0ustar00robertrobert000000 000000 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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_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_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 #else // !defined(_WIN32) || !defined(_MSC_VER) #define LOG4CXX_EXPORT #endif // !defined(_WIN32) || !defined(_MSC_VER) namespace log4cxx { /** * 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(); } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/logstring.h000644 001750 001750 00000004150 14354342764 024077 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { #if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_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::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::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.1.0/src/main/include/log4cxx/patternlayout.h000644 001750 001750 00000045532 14424033175 025002 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { LOG4CXX_LIST_DEF(LoggingEventPatternConverterList, log4cxx::pattern::LoggingEventPatternConverterPtr); LOG4CXX_LIST_DEF(FormattingInfoList, log4cxx::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(); /** * 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; /** * Call createPatternParser */ void activateOptions(helpers::Pool& p) override; 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::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.1.0/src/main/include/log4cxx/appender.h000644 001750 001750 00000007400 14354342764 023666 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { // 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::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.1.0/src/main/include/log4cxx/basicconfigurator.h000644 001750 001750 00000004145 14354342764 025577 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { class Appender; typedef std::shared_ptr AppenderPtr; /** Use this class to quickly configure the package.

For file based configuration see PropertyConfigurator. For XML based configuration see 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.1.0/src/main/include/log4cxx/level.h000644 001750 001750 00000020406 14354342764 023200 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** * 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 /** 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 }; 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.1.0/src/main/include/log4cxx/stream.h000644 001750 001750 00000035502 14353331212 023350 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** * 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::LoggerPtr& logger, const log4cxx::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::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::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::LoggerPtr logger; /** * associated level. */ log4cxx::LevelPtr level; /** * associated level. */ log4cxx::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::LoggerPtr& logger, const log4cxx::LevelPtr& level); /** * Constructor. */ logstream(const Ch* loggerName, const log4cxx::LevelPtr& level); /** * Constructor. */ logstream(const std::basic_string& loggerName, const log4cxx::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::LevelPtr& level); /** * Insertion operator for location. */ logstream& operator<<(const log4cxx::spi::LocationInfo& location); /** * Alias for insertion operator for location. Kludge to avoid * inappropriate compiler ambiguity. */ logstream& operator>>(const log4cxx::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::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::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::LoggerPtr& logger, const log4cxx::LevelPtr& level); /** * Constructor. */ wlogstream(const Ch* loggerName, const log4cxx::LevelPtr& level); /** * Constructor. */ wlogstream(const std::basic_string& loggerName, const log4cxx::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::LevelPtr& level); /** * Insertion operator for location. */ wlogstream& operator<<(const log4cxx::spi::LocationInfo& location); /** * Alias for insertion operator for location. Kludge to avoid * inappropriate compiler ambiguity. */ wlogstream& operator>>(const log4cxx::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::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::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 || LOG4CXX_CFSTRING_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::LoggerPtr& logger, const log4cxx::LevelPtr& level); #if LOG4CXX_UNICHAR_API /** * Constructor. */ ulogstream(const Ch* loggerName, const log4cxx::LevelPtr& level); /** * Constructor. */ ulogstream(const std::basic_string& loggerName, const log4cxx::LevelPtr& level); #endif #if LOG4CXX_CFSTRING_API ulogstream(const CFStringRef& loggerName, const log4cxx::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::LevelPtr& level); /** * Insertion operator for location. */ ulogstream& operator<<(const log4cxx::spi::LocationInfo& location); /** * Alias for insertion operator for location. Kludge to avoid * inappropriate compiler ambiguity. */ ulogstream& operator>>(const log4cxx::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::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::logstream& operator<<(log4cxx::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::wlogstream& operator<<(log4cxx::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::logstream_manipulator) log4cxx::logstream_base::nop >> LOG4CXX_LOCATION << (log4cxx::logstream_manipulator) log4cxx::logstream_base::endmsg #else #define LOG4CXX_ENDMSG LOG4CXX_LOCATION << (log4cxx::logstream_manipulator) log4cxx::logstream_base::endmsg #endif #endif #endif //_LOG4CXX_STREAM_H apache-log4cxx-1.1.0/src/main/include/log4cxx/simplelayout.h000644 001750 001750 00000004227 14354342764 024623 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** 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"
		
@return A byte array in SimpleLayout format. */ 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; } void activateOptions(helpers::Pool& /* p */) override {} void setOption(const LogString& /* option */, const LogString& /* value */) override {} }; LOG4CXX_PTR_DEF(SimpleLayout); } // namespace log4cxx #endif //_LOG4CXX_SIMPLE_LAYOUT_H apache-log4cxx-1.1.0/src/main/include/log4cxx/pattern/000755 001750 001750 00000000000 14424433605 023364 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx/pattern/threadpatternconverter.h000644 001750 001750 00000003432 14354342764 030343 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/linelocationpatternconverter.h000644 001750 001750 00000003463 14354342764 031560 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/propertiespatternconverter.h000644 001750 001750 00000004515 14354342764 031273 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/pattern/throwableinformationpatternconverter.h000644 001750 001750 00000004373 14354342764 033336 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/ndcpatternconverter.h000644 001750 001750 00000003371 14354342764 027642 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/datepatternconverter.h000644 001750 001750 00000004406 14354342764 030013 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace pattern { /** * Convert and format the event's date in a StringBuffer. * * * */ 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() DatePatternConverter(const OptionsList& options); ~DatePatternConverter(); static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& output, helpers::Pool& p) const override; void format(const helpers::ObjectPtr& obj, LogString& output, helpers::Pool& p) const override; void format(const helpers::DatePtr& date, LogString& toAppendTo, helpers::Pool& p) const; }; LOG4CXX_PTR_DEF(DatePatternConverter); } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/pattern/lineseparatorpatternconverter.h000644 001750 001750 00000003623 14354342764 031746 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/mdcpatternconverter.h000644 001750 001750 00000003760 14424033175 027632 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/namepatternconverter.h000644 001750 001750 00000004223 14354342764 030013 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/colorendpatternconverter.h000644 001750 001750 00000003427 14354342764 030705 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/classnamepatternconverter.h000644 001750 001750 00000003560 14354342764 031044 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/filelocationpatternconverter.h000644 001750 001750 00000003505 14354342764 031545 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/threadusernamepatternconverter.h000644 001750 001750 00000003226 14354342764 032104 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/pattern/colorstartpatternconverter.h000644 001750 001750 00000004250 14354342764 031267 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/relativetimepatternconverter.h000644 001750 001750 00000003606 14354342764 031571 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/pattern/methodlocationpatternconverter.h000644 001750 001750 00000003552 14354342764 032110 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/messagepatternconverter.h000644 001750 001750 00000003414 14354342764 030520 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/literalpatternconverter.h000644 001750 001750 00000003423 14354342764 030530 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/integerpatternconverter.h000644 001750 001750 00000003315 14354342764 030531 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/patternconverter.h000644 001750 001750 00000006627 14424032606 027151 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/loggingeventpatternconverter.h000644 001750 001750 00000005273 14354342764 031571 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/fulllocationpatternconverter.h000644 001750 001750 00000003464 14354342764 031574 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/loggerpatternconverter.h000644 001750 001750 00000003403 14354342764 030351 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/formattinginfo.h000644 001750 001750 00000004671 14354342764 026602 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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::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.1.0/src/main/include/log4cxx/pattern/nameabbreviator.h000644 001750 001750 00000004536 14353331212 026676 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace pattern { class NameAbbreviator; LOG4CXX_PTR_DEF(NameAbbreviator); /** * NameAbbreviator generates abbreviated logger and class names. * * * */ class LOG4CXX_EXPORT NameAbbreviator : public log4cxx::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.1.0/src/main/include/log4cxx/pattern/shortfilelocationpatternconverter.h000644 001750 001750 00000003613 14354342764 032625 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/patternparser.h000644 001750 001750 00000012245 14354342764 026442 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/pattern/filedatepatternconverter.h000644 001750 001750 00000003034 14353331212 030630 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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: /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); }; } } #endif apache-log4cxx-1.1.0/src/main/include/log4cxx/pattern/levelpatternconverter.h000644 001750 001750 00000003515 14354342764 030205 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx/hierarchy.h000644 001750 001750 00000020751 14354342764 024052 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #include #include #include #include namespace log4cxx { 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() LOG4CXX_CAST_ENTRY(spi::LoggerRepository) END_LOG4CXX_CAST_MAP() private: /** Create a new logger hierarchy. */ Hierarchy(); public: static HierarchyPtr create(); ~Hierarchy(); void addHierarchyEventListener(const spi::HierarchyEventListenerPtr& listener) override; /** * 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 l or higher. By default all levels are enabled. @param l The minimum level for which logging requests are sent to their appenders. */ void setThreshold(const LevelPtr& l) 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); 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.1.0/src/main/include/log4cxx-qt/000755 001750 001750 00000000000 14424433605 022331 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/include/log4cxx-qt/messagehandler.h000644 001750 001750 00000002655 14424032606 025470 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { 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.1.0/src/main/include/log4cxx-qt/configuration.h000644 001750 001750 00000003131 14354342764 025356 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { namespace qt { class LOG4CXX_EXPORT Configuration { private: Configuration(); static log4cxx::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.1.0/src/main/cpp/000755 001750 001750 00000000000 14424433605 017456 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/cpp/syslogappender.cpp000644 001750 001750 00000026223 14354342764 023235 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::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 ( std::vector::iterator it = packets.begin(); it != packets.end(); it++, current++ ) { char buf[12]; apr_snprintf( buf, sizeof(buf), "(%d/%d)", current, (int)packets.size() ); LOG4CXX_DECODE_CHAR(str, buf); it->append( str ); } } 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 ( std::vector::iterator it = packets.begin(); it != packets.end(); it++ ) { // use of "%s" to avoid a security hole ::syslog(_priv->syslogFacility | event->getLevel()->getSyslogEquivalent(), "%s", it->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 ( std::vector::iterator it = packets.begin(); it != packets.end(); it++ ) { 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(*it); _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.1.0/src/main/cpp/consoleappender.cpp000644 001750 001750 00000007545 14354342764 023365 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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 LogString name(LOG4CXX_STR("System.out")); return name; } const LogString& ConsoleAppender::getSystemErr() { static const LogString 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.1.0/src/main/cpp/socketoutputstream.cpp000644 001750 001750 00000003661 14354342764 024164 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; 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.1.0/src/main/cpp/rollingfileappender.cpp000644 001750 001750 00000035411 14424032606 024207 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::helpers; using namespace log4cxx::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::cast(_priv->rollingPolicy)) result = fwrp->getMaxIndex(); return result; } void RollingFileAppender::setMaxBackupIndex(int maxBackups) { auto fwrp = log4cxx::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::cast(_priv->triggeringPolicy)) result = sbtp->getMaxFileSize(); return result; } void RollingFileAppender::setMaximumFileSize(size_t maxFileSize) { auto sbtp = log4cxx::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::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::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) { LOG4CXX_DECODE_CHAR(lsMsg, ex.what()); LogString errorMsg = LOG4CXX_STR("Exception on rollover: "); errorMsg.append(lsMsg); LogLog::error(errorMsg); _priv->errorHandler->error(lsMsg, 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); } setFileInternal( rollover1->getActiveFileName(), rollover1->getAppend(), _priv->bufferedIO, _priv->bufferSize, p); } else { setFileInternal( rollover1->getActiveFileName(), true, _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) { LOG4CXX_DECODE_CHAR(lsMsg, ex.what()); LogString errorMsg = LOG4CXX_STR("Exception during rollover: "); errorMsg.append(lsMsg); LogLog::warn(errorMsg); _priv->errorHandler->error(lsMsg, 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); } return true; } } catch (std::exception& ex) { LOG4CXX_DECODE_CHAR(lsMsg, ex.what()); LogString errorMsg = LOG4CXX_STR("Exception during rollover: "); errorMsg.append(lsMsg); LogLog::warn(errorMsg); _priv->errorHandler->error(lsMsg, 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) { LOG4CXX_DECODE_CHAR(lsMsg, ex.what()); LogString errorMsg = LOG4CXX_STR("Exception during rollover attempt: "); errorMsg.append(lsMsg); LogLog::warn(errorMsg); _priv->errorHandler->error(lsMsg); } } 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 { 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.1.0/src/main/cpp/bytearrayoutputstream.cpp000644 001750 001750 00000003300 14354342764 024664 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/locationinfo.cpp000644 001750 001750 00000007466 14354342764 022672 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::spi; using namespace log4cxx::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 LocationInfo 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 ), shortFileName(shortFileName1), methodName( methodName1 ) { } /** * 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; methodName = src.methodName; lineNumber = src.lineNumber; return * this; } /** * Resets location info to default state. */ void LocationInfo::clear() { fileName = 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.1.0/src/main/cpp/datepatternconverter.cpp000644 001750 001750 00000011332 14354342764 024434 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; struct DatePatternConverter::DatePatternConverterPrivate : public PatternConverterPrivate { DatePatternConverterPrivate( const LogString& name, const LogString& style, DateFormatPtr _df ): PatternConverterPrivate(name, style), df(_df) {} /** * Date format. */ log4cxx::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::cast(obj); if (date != NULL) { format(date, toAppendTo, p); } else { LoggingEventPtr event = log4cxx::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.1.0/src/main/cpp/literalpatternconverter.cpp000644 001750 001750 00000004646 14354342764 025165 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::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 PatternConverterPtr 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.1.0/src/main/cpp/xmlsocketappender.cpp000644 001750 001750 00000010444 14354342764 023724 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::net; using namespace log4cxx::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::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::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::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.1.0/src/main/cpp/propertyconfigurator.cpp000644 001750 001750 00000040253 14424032606 024471 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #define LOG4CXX 1 #include #include using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; using namespace log4cxx::config; using namespace log4cxx::rolling; #if APR_HAS_THREADS #include namespace log4cxx { 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; #endif IMPLEMENT_LOG4CXX_OBJECT(PropertyConfigurator) PropertyConfigurator::PropertyConfigurator() : registry(new std::map()), loggerFactory(new DefaultLoggerFactory()) { } PropertyConfigurator::~PropertyConfigurator() { delete registry; } spi::ConfigurationStatus PropertyConfigurator::doConfigure(const File& configFileName, spi::LoggerRepositoryPtr hierarchy) { 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 { 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 APR_HAS_THREADS spi::ConfigurationStatus PropertyConfigurator::configureAndWatch(const File& configFilename) { return configureAndWatch(configFilename, FileWatchdog::DEFAULT_DELAY); } 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(delay); pdog->start(); return stat; } #endif spi::ConfigurationStatus PropertyConfigurator::doConfigure(helpers::Properties& properties, spi::LoggerRepositoryPtr hierarchy) { hierarchy->setConfigured(true); static const LogString DEBUG_KEY(LOG4CXX_STR("log4j.debug")); LogString value(properties.getProperty(DEBUG_KEY)); if (!value.empty()) { LogLog::setInternalDebugging(OptionConverter::toBoolean(value, true)); } static const LogString THRESHOLD_PREFIX(LOG4CXX_STR("log4j.threshold")); LogString thresholdStr = OptionConverter::findAndSubst(THRESHOLD_PREFIX, properties); if (!thresholdStr.empty()) { hierarchy->setThreshold(OptionConverter::toLevel(thresholdStr, Level::getAll())); 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 LogString LOGGER_FACTORY_KEY(LOG4CXX_STR("log4j.loggerFactory")); LogString factoryClassName = OptionConverter::findAndSubst(LOGGER_FACTORY_KEY, props); if (!factoryClassName.empty()) { 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::cast( instance ); static const LogString 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 LogString ROOT_CATEGORY_PREFIX(LOG4CXX_STR("log4j.rootCategory")); static const LogString 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 LogString 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 LogString CATEGORY_PREFIX(LOG4CXX_STR("log4j.category.")); static const LogString LOGGER_PREFIX(LOG4CXX_STR("log4j.logger.")); std::vector names = props.propertyNames(); std::vector::iterator it = names.begin(); std::vector::iterator itEnd = names.end(); while (it != itEnd) { LogString key = *it++; if (key.find(CATEGORY_PREFIX) == 0 || key.find(LOGGER_PREFIX) == 0) { LogString loggerName; if (key.find(CATEGORY_PREFIX) == 0) { loggerName = key.substr(CATEGORY_PREFIX.length()); } else if (key.find(LOGGER_PREFIX) == 0) { loggerName = key.substr(LOGGER_PREFIX.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 LogString ADDITIVITY_PREFIX(LOG4CXX_STR("log4j.additivity.")); LogString value(OptionConverter::findAndSubst(ADDITIVITY_PREFIX + loggerName, props)); LogLog::debug((LogString) LOG4CXX_STR("Handling ") + ADDITIVITY_PREFIX + loggerName + LOG4CXX_STR("=[") + value + LOG4CXX_STR("]")); // touch additivity only if necessary if (!value.empty()) { bool additivity = OptionConverter::toBoolean(value, true); 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) { 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(); 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 LogString INTERNAL_ROOT_NAME(LOG4CXX_STR("root")); if (loggerName == INTERNAL_ROOT_NAME) { LogLog::warn(LOG4CXX_STR("The root logger cannot be set to null.")); } else { logger->setLevel(0); LogLog::debug((LogString) LOG4CXX_STR("Logger ") + loggerName + LOG4CXX_STR(" set to null")); } } else { logger->setLevel(OptionConverter::toLevel(levelStr, Level::getDebug())); 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; } 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) { LogLog::debug((LogString) LOG4CXX_STR("Appender \"") + appenderName + LOG4CXX_STR("\" was already parsed.")); return appender; } static const LogString APPENDER_PREFIX(LOG4CXX_STR("log4j.appender.")); // Appender was not previously initialized. LogString prefix = APPENDER_PREFIX + appenderName; LogString layoutPrefix = prefix + LOG4CXX_STR(".layout"); std::shared_ptr obj = OptionConverter::instantiateByKey( props, prefix, Appender::getStaticClass(), 0); appender = log4cxx::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::cast( obj ); if (layout != 0) { appender->setLayout(layout); LogLog::debug((LogString) LOG4CXX_STR("Parsing layout options for \"") + appenderName + LOG4CXX_STR("\".")); PropertySetter::setProperties(layout, props, layoutPrefix + LOG4CXX_STR("."), p); LogLog::debug((LogString) LOG4CXX_STR("End of parsing for \"") + appenderName + LOG4CXX_STR("\".")); } } RollingFileAppenderPtr rolling = log4cxx::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::cast( rolling_obj ); if(rollingPolicy) { rolling->setRollingPolicy(rollingPolicy); 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::cast( triggering_obj ); if(triggeringPolicy) { rolling->setTriggeringPolicy(triggeringPolicy); 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); 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.1.0/src/main/cpp/filterbasedtriggeringpolicy.cpp000644 001750 001750 00000005745 14354342764 025772 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(FilterBasedTriggeringPolicy) struct FilterBasedTriggeringPolicy::FilterBasedTriggeringPolicyPrivate{ /** * The first filter in the filter chain. Set to null initially. */ log4cxx::spi::FilterPtr headFilter; /** * The last filter in the filter chain. */ log4cxx::spi::FilterPtr tailFilter; }; FilterBasedTriggeringPolicy::FilterBasedTriggeringPolicy() : m_priv(std::make_unique()) { } FilterBasedTriggeringPolicy::~FilterBasedTriggeringPolicy() { } bool FilterBasedTriggeringPolicy::isTriggeringEvent( Appender* /* appender */, const log4cxx::spi::LoggingEventPtr& event, const LogString& /* filename */, size_t /* fileLength */ ) { if (m_priv->headFilter == NULL) { return false; } for (log4cxx::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::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::spi::FilterPtr empty; m_priv->headFilter = empty; m_priv->tailFilter = empty; } log4cxx::spi::FilterPtr& FilterBasedTriggeringPolicy::getFilter() { return m_priv->headFilter; } /** * Prepares the instance for use. */ void FilterBasedTriggeringPolicy::activateOptions(log4cxx::helpers::Pool& p) { for (log4cxx::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.1.0/src/main/cpp/loggingevent.cpp000644 001750 001750 00000025415 14424032606 022655 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; struct LoggingEvent::LoggingEventPrivate { LoggingEventPrivate() : ndc(0), mdcCopy(0), properties(0), ndcLookupRequired(true), mdcCopyLookupRequired(true), timeStamp(0), locationInfo(), threadName(getCurrentThreadName()), threadUserName(getCurrentThreadUserName()) { } LoggingEventPrivate( const LogString& logger1, const LevelPtr& level1, const LogString& message1, const LocationInfo& locationInfo1) : logger(logger1), level(level1), ndc(0), mdcCopy(0), properties(0), ndcLookupRequired(true), mdcCopyLookupRequired(true), message(message1), timeStamp(Date::currentTime()), locationInfo(locationInfo1), threadName(getCurrentThreadName()), threadUserName(getCurrentThreadUserName()), chronoTimeStamp(std::chrono::microseconds(timeStamp)) { } ~LoggingEventPrivate() { delete ndc; delete mdcCopy; delete properties; } /** * The logger of the logging event. **/ LogString logger; /** level of logging event. */ LevelPtr level; /** The nested diagnostic context (NDC) of logging event. */ mutable LogString* ndc; /** The mapped diagnostic context (MDC) of logging event. */ mutable MDC::Map* mdcCopy; /** * A map of String keys and String values. */ std::map* properties; /** Have we tried to do an NDC lookup? If we did, there is no need * to do it again. Note that its value is always false when * serialized. Thus, a receiving SocketNode will never use it's own * (incorrect) NDC. See also writeObject method. */ mutable bool ndcLookupRequired; /** * Have we tried to do an MDC lookup? If we did, there is no need to do it * again. Note that its value is always false when serialized. See also * the getMDC and getMDCCopy methods. */ mutable bool mdcCopyLookupRequired; /** The application supplied message of logging event. */ LogString message; /** The number of microseconds elapsed from 01.01.1970 until logging event was created. */ log4cxx_time_t timeStamp; /** The is the location where this log statement was written. */ const log4cxx::spi::LocationInfo locationInfo; /** The identifier of thread in which this logging event was generated. */ const LogString& threadName; /** * The user-specified name of the thread(on a per-platform basis). * This is set using a method such as pthread_setname_np on POSIX * systems or SetThreadDescription on Windows. */ const LogString& threadUserName; std::chrono::time_point chronoTimeStamp; }; IMPLEMENT_LOG4CXX_OBJECT(LoggingEvent) // // Accessor for start time. // log4cxx_time_t LoggingEvent::getStartTime() { return log4cxx::helpers::APRInitializer::initialize(); } LoggingEvent::LoggingEvent() : m_priv(std::make_unique()) { } 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->threadUserName; } bool LoggingEvent::getNDC(LogString& dest) const { if (m_priv->ndcLookupRequired) { m_priv->ndcLookupRequired = false; LogString val; if (NDC::get(val)) { m_priv->ndc = new LogString(val); } } if (m_priv->ndc) { dest.append(*m_priv->ndc); return true; } return false; } bool LoggingEvent::getMDC(const LogString& key, LogString& dest) const { // Note the mdcCopy is used if it exists. Otherwise we use the MDC // that is associated with the thread. if (m_priv->mdcCopy != 0 && !m_priv->mdcCopy->empty()) { MDC::Map::const_iterator it = m_priv->mdcCopy->find(key); if (it != m_priv->mdcCopy->end()) { if (!it->second.empty()) { dest.append(it->second); return true; } } } return MDC::get(key, dest); } LoggingEvent::KeySet LoggingEvent::getMDCKeySet() const { LoggingEvent::KeySet set; if (m_priv->mdcCopy != 0 && !m_priv->mdcCopy->empty()) { MDC::Map::const_iterator it; for (it = m_priv->mdcCopy->begin(); it != m_priv->mdcCopy->end(); it++) { set.push_back(it->first); } } else { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { MDC::Map& m = data->getMap(); for (MDC::Map::const_iterator it = m.begin(); it != m.end(); it++) { set.push_back(it->first); } } } return set; } void LoggingEvent::getMDCCopy() const { if (m_priv->mdcCopyLookupRequired) { m_priv->mdcCopyLookupRequired = false; // the clone call is required for asynchronous logging. ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { m_priv->mdcCopy = new MDC::Map(data->getMap()); } else { m_priv->mdcCopy = new MDC::Map(); } } } 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 != 0) { std::map::const_iterator it; for (it = m_priv->properties->begin(); it != m_priv->properties->end(); it++) { set.push_back(it->first); } } return set; } const LogString& LoggingEvent::getCurrentThreadName() { #if defined(_WIN32) using ThreadIdType = DWORD; ThreadIdType threadId = GetCurrentThreadId(); #elif APR_HAS_THREADS using ThreadIdType = apr_os_thread_t; ThreadIdType threadId = apr_os_thread_current(); #else using ThreadIdType = int; ThreadIdType threadId = 0; #endif #if LOG4CXX_HAS_THREAD_LOCAL thread_local LogString thread_id_string; #else using ListItem = std::pair; static std::list thread_id_map; static std::mutex mutex; std::lock_guard lock(mutex); auto pThreadId = std::find_if(thread_id_map.begin(), thread_id_map.end() , [threadId](const ListItem& item) { return threadId == item.first; }); if (thread_id_map.end() == pThreadId) pThreadId = thread_id_map.insert(thread_id_map.begin(), ListItem(threadId, LogString())); LogString& thread_id_string = pThreadId->second; #endif if ( !thread_id_string.empty() ) { return thread_id_string; } #if APR_HAS_THREADS #if defined(_WIN32) char result[20]; apr_snprintf(result, sizeof(result), LOG4CXX_WIN32_THREAD_FMTSPEC, threadId); #else // apr_os_thread_t encoded in HEX takes needs as many characters // as two times the size of the type, plus an additional null byte. char result[sizeof(apr_os_thread_t) * 3 + 10]; apr_snprintf(result, sizeof(result), LOG4CXX_APR_THREAD_FMTSPEC, (void*) &threadId); #endif /* _WIN32 */ log4cxx::helpers::Transcoder::decode(reinterpret_cast(result), thread_id_string); #else thread_id_string = LOG4CXX_STR("0x00000000"); #endif /* APR_HAS_THREADS */ return thread_id_string; } const LogString& LoggingEvent::getCurrentThreadUserName() { #if LOG4CXX_HAS_THREAD_LOCAL thread_local LogString thread_name; #else static LogString thread_name = LOG4CXX_STR("(noname)"); #endif if( !thread_name.empty() ){ return thread_name; } #if LOG4CXX_HAS_PTHREAD_GETNAME char result[16]; pthread_t current_thread = pthread_self(); if( pthread_getname_np( current_thread, result, sizeof(result) ) < 0 ){ thread_name = LOG4CXX_STR("(noname)"); } log4cxx::helpers::Transcoder::decode(reinterpret_cast(result), thread_name); #elif 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)) { std::wstring wresult = result; LOG4CXX_DECODE_WCHAR(decoded, wresult); LocalFree(result); thread_name = decoded; } }else{ thread_name = LOG4CXX_STR("(noname)"); } #else thread_name = LOG4CXX_STR("(noname)"); #endif return thread_name; } 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->threadName; } log4cxx_time_t LoggingEvent::getTimeStamp() const { return m_priv->timeStamp; } const log4cxx::spi::LocationInfo& LoggingEvent::getLocationInformation() const { return m_priv->locationInfo; } std::chrono::time_point LoggingEvent::getChronoTimeStamp() const{ return m_priv->chronoTimeStamp; } apache-log4cxx-1.1.0/src/main/cpp/fileoutputstream.cpp000644 001750 001750 00000006137 14354342764 023614 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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(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 IOException(-1); } 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.1.0/src/main/cpp/filewatchdog.cpp000644 001750 001750 00000007101 14354342764 022630 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 using namespace log4cxx; using namespace log4cxx::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(){} /** 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; }; FileWatchdog::FileWatchdog(const File& file1) : m_priv(std::make_unique(file1)) { } FileWatchdog::~FileWatchdog() { m_priv->interrupted = 0xFFFF; { std::unique_lock lock(m_priv->interrupt_mutex); m_priv->interrupt.notify_all(); } m_priv->thread.join(); } const File& FileWatchdog::file(){ return m_priv->file; } void FileWatchdog::checkAndConfigure() { Pool pool1; if (!m_priv->file.exists(pool1)) { if (!m_priv->warnedAlready) { LogLog::debug(((LogString) LOG4CXX_STR("[")) + m_priv->file.getPath() + LOG4CXX_STR("] does not exist.")); m_priv->warnedAlready = true; } } else { apr_time_t thisMod = m_priv->file.lastModified(pool1); if (thisMod > m_priv->lastModif) { m_priv->lastModif = thisMod; doOnChange(); m_priv->warnedAlready = false; } } } void FileWatchdog::run() { 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 (m_priv->interrupted != 0xFFFF) { std::unique_lock lock( m_priv->interrupt_mutex ); m_priv->interrupt.wait_for( lock, std::chrono::milliseconds( m_priv->delay ), std::bind(&FileWatchdog::is_interrupted, this) ); checkAndConfigure(); } LogString msg2(LOG4CXX_STR("Stop checking [")); msg2 += m_priv->file.getPath(); msg2 += LOG4CXX_STR("]"); LogLog::debug(msg2); } void FileWatchdog::start() { checkAndConfigure(); 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.1.0/src/main/cpp/resourcebundle.cpp000644 001750 001750 00000006232 14354342764 023215 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ResourceBundle) ResourceBundlePtr ResourceBundle::getBundle(const LogString& baseName, const Locale& locale) { LogString bundleName; PropertyResourceBundlePtr resourceBundle, previous; 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); for (std::vector::iterator it = bundlesNames.begin(); it != bundlesNames.end(); it++) { bundleName = *it; PropertyResourceBundlePtr current; // Try loading a class which implements ResourceBundle try { const Class& classObj = Loader::loadClass(bundleName); ObjectPtr obj = ObjectPtr(classObj.newInstance()); current = log4cxx::cast(obj); } catch (ClassNotFoundException&) { current = 0; } // No class found, then try to create a PropertyResourceBundle from a file if (current == 0) { InputStreamPtr bundleStream = Loader::getResourceAsStream( bundleName + LOG4CXX_STR(".properties")); if (bundleStream == 0) { continue; } try { current = std::make_shared(bundleStream); } catch (Exception&) { throw; } } // Add the new resource bundle to the hierarchy if (resourceBundle == 0) { resourceBundle = current; previous = current; } else { previous->setParent(current); previous = current; } } // no resource bundle found at all, then throw exception if (resourceBundle == 0) { throw MissingResourceException( ((LogString) LOG4CXX_STR("Missing resource bundle ")) + baseName); } return resourceBundle; } apache-log4cxx-1.1.0/src/main/cpp/threadutility.cpp000644 001750 001750 00000012237 14424032606 023056 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #if WIN32 #include #include #endif namespace log4cxx { 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 ThreadUtility instance; return &instance; } 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 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 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.1.0/src/main/cpp/exception.cpp000644 001750 001750 00000025306 14424032606 022162 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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; using namespace log4cxx::helpers; Exception::Exception(const LogString& msg1) { std::string m; Transcoder::encode(msg1, m); 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& 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) { char err_buff[32]; LogString s(LOG4CXX_STR("IO Exception : status code = ")); Pool p; StringHelper::toString(stat, p, s); s.append(LOG4CXX_STR("(")); apr_strerror(stat, err_buff, sizeof(err_buff)); std::string sMsg = err_buff; LOG4CXX_DECODE_CHAR(lsMsg, sMsg); s.append(lsMsg); s.append(LOG4CXX_STR(")")); 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.1.0/src/main/cpp/bytearrayinputstream.cpp000644 001750 001750 00000003647 14354342764 024501 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/loader.cpp000644 001750 001750 00000004607 14354342764 021446 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::spi; using namespace log4cxx::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.1.0/src/main/cpp/loggingeventpatternconverter.cpp000644 001750 001750 00000003353 14354342764 026213 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::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::helpers::Pool& p) const { LoggingEventPtr le = log4cxx::cast(obj); if (le != NULL) { format(le, output, p); } } bool LoggingEventPatternConverter::handlesThrowable() const { return false; } apache-log4cxx-1.1.0/src/main/cpp/multiprocessrollingfileappender.cpp000644 001750 001750 00000041262 14354342764 026675 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 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; using namespace log4cxx::rolling; using namespace log4cxx::helpers; using namespace log4cxx::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::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::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) { snprintf(szUid, MAX_FILE_LEN, "%u", uid); } log4cxx::filesystem::path path = szDirName; const LogString lockname = path.parent_path() / (path.filename().string() + szUid + ".lock"); apr_file_t* lock_file; stat = apr_file_open(&lock_file, lockname.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::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) { LogLog::warn(LOG4CXX_STR("Exception on rollover")); LogString exmsg; log4cxx::helpers::Transcoder::decode(ex.what(), exmsg); _priv->errorHandler->error(exmsg, 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); } setFileInternal( rollover1->getActiveFileName(), rollover1->getAppend(), _priv->bufferedIO, _priv->bufferSize, p); } else { setFileInternal( rollover1->getActiveFileName(), true, _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) { LogLog::warn(LOG4CXX_STR("Exception during rollover")); LogString exmsg; log4cxx::helpers::Transcoder::decode(ex.what(), exmsg); _priv->errorHandler->error(exmsg, 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) { LogLog::warn(LOG4CXX_STR("Exception during rollover")); LogString exmsg; log4cxx::helpers::Transcoder::decode(ex.what(), exmsg); _priv->errorHandler->error(exmsg, 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) { LogLog::warn(LOG4CXX_STR("Exception during rollover attempt.")); LogString exmsg; log4cxx::helpers::Transcoder::decode(ex.what(), exmsg); _priv->errorHandler->error(exmsg); } } //do re-check before every write // apr_finfo_t finfo1, finfo2; apr_status_t st1, st2; const WriterPtr writer = getWriter(); const FileOutputStreamPtr fos = log4cxx::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::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 { 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.1.0/src/main/cpp/rolloverdescription.cpp000644 001750 001750 00000005401 14354342764 024301 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::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.1.0/src/main/cpp/socket.cpp000644 001750 001750 00000002670 14354342764 021466 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/rollingpolicybase.cpp000644 001750 001750 00000012532 14354342764 023715 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::helpers; using namespace log4cxx::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::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::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::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.1.0/src/main/cpp/outputstreamwriter.cpp000644 001750 001750 00000006124 14354342764 024205 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; 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.length() > 0) { #ifdef LOG4CXX_MULTI_PROCESS // Why does this need to happen for multiproces?? why?? size_t bufSize = str.length() * 2; char* rawbuf = new char[bufSize]; ByteBuffer buf(rawbuf, (size_t) bufSize); #else enum { BUFSIZE = 1024 }; char rawbuf[BUFSIZE]; ByteBuffer buf(rawbuf, (size_t) BUFSIZE); #endif 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); #ifdef LOG4CXX_MULTI_PROCESS delete []rawbuf; #endif } } OutputStreamPtr OutputStreamWriter::getOutputStreamPtr() const { return m_priv->out; } apache-log4cxx-1.1.0/src/main/cpp/outputstream.cpp000644 001750 001750 00000002053 14354342764 022745 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(OutputStream) OutputStream::OutputStream() { } OutputStream::~OutputStream() { } apache-log4cxx-1.1.0/src/main/cpp/triggeringpolicy.cpp000644 001750 001750 00000002007 14353331212 023532 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(TriggeringPolicy) TriggeringPolicy::~TriggeringPolicy() { } apache-log4cxx-1.1.0/src/main/cpp/timezone.cpp000644 001750 001750 00000014301 14354342764 022022 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT( TimeZone ) namespace log4cxx { namespace helpers { namespace TimeZoneImpl { /** Time zone object that represents GMT. */ class GMTTimeZone : public TimeZone { public: /** Class factory. */ static const TimeZonePtr& getInstance() { static TimeZonePtr 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 TimeZonePtr 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::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::helpers::TimeZoneImpl::LocalTimeZone::getInstance(); } const TimeZonePtr& TimeZone::getGMT() { return log4cxx::helpers::TimeZoneImpl::GMTTimeZone::getInstance(); } const TimeZonePtr TimeZone::getTimeZone( const LogString& id ) { const logchar gmt[] = { 0x47, 0x4D, 0x54, 0 }; if ( id == gmt ) { return log4cxx::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.1.0/src/main/cpp/zipcompressaction.cpp000644 001750 001750 00000010002 14354342764 023736 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::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::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 && priv->throwIOExceptionOnForkFailure) { throw IOException(stat); }else if(stat != APR_SUCCESS && !priv->throwIOExceptionOnForkFailure) { /* 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. */ LogLog::warn(LOG4CXX_STR("Failed to fork zip during log rotation; leaving log file uncompressed")); 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.1.0/src/main/cpp/outputdebugstringappender.cpp000644 001750 001750 00000002764 14354342764 025517 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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; using namespace log4cxx::helpers; using namespace log4cxx::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.1.0/src/main/cpp/defaultloggerfactory.cpp000644 001750 001750 00000002171 14354342764 024406 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; IMPLEMENT_LOG4CXX_OBJECT(DefaultLoggerFactory) LoggerPtr DefaultLoggerFactory::makeNewLoggerInstance( log4cxx::helpers::Pool& pool, const LogString& name) const { return std::make_shared(pool, name); } apache-log4cxx-1.1.0/src/main/cpp/socketappenderskeleton.cpp000644 001750 001750 00000015336 14424033175 024744 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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; using namespace log4cxx::helpers; using namespace log4cxx::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() { std::lock_guard lock(_priv->mutex); if (_priv->closed) { return; } _priv->closed = true; cleanUp(_priv->pool); { std::unique_lock lock2(_priv->interrupt_mutex); _priv->interrupt.notify_all(); } if ( _priv->thread.joinable() ) { _priv->thread.join(); } } 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 { SocketPtr socket = Socket::create(_priv->address, _priv->port); setSocket(socket, p); } catch (SocketException& e) { LogString msg = LOG4CXX_STR("Could not connect to [") + _priv->address->getHostName() + LOG4CXX_STR(":"); StringHelper::toString(_priv->port, p, msg); msg += LOG4CXX_STR("]."); if (_priv->reconnectionDelay > 0) { msg += LOG4CXX_STR(" We will try again in "); StringHelper::toString(_priv->reconnectionDelay, p, msg); msg += LOG4CXX_STR(" ms"); } 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() { SocketPtr socket; bool isClosed = _priv->closed; while (!isClosed) { try { if (!_priv->closed) { LogLog::debug(LogString(LOG4CXX_STR("Attempting connection to ")) + _priv->address->getHostName()); socket = Socket::create(_priv->address, _priv->port); Pool p; setSocket(socket, p); LogLog::debug(LOG4CXX_STR("Connection established. Exiting connector thread.")); return; } } catch (ConnectException&) { LogLog::debug(LOG4CXX_STR("Remote host ") + _priv->address->getHostName() + LOG4CXX_STR(" refused connection.")); } catch (IOException& e) { LogString exmsg; log4cxx::helpers::Transcoder::decode(e.what(), exmsg); LogLog::debug(((LogString) LOG4CXX_STR("Could not connect to ")) + _priv->address->getHostName() + LOG4CXX_STR(". Exception is ") + exmsg); } std::unique_lock lock( _priv->interrupt_mutex ); _priv->interrupt.wait_for( lock, std::chrono::milliseconds( _priv->reconnectionDelay ), std::bind(&SocketAppenderSkeleton::is_closed, this) ); isClosed = _priv->closed; } LogLog::debug(LOG4CXX_STR("Exiting Connector.run() method.")); } 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.1.0/src/main/cpp/serversocket.cpp000644 001750 001750 00000003045 14354342764 022712 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::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.1.0/src/main/cpp/defaultconfigurator.cpp000644 001750 001750 00000014113 14424032606 024225 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::spi; using namespace log4cxx::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]); 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)) { 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 (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 LogString LOG4CXX_DEFAULT_CONFIGURATION_KEY(LOG4CXX_STR("LOG4CXX_CONFIGURATION")); static const LogString 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 LogString 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::spi::ConfigurationStatus DefaultConfigurator::tryLoadFile(const LogString& filename){ if(helpers::StringHelper::endsWith(filename, LOG4CXX_STR(".xml"))){ return log4cxx::xml::DOMConfigurator::configure(filename); }else if(helpers::StringHelper::endsWith(filename, LOG4CXX_STR(".properties"))){ return log4cxx::PropertyConfigurator::configure(filename); } return log4cxx::spi::ConfigurationStatus::NotConfigured; } std::tuple DefaultConfigurator::configureFromFile(const std::vector& directories, const std::vector& filenames){ using ResultType = std::tuple; log4cxx::helpers::Pool pool; for( LogString dir : directories ){ for( LogString fname : filenames ){ LogString canidate_str = dir + LOG4CXX_STR("/") + fname; File candidate(canidate_str); LogString debugMsg = LOG4CXX_STR("Checking file "); debugMsg.append(canidate_str); LogLog::debug(debugMsg); if (candidate.exists(pool)) { log4cxx::spi::ConfigurationStatus configStatus = tryLoadFile(canidate_str); if( configStatus == log4cxx::spi::ConfigurationStatus::Configured ){ return ResultType{configStatus, canidate_str}; } LogLog::debug(LOG4CXX_STR("Unable to load file: trying next")); } } } return ResultType{log4cxx::spi::ConfigurationStatus::NotConfigured, LogString()}; } apache-log4cxx-1.1.0/src/main/cpp/jsonlayout.cpp000644 001750 001750 00000024144 14424033175 022374 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(JSONLayout) struct JSONLayout::JSONLayoutPrivate { JSONLayoutPrivate() : locationInfo(false), prettyPrint(false), dateFormat(), ppIndentL1(LOG4CXX_STR(" ")), ppIndentL2(LOG4CXX_STR(" ")) {} // Print no location info by default bool locationInfo; //= false bool prettyPrint; //= false helpers::ISO8601DateFormat dateFormat; LogString ppIndentL1; LogString ppIndentL2; }; 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; } LogString JSONLayout::getContentType() const { return LOG4CXX_STR("application/json"); } void JSONLayout::activateOptions(helpers::Pool& /* p */) { } void JSONLayout::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("PRETTYPRINT"), LOG4CXX_STR("prettyprint"))) { setPrettyPrint(OptionConverter::toBoolean(value, false)); } } void JSONLayout::format(LogString& output, const spi::LoggingEventPtr& event, Pool& p) const { 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->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.1.0/src/main/cpp/loglog.cpp000644 001750 001750 00000007206 14424032606 021446 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; struct LogLog::LogLogPrivate { LogLogPrivate() : debugEnabled(false), quietMode(false){} 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 LogLog internalLogger; return internalLogger; } void LogLog::setInternalDebugging(bool debugEnabled1) { std::unique_lock lock(getInstance().m_priv->mutex); getInstance().m_priv->debugEnabled = debugEnabled1; } void LogLog::debug(const LogString& msg) { if (!getInstance().m_priv->debugEnabled) { return; } std::unique_lock lock(getInstance().m_priv->mutex); emit(msg); } void LogLog::debug(const LogString& msg, const std::exception& e) { if (!getInstance().m_priv->debugEnabled) { return; } std::unique_lock lock(getInstance().m_priv->mutex); emit(msg); emit(e); } void LogLog::error(const LogString& msg) { std::unique_lock lock(getInstance().m_priv->mutex); emit(msg); } void LogLog::error(const LogString& msg, const std::exception& e) { std::unique_lock lock(getInstance().m_priv->mutex); emit(msg); emit(e); } void LogLog::setQuietMode(bool quietMode1) { std::unique_lock lock(getInstance().m_priv->mutex); getInstance().m_priv->quietMode = quietMode1; } void LogLog::warn(const LogString& msg) { std::unique_lock lock(getInstance().m_priv->mutex); emit(msg); } void LogLog::warn(const LogString& msg, const std::exception& e) { std::unique_lock lock(getInstance().m_priv->mutex); emit(msg); emit(e); } void LogLog::emit(const LogString& msg) { if (getInstance().m_priv->quietMode) { return; } LogString out(LOG4CXX_STR("log4cxx: ")); out.append(msg); out.append(1, (logchar) 0x0A); SystemErrWriter::write(out); } void LogLog::emit(const std::exception& ex) { if (getInstance().m_priv->quietMode) { return; } 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.1.0/src/main/cpp/cyclicbuffer.cpp000644 001750 001750 00000010005 14354342764 022625 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::spi; struct CyclicBuffer::CyclicBufferPriv { CyclicBufferPriv(int maxSize1) : ea(maxSize1), first(0), last(0), numElems(0), maxSize(maxSize1) {} log4cxx::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.1.0/src/main/cpp/systemerrwriter.cpp000644 001750 001750 00000003550 14353331212 023447 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/asyncappender.cpp000644 001750 001750 00000025530 14354342764 023032 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::spi; /** * The default buffer size is set to 128 events. */ enum { DEFAULT_BUFFER_SIZE = 128 }; class DiscardSummary { private: /** * First event of the highest severity. */ ::log4cxx::spi::LoggingEventPtr maxEvent; /** * Total count of messages discarded. */ int count; public: /** * Create new instance. * * @param event event, may not be null. */ DiscardSummary(const ::log4cxx::spi::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 ::log4cxx::spi::LoggingEventPtr& event); /** * Create event with summary information. * * @return new event. */ ::log4cxx::spi::LoggingEventPtr createEvent(::log4cxx::helpers::Pool& p); static ::log4cxx::spi::LoggingEventPtr createEvent(::log4cxx::helpers::Pool& p, size_t discardedCount); }; typedef std::map DiscardMap; struct AsyncAppender::AsyncAppenderPriv : public AppenderSkeleton::AppenderSkeletonPrivate { AsyncAppenderPriv() : AppenderSkeletonPrivate(), buffer(), bufferSize(DEFAULT_BUFFER_SIZE), appenders(std::make_shared(pool)), dispatcher(), locationInfo(false), blocking(true) {} /** * Event buffer. */ #if defined(NON_BLOCKING) boost::lockfree::queue buffer; std::atomic discardedCount; #else LoggingEventList buffer; #endif /** * Mutex used to guard access to buffer and discardMap. */ std::mutex bufferMutex; #if defined(NON_BLOCKING) ::log4cxx::helpers::Semaphore bufferNotFull; ::log4cxx::helpers::Semaphore bufferNotEmpty; #else std::condition_variable bufferNotFull; std::condition_variable bufferNotEmpty; #endif /** * Map of DiscardSummary objects keyed by logger name. */ DiscardMap discardMap; /** * Buffer size. */ int bufferSize; /** * Nested appenders. */ helpers::AppenderAttachableImplPtr appenders; /** * Dispatcher. */ std::thread dispatcher; /** * Should location info be included in dispatched messages. */ bool locationInfo; /** * Does appender block when buffer is full. */ bool blocking; }; 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) { std::lock_guard lock(priv->mutex); doAppendImpl(event, pool1); } void AsyncAppender::append(const spi::LoggingEventPtr& event, Pool& p) { if (priv->bufferSize <= 0) { priv->appenders->appendLoopOnAppenders(event, p); } if (!priv->dispatcher.joinable()) { priv->dispatcher = ThreadUtility::instance()->createThread( LOG4CXX_STR("AsyncAppender"), &AsyncAppender::dispatch, this ); } // Set the NDC and MDC for the calling thread as these // LoggingEvent fields were not set at event creation time. LogString ndcVal; event->getNDC(ndcVal); // Get a copy of this thread's MDC. event->getMDCCopy(); { std::unique_lock lock(priv->bufferMutex); while (true) { size_t previousSize = priv->buffer.size(); if (previousSize < (size_t)priv->bufferSize) { priv->buffer.push_back(event); if (previousSize == 0) { priv->bufferNotEmpty.notify_all(); } break; } // // Following code is only reachable if buffer is full // // // 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->bufferNotFull.wait(lock); 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() { { std::lock_guard lock(priv->bufferMutex); priv->closed = true; priv->bufferNotEmpty.notify_all(); priv->bufferNotFull.notify_all(); } if ( priv->dispatcher.joinable() ) { priv->dispatcher.join(); } { AppenderList appenderList = priv->appenders->getAllAppenders(); for (AppenderList::iterator iter = appenderList.begin(); iter != appenderList.end(); iter++) { (*iter)->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->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() ); } ::log4cxx::spi::LoggingEventPtr DiscardSummary::createEvent(::log4cxx::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::Level::getError(), msg, LocationInfo::getLocationUnavailable() ); } void AsyncAppender::dispatch() { bool isActive = true; while (isActive) { // // process events after lock on buffer is released. // Pool p; LoggingEventList events; { std::unique_lock lock(priv->bufferMutex); priv->bufferNotEmpty.wait(lock, [this]() -> bool { return 0 < priv->buffer.size() || priv->closed; } ); isActive = !priv->closed; for (LoggingEventList::iterator eventIter = priv->buffer.begin(); eventIter != priv->buffer.end(); eventIter++) { events.push_back(*eventIter); } for (DiscardMap::iterator discardIter = priv->discardMap.begin(); discardIter != priv->discardMap.end(); discardIter++) { events.push_back(discardIter->second.createEvent(p)); } priv->buffer.clear(); priv->discardMap.clear(); priv->bufferNotFull.notify_all(); } for (LoggingEventList::iterator iter = events.begin(); iter != events.end(); iter++) { try { priv->appenders->appendLoopOnAppenders(*iter, p); } catch (std::exception& ex) { priv->errorHandler->error(LOG4CXX_STR("async dispatcher"), ex, 0, *iter); isActive = false; } catch (...) { priv->errorHandler->error(LOG4CXX_STR("async dispatcher")); isActive = false; } } } } apache-log4cxx-1.1.0/src/main/cpp/loggermatchfilter.cpp000644 001750 001750 00000005361 14354342764 023700 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::filter; using namespace log4cxx::spi; using namespace log4cxx::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.1.0/src/main/cpp/nteventlogappender.cpp000644 001750 001750 00000021753 14354342764 024105 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; using namespace log4cxx::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.1.0/src/main/cpp/hierarchy.cpp000644 001750 001750 00000025510 14354342764 022152 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #include #include #include #include "assert.h" using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::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::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; }; IMPLEMENT_LOG4CXX_OBJECT(Hierarchy) Hierarchy::Hierarchy() : m_priv(std::make_unique()) { } Hierarchy::~Hierarchy() { std::unique_lock 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::unique_lock lock(m_priv->mutex); 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::clear() { std::unique_lock lock(m_priv->mutex); m_priv->loggers.clear(); } void Hierarchy::emitNoAppenderWarning(const Logger* logger) { bool emitWarning = false; { std::unique_lock 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::unique_lock 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::unique_lock 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::unique_lock lock(m_priv->mutex); clonedList = m_priv->listeners; } HierarchyEventListenerList::iterator it, itEnd = clonedList.end(); HierarchyEventListenerPtr listener; for (it = clonedList.begin(); it != itEnd; it++) { listener = *it; listener->addAppenderEvent(logger, appender); } } void Hierarchy::fireRemoveAppenderEvent(const Logger* logger, const Appender* appender) { HierarchyEventListenerList clonedList; { std::unique_lock lock(m_priv->mutex); clonedList = m_priv->listeners; } HierarchyEventListenerList::iterator it, itEnd = clonedList.end(); HierarchyEventListenerPtr listener; for (it = clonedList.begin(); it != itEnd; it++) { listener = *it; listener->removeAppenderEvent(logger, appender); } } LevelPtr Hierarchy::getThreshold() const { return m_priv->threshold ? m_priv->threshold : Level::getAll(); } LoggerPtr Hierarchy::getLogger(const LogString& name) { static spi::LoggerFactoryPtr defaultFactory = std::make_shared(); return getLogger(name, defaultFactory); } LoggerPtr Hierarchy::getLogger(const LogString& name, const spi::LoggerFactoryPtr& factory) { auto root = getRootLogger(); std::unique_lock 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) { LoggerPtr logger(factory->makeNewLoggerInstance(m_priv->pool, name)); 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::unique_lock 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::unique_lock lock(m_priv->mutex); if (!m_priv->root) { m_priv->root = std::make_shared(m_priv->pool, 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::unique_lock lock(m_priv->configuredMutex); if (!m_priv->configured) { configurator(); m_priv->configured = true; } } void Hierarchy::resetConfiguration() { std::unique_lock lock(m_priv->mutex); if (m_priv->root) { m_priv->root->setLevel(Level::getDebug()); m_priv->root->setResourceBundle(0); } setThresholdInternal(Level::getAll()); shutdownInternal(); LoggerMap::const_iterator it, itEnd = m_priv->loggers.end(); for (it = m_priv->loggers.begin(); it != itEnd; it++) { if (auto pLogger = it->second) { pLogger->setLevel(0); pLogger->setAdditivity(true); pLogger->setResourceBundle(0); } } //rendererMap.clear(); } void Hierarchy::shutdown() { std::unique_lock 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(); LoggerMap::iterator it, itEnd = m_priv->loggers.end(); for (it = m_priv->loggers.begin(); it != itEnd; it++) { if (auto pLogger = it->second) pLogger->closeNestedAppenders(); } // then, remove all appenders if (m_priv->root) m_priv->root->removeAllAppenders(); for (it = m_priv->loggers.begin(); it != itEnd; it++) { if (auto pLogger = it->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) { ProvisionNode::iterator it, itEnd = pn.end(); for (it = pn.begin(); it != itEnd; it++) { LoggerPtr& l = *it; // 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::unique_lock 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); } apache-log4cxx-1.1.0/src/main/cpp/threadlocal.cpp000644 001750 001750 00000003303 14353331212 022433 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::helpers; using namespace log4cxx; 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.1.0/src/main/cpp/stringhelper.cpp000644 001750 001750 00000010305 14424032606 022663 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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; using namespace log4cxx::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.1.0/src/main/cpp/gzcompressaction.cpp000644 001750 001750 00000011216 14354342764 023564 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::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::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(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 && priv->throwIOExceptionOnForkFailure) { throw IOException(stat); }else if(stat != APR_SUCCESS && !priv->throwIOExceptionOnForkFailure) { /* 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. */ LogLog::warn(LOG4CXX_STR("Failed to fork gzip during log rotation; leaving log file uncompressed")); stat = apr_file_close(child_out); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("Failed to close abandoned .gz file; ignoring")); } 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.1.0/src/main/cpp/aprdatagramsocket.cpp000644 001750 001750 00000012040 14424032606 023647 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { 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.1.0/src/main/cpp/bufferedwriter.cpp000644 001750 001750 00000003740 14354342764 023214 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/fmtlayout.cpp000644 001750 001750 00000010662 14424032606 022207 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::spi; struct FMTLayout::FMTLayoutPrivate{ FMTLayoutPrivate(){} FMTLayoutPrivate(const LogString& pattern) : conversionPattern(pattern) {} LogString conversionPattern; }; 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&) { } void FMTLayout::format(LogString& output, const spi::LoggingEventPtr& event, log4cxx::helpers::Pool&) const { 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), 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.1.0/src/main/cpp/ndc.cpp000644 001750 001750 00000014615 14424043276 020736 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; NDC::NDC(const std::string& message) { push(message); } NDC::~NDC() { pop(); } LogString& NDC::getMessage(NDC::DiagnosticContext& ctx) { return ctx.first; } LogString& NDC::getFullMessage(NDC::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.1.0/src/main/cpp/charsetencoder.cpp000644 001750 001750 00000034255 14354342764 023173 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #ifdef LOG4CXX_HAS_WCSTOMBS #include #endif using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(CharsetEncoder) namespace log4cxx { 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::unique_lock 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::unique_lock 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 an embedded CharsetEncoder consistent * with current locale settings. */ class LocaleCharsetEncoder : public CharsetEncoder { public: LocaleCharsetEncoder() : pool(), encoder(), encoding() { } virtual ~LocaleCharsetEncoder() { } virtual log4cxx_status_t encode(const LogString& in, LogString::const_iterator& iter, ByteBuffer& out) { #if !LOG4CXX_CHARSET_EBCDIC char* current = out.current(); size_t remain = out.remaining(); for (; iter != in.end() && ((unsigned int) *iter) < 0x80 && remain > 0; iter++, remain--, current++) { *current = *iter; } out.position(current - out.data()); #endif if (iter != in.end() && out.remaining() > 0) { Pool subpool; const char* enc = apr_os_locale_encoding(subpool.getAPRPool()); { std::unique_lock lock(mutex); if (enc == 0) { if (encoder == 0) { encoding = "C"; encoder.reset( new USASCIICharsetEncoder() ); } } else if (encoding != enc) { encoding = enc; LogString ename; Transcoder::decode(encoding, ename); try { encoder = CharsetEncoder::getEncoder(ename); } catch (IllegalArgumentException&) { encoder.reset( new USASCIICharsetEncoder() ); } } } return encoder->encode(in, iter, out); } return APR_SUCCESS; } private: LocaleCharsetEncoder(const LocaleCharsetEncoder&); LocaleCharsetEncoder& operator=(const LocaleCharsetEncoder&); Pool pool; std::mutex mutex; CharsetEncoderPtr encoder; std::string encoding; }; } // namespace helpers } //namespace log4cxx CharsetEncoder::CharsetEncoder() { } CharsetEncoder::~CharsetEncoder() { } CharsetEncoderPtr CharsetEncoder::getDefaultEncoder() { static CharsetEncoderPtr 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 == 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"))) { 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"))) { 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"))) { 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"))) { return std::make_shared(); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-16LE"), LOG4CXX_STR("utf-16le"))) { 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); } } apache-log4cxx-1.1.0/src/main/cpp/telnetappender.cpp000644 001750 001750 00000016177 14354342764 023217 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; 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()), sh(), activeConnections(0) {} int port; ConnectionList connections; LogString encoding; log4cxx::helpers::CharsetEncoderPtr encoder; std::unique_ptr serverSocket; std::thread sh; size_t activeConnections; }; #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); } _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("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() { std::lock_guard lock(_priv->mutex); if (_priv->closed) { return; } _priv->closed = true; SocketPtr nullSocket; for (ConnectionList::iterator iter = _priv->connections.begin(); iter != _priv->connections.end(); iter++) { if (*iter != 0) { (*iter)->close(); *iter = nullSocket; } } if (_priv->serverSocket != NULL) { try { _priv->serverSocket->close(); } catch (Exception&) { } } if ( _priv->sh.joinable() ) { _priv->sh.join(); } _priv->activeConnections = 0; } void TelnetAppender::write(ByteBuffer& buf) { for (ConnectionList::iterator iter = _priv->connections.begin(); iter != _priv->connections.end(); iter++) { if (*iter != 0) { try { ByteBuffer b(buf.current(), buf.remaining()); (*iter)->write(b); } catch (Exception&) { // The client has closed the connection, remove it from our list: *iter = 0; _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; _priv->layout->format(msg, event, _priv->pool); 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 (ConnectionList::iterator iter = _priv->connections.begin(); iter != _priv->connections.end(); iter++) { if (*iter == NULL) { *iter = 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; } apache-log4cxx-1.1.0/src/main/cpp/messagepatternconverter.cpp000644 001750 001750 00000005233 14424032606 025133 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; IMPLEMENT_LOG4CXX_OBJECT(MessagePatternConverter) /** * 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 PatternConverterPtr 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.1.0/src/main/cpp/onlyonceerrorhandler.cpp000644 001750 001750 00000004521 14354342764 024431 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(OnlyOnceErrorHandler) struct OnlyOnceErrorHandler::OnlyOnceErrorHandlerPrivate{ OnlyOnceErrorHandlerPrivate() : WARN_PREFIX(LOG4CXX_STR("log4cxx warning: ")), ERROR_PREFIX(LOG4CXX_STR("log4cxx error: ")), firstTime(true){} LogString WARN_PREFIX; LogString ERROR_PREFIX; 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::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&) { } apache-log4cxx-1.1.0/src/main/cpp/threadpatternconverter.cpp000644 001750 001750 00000003153 14354342764 024770 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ThreadPatternConverter) ThreadPatternConverter::ThreadPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Thread"), LOG4CXX_STR("Thread")) { } PatternConverterPtr ThreadPatternConverter::newInstance( const std::vector& /* options */) { static PatternConverterPtr def = std::make_shared(); return def; } void ThreadPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(event->getThreadName()); } apache-log4cxx-1.1.0/src/main/cpp/fileappender.cpp000644 001750 001750 00000021524 14354342764 022633 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::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, true); } 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.1.0/src/main/cpp/cacheddateformat.cpp000644 001750 001750 00000026570 14354342764 023461 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::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::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) { apr_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.1.0/src/main/cpp/filter.cpp000644 001750 001750 00000002607 14354342764 021463 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::spi; using namespace log4cxx::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.1.0/src/main/cpp/datagramsocket.cpp000644 001750 001750 00000004730 14354342764 023166 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 "apr_network_io.h" #include "apr_lib.h" using namespace log4cxx::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){ std::unique_ptr sock = std::make_unique(); InetAddressPtr bindAddr = InetAddress::anyAddress(); sock->bind(localPort1, bindAddr); return sock; } DatagramSocketUniquePtr DatagramSocket::create(int localPort1, InetAddressPtr localAddress1){ std::unique_ptr sock = std::make_unique(); sock->bind(localPort1, localAddress1); return sock; } apache-log4cxx-1.1.0/src/main/cpp/datagrampacket.cpp000644 001750 001750 00000007464 14354342764 023154 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::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.1.0/src/main/cpp/levelpatternconverter.cpp000644 001750 001750 00000004610 14354342764 024627 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(LevelPatternConverter) LevelPatternConverter::LevelPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Level"), LOG4CXX_STR("level")) { } PatternConverterPtr LevelPatternConverter::newInstance( const std::vector& /* options */) { static PatternConverterPtr def = std::make_shared(); return def; } void LevelPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& /* p */) const { toAppendTo.append(event->getLevel()->toString()); } /** * {@inheritDoc} */ LogString LevelPatternConverter::getStyleClass(const ObjectPtr& obj) const { LoggingEventPtr e = log4cxx::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.1.0/src/main/cpp/messagebuffer.cpp000644 001750 001750 00000042635 14354342764 023021 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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_CFSTRING_API) #define __FORCE_INSTANCE #endif #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include using namespace log4cxx::helpers; template void ResetStream(std::basic_ostringstream& stream) { stream.seekp(0); stream.str(std::basic_string()); stream.clear(); } struct CharMessageBuffer::CharMessageBufferPrivate{ CharMessageBufferPrivate() : stream(nullptr){} /** * Encapsulated std::string. */ std::basic_string buf; /** * Encapsulated stream, created on demand. */ std::basic_ostringstream* stream; }; CharMessageBuffer::CharMessageBuffer() : m_priv(std::make_unique()) { } CharMessageBuffer::~CharMessageBuffer() { #if !LOG4CXX_HAS_THREAD_LOCAL delete m_priv->stream; #endif } 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& () { if (!m_priv->stream) { #if LOG4CXX_HAS_THREAD_LOCAL thread_local static std::basic_ostringstream sStream; m_priv->stream = &sStream; #else m_priv->stream = new std::basic_ostringstream(); #endif if (!m_priv->buf.empty()) { *m_priv->stream << m_priv->buf; } } return *m_priv->stream; } const std::basic_string& CharMessageBuffer::str(std::basic_ostream&) { m_priv->buf = m_priv->stream->str(); ResetStream(*m_priv->stream); return m_priv->buf; } 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{ WideMessageBufferPrivate() : stream(nullptr){} /** * Encapsulated std::string. */ std::basic_string buf; /** * Encapsulated stream, created on demand. */ std::basic_ostringstream* stream; }; WideMessageBuffer::WideMessageBuffer() : m_priv(std::make_unique()) { } WideMessageBuffer::~WideMessageBuffer() { #if !LOG4CXX_HAS_THREAD_LOCAL delete m_priv->stream; #endif } 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& () { if (!m_priv->stream) { #if LOG4CXX_HAS_THREAD_LOCAL thread_local static std::basic_ostringstream sStream; m_priv->stream = &sStream; #else m_priv->stream = new std::basic_ostringstream(); #endif if (!m_priv->buf.empty()) { *m_priv->stream << m_priv->buf; } } return *m_priv->stream; } const std::basic_string& WideMessageBuffer::str(std::basic_ostream&) { m_priv->buf = m_priv->stream->str(); ResetStream(*m_priv->stream); return m_priv->buf; } 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 || LOG4CXX_CFSTRING_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 || LOG4CXX_CFSTRING_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); } 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; } 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 || LOG4CXX_CFSTRING_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::UniChar* msg) { m_priv->ubuf = std::make_unique(); return (*m_priv->ubuf) << msg; } UniCharMessageBuffer& MessageBuffer::operator<<(log4cxx::UniChar* msg) { m_priv->ubuf = std::make_unique(); return (*m_priv->ubuf) << (const log4cxx::UniChar*) msg; } UniCharMessageBuffer& MessageBuffer::operator<<(const log4cxx::UniChar msg) { m_priv->ubuf = std::make_unique(); return (*m_priv->ubuf) << msg; } 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 || LOG4CXX_CFSTRING_API #endif // LOG4CXX_WCHAR_T_API #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API struct UniCharMessageBuffer::UniCharMessageBufferPrivate { UniCharMessageBufferPrivate() : stream(nullptr){} /** * Encapsulated std::string. */ std::basic_string buf; /** * Encapsulated stream, created on demand. */ std::basic_ostringstream* stream; }; UniCharMessageBuffer::UniCharMessageBuffer() : m_priv(std::make_unique()) { } UniCharMessageBuffer::~UniCharMessageBuffer() { #if !LOG4CXX_HAS_THREAD_LOCAL delete m_priv->stream; #endif } 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::UniChar* msg) { const log4cxx::UniChar* actualMsg = msg; static log4cxx::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::UniChar* msg) { return operator<<((const log4cxx::UniChar*) msg); } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const log4cxx::UniChar msg) { if (!m_priv->stream) { m_priv->buf.append(1, msg); } else { *m_priv->stream << msg; } return *this; } UniCharMessageBuffer::operator UniCharMessageBuffer::uostream& () { if (!m_priv->stream) { #if LOG4CXX_HAS_THREAD_LOCAL thread_local static std::basic_ostringstream sStream; m_priv->stream = &sStream; #else m_priv->stream = new std::basic_ostringstream(); #endif if (!m_priv->buf.empty()) { *m_priv->stream << m_priv->buf; } } return *m_priv->stream; } const std::basic_string& UniCharMessageBuffer::str(UniCharMessageBuffer::uostream&) { m_priv->buf = m_priv->stream->str(); ResetStream(*m_priv->stream); return m_priv->buf; } 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 || LOG4CXX_CFSTRING_API #if LOG4CXX_CFSTRING_API #include #include UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const CFStringRef& msg) { const log4cxx::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; } #endif // LOG4CXX_CFSTRING_API apache-log4cxx-1.1.0/src/main/cpp/level.cpp000644 001750 001750 00000014037 14354342764 021305 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(Level, LevelClass) LevelPtr Level::getOff() { static LevelPtr offLevel = std::make_shared(Level::OFF_INT, LOG4CXX_STR("OFF"), 0); return offLevel; } LevelPtr Level::getFatal() { static LevelPtr fatalLevel = std::make_shared(Level::FATAL_INT, LOG4CXX_STR("FATAL"), 0); return fatalLevel; } LevelPtr Level::getError() { static LevelPtr errorLevel = std::make_shared(Level::ERROR_INT, LOG4CXX_STR("ERROR"), 3); return errorLevel; } LevelPtr Level::getWarn() { static LevelPtr warnLevel = std::make_shared(Level::WARN_INT, LOG4CXX_STR("WARN"), 4); return warnLevel; } LevelPtr Level::getInfo() { static LevelPtr infoLevel = std::make_shared(Level::INFO_INT, LOG4CXX_STR("INFO"), 6); return infoLevel; } LevelPtr Level::getDebug() { static LevelPtr debugLevel = std::make_shared(Level::DEBUG_INT, LOG4CXX_STR("DEBUG"), 7); return debugLevel; } LevelPtr Level::getTrace() { static LevelPtr traceLevel = std::make_shared(Level::TRACE_INT, LOG4CXX_STR("TRACE"), 7); return traceLevel; } LevelPtr Level::getAll() { static LevelPtr 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) { APRInitializer::initialize(); } 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()); } 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 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.1.0/src/main/cpp/appenderskeleton.cpp000644 001750 001750 00000011075 14354342764 023540 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::spi; using namespace log4cxx::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& layout1) : m_priv(std::make_unique()) { } 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); } 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.1.0/src/main/cpp/lineseparatorpatternconverter.cpp000644 001750 001750 00000003502 14354342764 026367 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(LineSeparatorPatternConverter) LineSeparatorPatternConverter::LineSeparatorPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Line Sep"), LOG4CXX_STR("lineSep")) { } PatternConverterPtr LineSeparatorPatternConverter::newInstance( const std::vector& /* options */) { static PatternConverterPtr 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.1.0/src/main/cpp/patternlayout.cpp000644 001750 001750 00000022144 14424033175 023076 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::spi; using namespace log4cxx::pattern; struct PatternLayout::PatternLayoutPrivate { PatternLayoutPrivate() {} PatternLayoutPrivate(const LogString& pattern) : conversionPattern(pattern) {} /** * 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; }; 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 { 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; LogLog::debug(LOG4CXX_STR("Setting error color to ")); LogLog::debug(value); }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 (std::vector::const_iterator converterIter = converters.begin(); converterIter != converters.end(); converterIter++) { LoggingEventPatternConverterPtr eventConverter = log4cxx::cast(*converterIter); if (eventConverter != NULL) { m_priv->patternConverters.push_back(eventConverter); } } } #define RULES_PUT(spec, cls) \ specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR(spec)), cls ::newInstance)) log4cxx::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.1.0/src/main/cpp/smtpappender.cpp000644 001750 001750 00000044077 14424032606 022674 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::net; using namespace log4cxx::spi; #if LOG4CXX_HAVE_LIBESMTP #include #include #endif namespace log4cxx { 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 (LogString::const_iterator iter = str.begin(); iter != str.end(); iter++) { unsigned int c = *iter; 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; // // iterator through message // for (LogString::const_iterator iter = str.begin(); iter != str.end(); iter++) { unsigned int c = *iter; // // 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 *current++ = 0x0D; *current++ = 0x0A; startOfLine = current; LogString::const_iterator next = iter + 1; if (next != str.end() && (*next == 0x0A || *next == 0x0D)) { iter++; } } 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 (LogString::const_iterator iter = value.begin(); iter != value.end(); iter++) { if (0x7F < (unsigned int) *iter) { 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; } LogString ndc; event->getNDC(ndc); event->getThreadName(); // Get a copy of this thread's MDC. event->getMDCCopy(); _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) { LogLog::error(LOG4CXX_STR("Error occured while sending e-mail notification."), e); } #endif } /** Returns value of the EvaluatorClass option. */ LogString SMTPAppender::getEvaluatorClass() { return _priv->evaluator == 0 ? LogString() : _priv->evaluator->getClass().getName(); } log4cxx::spi::TriggeringEventEvaluatorPtr SMTPAppender::getEvaluator() const { return _priv->evaluator; } void SMTPAppender::setEvaluator(log4cxx::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::cast(obj); } int SMTPAppender::getBufferSize() const { return _priv->bufferSize; } apache-log4cxx-1.1.0/src/main/cpp/systemoutwriter.cpp000644 001750 001750 00000003553 14353331212 023471 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/ndcpatternconverter.cpp000644 001750 001750 00000003164 14354342764 024267 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(NDCPatternConverter) NDCPatternConverter::NDCPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("NDC"), LOG4CXX_STR("ndc")) { } PatternConverterPtr NDCPatternConverter::newInstance( const std::vector& /* options */) { static PatternConverterPtr 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.1.0/src/main/cpp/dbappender.cpp000644 001750 001750 00000021370 14424033655 022272 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::db; using namespace log4cxx::spi; using namespace log4cxx::pattern; IMPLEMENT_LOG4CXX_OBJECT(DBAppender) #define _priv static_cast(m_priv.get()) struct DBAppender::DBAppenderPriv : public AppenderSkeleton::AppenderSkeletonPrivate { DBAppenderPriv() : AppenderSkeletonPrivate() {} 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::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, 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.1.0/src/main/cpp/pool.cpp000644 001750 001750 00000004152 14353331212 021125 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::helpers; using namespace log4cxx; Pool::Pool() : pool(0), release(true) { apr_status_t stat = apr_pool_create(&pool, APRInitializer::getRootPool()); if (stat != APR_SUCCESS) { throw PoolException(stat); } } Pool::Pool(apr_pool_t* p, bool release1) : pool(p), release(release1) { assert(p != NULL); } Pool::~Pool() { if (release) { apr_pool_destroy(pool); } } apr_pool_t* Pool::getAPRPool() { return pool; } apr_pool_t* Pool::create() { 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) { return apr_palloc(pool, size); } char* Pool::pstralloc(size_t size) { return (char*) palloc(size); } char* Pool::itoa(int n) { return apr_itoa(pool, n); } char* Pool::pstrndup(const char* s, size_t len) { return apr_pstrndup(pool, s, len); } char* Pool::pstrdup(const char* s) { return apr_pstrdup(pool, s); } char* Pool::pstrdup(const std::string& s) { return apr_pstrndup(pool, s.data(), s.length()); } apache-log4cxx-1.1.0/src/main/cpp/optionconverter.cpp000644 001750 001750 00000024406 14354342764 023437 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #if APR_HAS_THREADS #include namespace log4cxx { 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() { m_config->doConfigure(file(), LogManager::getLoggerRepository()); } }; } #endif using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::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 { 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); LogLog::debug(((LogString) 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 (clazz.empty() && filename.length() > 4 && StringHelper::equalsIgnoreCase( filename.substr(filename.length() - 4), LOG4CXX_STR(".XML"), LOG4CXX_STR(".xml"))) { clazz = log4cxx::xml::DOMConfigurator::getStaticClass().toString(); } if (!clazz.empty()) { LogLog::debug(LOG4CXX_STR("Preferred configurator class: ") + clazz); const Class& clazzObj = Loader::loadClass(clazz); ObjectPtr obj = ObjectPtr(clazzObj.newInstance()); configurator = log4cxx::cast(obj); if (configurator == 0) { LogLog::error(LOG4CXX_STR("Could not instantiate configurator [") + clazz + LOG4CXX_STR("].")); return; } } else { configurator = std::make_shared(); } #if APR_HAS_THREADS if (0 < delay) { auto dog = new ConfiguratorWatchdog(configurator, configFileName); APRInitializer::registerCleanup(dog); dog->setDelay(delay); dog->start(); } else #endif configurator->doConfigure(configFileName, hierarchy); } apache-log4cxx-1.1.0/src/main/cpp/syslogwriter.cpp000644 001750 001750 00000004534 14354342764 022754 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/colorstartpatternconverter.cpp000644 001750 001750 00000020772 14424032606 025710 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::pattern; using namespace log4cxx::spi; using namespace log4cxx::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 PatternConverterPtr instance = std::make_shared(); return instance; } void ColorStartPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { log4cxx::LevelPtr lvl = event->getLevel(); switch (lvl->toInt()) { case log4cxx::Level::FATAL_INT: toAppendTo.append(priv->m_fatalColor); break; case log4cxx::Level::ERROR_INT: toAppendTo.append(priv->m_errorColor); break; case log4cxx::Level::WARN_INT: toAppendTo.append(priv->m_warnColor); break; case log4cxx::Level::INFO_INT: toAppendTo.append(priv->m_infoColor); break; case log4cxx::Level::DEBUG_INT: toAppendTo.append(priv->m_debugColor); break; case log4cxx::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.1.0/src/main/cpp/threadspecificdata.cpp000644 001750 001750 00000007006 14354342764 024003 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; struct ThreadSpecificData::ThreadSpecificDataPrivate{ log4cxx::NDC::Stack ndcStack; log4cxx::MDC::Map mdcMap; }; ThreadSpecificData::ThreadSpecificData() : m_priv(std::make_unique()) { } ThreadSpecificData::~ThreadSpecificData() { } log4cxx::NDC::Stack& ThreadSpecificData::getStack() { return m_priv->ndcStack; } log4cxx::MDC::Map& ThreadSpecificData::getMap() { return m_priv->mdcMap; } ThreadSpecificData& ThreadSpecificData::getDataNoThreads() { static ThreadSpecificData noThreadData; return noThreadData; } ThreadSpecificData* ThreadSpecificData::getCurrentData() { #if APR_HAS_THREADS void* pData = NULL; apr_threadkey_private_get(&pData, APRInitializer::getTlsKey()); return (ThreadSpecificData*) pData; #else return &getDataNoThreads(); #endif } void ThreadSpecificData::recycle() { #if APR_HAS_THREADS if (m_priv->ndcStack.empty() && m_priv->mdcMap.empty()) { void* pData = NULL; apr_status_t stat = apr_threadkey_private_get(&pData, APRInitializer::getTlsKey()); if (stat == APR_SUCCESS && pData == this) { stat = apr_threadkey_private_set(0, APRInitializer::getTlsKey()); if (stat == APR_SUCCESS) { delete this; } } } #endif } void ThreadSpecificData::put(const LogString& key, const LogString& val) { ThreadSpecificData* data = getCurrentData(); if (data == 0) { data = createCurrentData(); } if (data != 0) { data->getMap()[key] = val; } } void ThreadSpecificData::push(const LogString& val) { ThreadSpecificData* data = getCurrentData(); if (data == 0) { data = createCurrentData(); } if (data != 0) { NDC::Stack& stack = data->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) { ThreadSpecificData* data = getCurrentData(); if (data == 0) { data = createCurrentData(); } if (data != 0) { data->getStack() = src; } } ThreadSpecificData* ThreadSpecificData::createCurrentData() { #if APR_HAS_THREADS ThreadSpecificData* newData = new ThreadSpecificData(); apr_status_t stat = apr_threadkey_private_set(newData, APRInitializer::getTlsKey()); if (stat != APR_SUCCESS) { delete newData; newData = NULL; } return newData; #else return 0; #endif } apache-log4cxx-1.1.0/src/main/cpp/aprserversocket.cpp000644 001750 001750 00000007256 14424032606 023412 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { 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::unique_lock 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() { std::unique_lock lock(_priv->mutex); if (_priv->socket == 0) { throw IOException(); } 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 = _priv->socket; 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, _priv->socket, 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.1.0/src/main/cpp/inetaddress.cpp000644 001750 001750 00000007662 14354342764 022511 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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) { return getAllByName(host)[0]; } /** 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()); rv.append(LOG4CXX_STR("/")); rv.append(getHostAddress()); return rv; } apache-log4cxx-1.1.0/src/main/cpp/patternconverter.cpp000644 001750 001750 00000003301 14354342764 023573 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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::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.1.0/src/main/cpp/manualtriggeringpolicy.cpp000644 001750 001750 00000002752 14353331212 024737 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ManualTriggeringPolicy) ManualTriggeringPolicy::ManualTriggeringPolicy() { } bool ManualTriggeringPolicy::isTriggeringEvent(Appender* /* appender */, const log4cxx::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.1.0/src/main/cpp/patternparser.cpp000644 001750 001750 00000022770 14354342764 023073 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::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.1.0/src/main/cpp/fileinputstream.cpp000644 001750 001750 00000005625 14354342764 023414 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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(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(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.1.0/src/main/cpp/action.cpp000644 001750 001750 00000003670 14354342764 021454 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::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::helpers::Pool& pool1) { std::unique_lock 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::unique_lock 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.1.0/src/main/cpp/fulllocationpatternconverter.cpp000644 001750 001750 00000003647 14354342764 026224 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(FullLocationPatternConverter) FullLocationPatternConverter::FullLocationPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Full Location"), LOG4CXX_STR("fullLocation")) { } PatternConverterPtr FullLocationPatternConverter::newInstance( const std::vector& /* options */) { static PatternConverterPtr 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.1.0/src/main/cpp/mapfilter.cpp000644 001750 001750 00000006722 14354342764 022163 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::filter; using namespace log4cxx::spi; using namespace log4cxx::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::spi::LoggingEventPtr& event) const { if (priv->keyVals.empty()) { return Filter::NEUTRAL; } bool matched = true; for (KeyVals::const_iterator it = priv->keyVals.begin(); it != priv->keyVals.end(); ++it) { LogString curval; event->getMDC(it->first, curval); if (curval.empty() || curval != it->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 LogString empty; const KeyVals::const_iterator it(priv->keyVals.find(strKey)); return (it != priv->keyVals.end() ? it->second : empty); } 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.1.0/src/main/cpp/filedatepatternconverter.cpp000644 001750 001750 00000002565 14354342764 025304 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::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.1.0/src/main/cpp/CMakeLists.txt000644 001750 001750 00000015334 14424033655 022225 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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(BUILD_SHARED_LIBS) target_compile_definitions(log4cxx PRIVATE LOG4CXX) else() target_compile_definitions(log4cxx PUBLIC LOG4CXX_STATIC) endif() add_dependencies(log4cxx configure_log4cxx) set(extra_classes "") if(LOG4CXX_NETWORKING_SUPPORT) set(extra_classes ${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() set(extra_classes ${extra_classes} multiprocessrollingfileappender.cpp ) endif() if(${ENABLE_FMT_LAYOUT}) set(extra_classes ${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 domconfigurator.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 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} ) set_target_properties(log4cxx PROPERTIES VERSION ${LIBLOG4CXX_LIB_VERSION} SOVERSION ${LIBLOG4CXX_LIB_SOVERSION} ) boostfallback_link(log4cxx) 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) 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.1.0/src/main/cpp/strftimedateformat.cpp000644 001750 001750 00000003740 14354342764 024101 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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::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::helpers::Transcoder::decode(std::string(buf, bufLen), s); } } } void StrftimeDateFormat::setTimeZone(const TimeZonePtr& zone) { m_priv->timeZone = zone; } apache-log4cxx-1.1.0/src/main/cpp/levelrangefilter.cpp000644 001750 001750 00000007373 14354342764 023535 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::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.1.0/src/main/cpp/logstream.cpp000644 001750 001750 00000030233 14353331212 022150 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 || LOG4CXX_CFSTRING_API) #define __FORCE_INSTANCE #endif #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include using namespace log4cxx; 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::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::logstream_base::precision() { get_stream_state(initclear, initset, fillchar, fillset); return (int)initclear.precision(); } int log4cxx::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::logstream_base::width() { get_stream_state(initclear, initset, fillchar, fillset); return (int)initclear.width(); } int log4cxx::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::LevelPtr& newlevel) { level = newlevel; bool oldLevel = enabled; enabled = logger->isEnabledFor(level); if (oldLevel != enabled) { erase(); } } bool logstream_base::isEnabledFor(const ::log4cxx::LevelPtr& l) const { return logger->isEnabledFor(l); } void logstream_base::setLocation(const log4cxx::spi::LocationInfo& newlocation) { if (LOG4CXX_UNLIKELY(enabled)) { location = newlocation; } } logstream::logstream(const log4cxx::LoggerPtr& logger, const log4cxx::LevelPtr& level) : logstream_base(logger, level), stream(0) { } logstream::logstream(const Ch* loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } logstream::logstream(const std::basic_string& loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::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::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } logstream& logstream::operator>>(const log4cxx::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::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::LoggerPtr& logger, const log4cxx::LevelPtr& level) : logstream_base(logger, level), stream(0) { } wlogstream::wlogstream(const Ch* loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } wlogstream::wlogstream(const std::basic_string& loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::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::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } wlogstream& wlogstream::operator>>(const log4cxx::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::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::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } ulogstream::ulogstream(const std::basic_string& loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } #endif #if LOG4CXX_CFSTRING_API ulogstream::ulogstream(const CFStringRef& loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API ulogstream::ulogstream(const log4cxx::LoggerPtr& logger, const log4cxx::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::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } ulogstream& ulogstream::operator>>(const log4cxx::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::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.1.0/src/main/cpp/filerenameaction.cpp000644 001750 001750 00000003367 14354342764 023507 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::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::helpers::Pool& pool1) const { return priv->source.renameTo(priv->destination, pool1); } apache-log4cxx-1.1.0/src/main/cpp/nameabbreviator.cpp000644 001750 001750 00000020165 14354342764 023336 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(NameAbbreviator) NameAbbreviator::NameAbbreviator() { } NameAbbreviator::~NameAbbreviator() { } namespace log4cxx { 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 NameAbbreviatorPtr def = std::make_shared(); return def; } apache-log4cxx-1.1.0/src/main/cpp/throwableinformationpatternconverter.cpp000644 001750 001750 00000005237 14354342764 027763 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::pattern; using namespace log4cxx::spi; using namespace log4cxx::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 PatternConverterPtr shortConverter = std::make_shared(true); return shortConverter; } static PatternConverterPtr 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.1.0/src/main/cpp/dateformat.cpp000644 001750 001750 00000002322 14353331212 022277 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/appenderattachableimpl.cpp000644 001750 001750 00000011031 14354342764 024656 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(AppenderAttachableImpl) struct AppenderAttachableImpl::priv_data { /** Array of appenders. */ AppenderList appenderList; mutable std::recursive_mutex m_mutex; }; AppenderAttachableImpl::AppenderAttachableImpl(Pool& pool) : m_priv(std::make_unique()) { } AppenderAttachableImpl::~AppenderAttachableImpl() { } void AppenderAttachableImpl::addAppender(const AppenderPtr newAppender) { // Null values for newAppender parameter are strictly forbidden. if (newAppender == 0) { return; } 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; std::lock_guard lock( m_priv->m_mutex ); // 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 = m_priv->appenderList; for (auto appender : allAppenders) { appender->doAppend(event, p); numberAppended++; } return numberAppended; } AppenderList AppenderAttachableImpl::getAllAppenders() const { std::lock_guard lock( m_priv->m_mutex ); return m_priv->appenderList; } AppenderPtr AppenderAttachableImpl::getAppender(const LogString& name) const { if (name.empty()) { return 0; } std::lock_guard lock( m_priv->m_mutex ); AppenderList::const_iterator it, itEnd = m_priv->appenderList.end(); AppenderPtr appender; for (it = m_priv->appenderList.begin(); it != itEnd; it++) { appender = *it; if (name == appender->getName()) { return appender; } } return 0; } bool AppenderAttachableImpl::isAttached(const AppenderPtr appender) const { if (appender == 0) { return false; } std::lock_guard lock( m_priv->m_mutex ); AppenderList::const_iterator it = std::find( m_priv->appenderList.begin(), m_priv->appenderList.end(), appender); return it != m_priv->appenderList.end(); } void AppenderAttachableImpl::removeAllAppenders() { std::lock_guard lock( m_priv->m_mutex ); AppenderList::iterator it, itEnd = m_priv->appenderList.end(); AppenderPtr a; for (it = m_priv->appenderList.begin(); it != itEnd; it++) { a = *it; a->close(); } m_priv->appenderList.clear(); } void AppenderAttachableImpl::removeAppender(const AppenderPtr appender) { if (appender == 0) { return; } std::lock_guard lock( m_priv->m_mutex ); AppenderList::iterator 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 (name.empty()) { return; } std::lock_guard lock( m_priv->m_mutex ); AppenderList::iterator it, itEnd = m_priv->appenderList.end(); AppenderPtr appender; for (it = m_priv->appenderList.begin(); it != itEnd; it++) { appender = *it; if (name == appender->getName()) { m_priv->appenderList.erase(it); return; } } } apache-log4cxx-1.1.0/src/main/cpp/defaultrepositoryselector.cpp000644 001750 001750 00000002601 14354342764 025515 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::spi; using namespace log4cxx::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.1.0/src/main/cpp/integerpatternconverter.cpp000644 001750 001750 00000003217 14354342764 025157 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(IntegerPatternConverter) IntegerPatternConverter::IntegerPatternConverter() : PatternConverter(LOG4CXX_STR("Integer"), LOG4CXX_STR("integer")) { } PatternConverterPtr IntegerPatternConverter::newInstance( const std::vector& /* options */) { static PatternConverterPtr instance = std::make_shared(); return instance; } void IntegerPatternConverter::format( const ObjectPtr& obj, LogString& toAppendTo, Pool& p) const { IntegerPtr i = log4cxx::cast(obj); if (i != NULL) { StringHelper::toString(i->intValue(), p, toAppendTo); } } apache-log4cxx-1.1.0/src/main/cpp/threadusernamepatternconverter.cpp000644 001750 001750 00000003261 14354342764 026530 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ThreadUsernamePatternConverter) ThreadUsernamePatternConverter::ThreadUsernamePatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Thread Name"), LOG4CXX_STR("Thread Name")) { } PatternConverterPtr ThreadUsernamePatternConverter::newInstance( const std::vector& /* options */) { static PatternConverterPtr def = std::make_shared(); return def; } void ThreadUsernamePatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(event->getThreadUserName()); } apache-log4cxx-1.1.0/src/main/cpp/reader.cpp000644 001750 001750 00000001731 14353331212 021416 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::helpers; IMPLEMENT_LOG4CXX_OBJECT(Reader) Reader::Reader() { } Reader::~Reader() { } apache-log4cxx-1.1.0/src/main/cpp/htmllayout.cpp000644 001750 001750 00000017530 14354342764 022401 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; struct HTMLLayout::HTMLLayoutPrivate { HTMLLayoutPrivate() : locationInfo(false), title(LOG4CXX_STR("Log4cxx Log Messages")), dateFormat() {} // Print no location info by default bool locationInfo; //= false LogString title; helpers::ISO8601DateFormat dateFormat; }; IMPLEMENT_LOG4CXX_OBJECT(HTMLLayout) HTMLLayout::HTMLLayout() : m_priv(std::make_unique()) { m_priv->dateFormat.setTimeZone(TimeZone::getGMT()); } 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)); } } void HTMLLayout::format(LogString& output, const spi::LoggingEventPtr& event, Pool& p) const { 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.1.0/src/main/cpp/propertysetter.cpp000644 001750 001750 00000005744 14353331212 023277 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::spi; using namespace log4cxx::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(); std::vector names = properties.propertyNames(); std::vector::iterator it; for (it = names.begin(); it != names.end(); it++) { LogString key = *it; // 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())) { LogLog::debug(LOG4CXX_STR("Setting option name=[") + option + LOG4CXX_STR("], value=[") + value + LOG4CXX_STR("]")); OptionHandlerPtr handler = log4cxx::cast(obj); handler->setOption(option, value); } } void PropertySetter::activate(Pool& p) { if (obj != 0 && obj->instanceof(OptionHandler::getStaticClass())) { OptionHandlerPtr handler = log4cxx::cast(obj); handler->activateOptions(p); } } apache-log4cxx-1.1.0/src/main/cpp/simpledateformat.cpp000644 001750 001750 00000041254 14354342764 023537 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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 { 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::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::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 ( PatternTokenList::iterator iter = m_priv->pattern.begin(); iter != m_priv->pattern.end(); iter++ ) { ( * iter )->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 ( PatternTokenList::iterator iter = m_priv->pattern.begin(); iter != m_priv->pattern.end(); iter++ ) { ( * iter )->setTimeZone( m_priv->timeZone ); } } SimpleDateFormat::~SimpleDateFormat() { for ( PatternTokenList::iterator iter = m_priv->pattern.begin(); iter != m_priv->pattern.end(); iter++ ) { delete * iter; } } 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.1.0/src/main/cpp/aprinitializer.cpp000644 001750 001750 00000010521 14424033655 023210 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::helpers; using namespace log4cxx; 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 { extern "C" void tlsDestruct(void* ptr) { delete ((ThreadSpecificData*) ptr); } // 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); apr_atomic_init(m_priv->p); m_priv->startTime = Date::currentTime(); #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_create(&m_priv->tlsKey, tlsDestruct, m_priv->p); assert(stat == APR_SUCCESS); assert(stat == APR_SUCCESS); #endif apr_status_t stat2 = apr_dbd_init(m_priv->p); assert(stat2 == APR_SUCCESS); } APRInitializer::~APRInitializer() { stopWatchDogs(); isDestructed = true; #if APR_HAS_THREADS std::unique_lock lock(m_priv->mutex); apr_threadkey_private_delete(m_priv->tlsKey); #endif } void APRInitializer::stopWatchDogs() { #if APR_HAS_THREADS std::unique_lock lock(m_priv->mutex); #endif while (!m_priv->watchdogs.empty()) { delete m_priv->watchdogs.back(); m_priv->watchdogs.pop_back(); } } void APRInitializer::unregisterAll() { getInstance().stopWatchDogs(); } APRInitializer& APRInitializer::getInstance() { static apr_environment env; static APRInitializer init; return init; } log4cxx_time_t APRInitializer::initialize() { 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()); #if APR_HAS_THREADS std::unique_lock lock(instance.m_priv->mutex); #endif instance.m_priv->watchdogs.push_back(watchdog); } void APRInitializer::unregisterCleanup(FileWatchdog* watchdog) { APRInitializer& instance(getInstance()); #if APR_HAS_THREADS std::unique_lock lock(instance.m_priv->mutex); #endif for (std::list::iterator iter = instance.m_priv->watchdogs.begin(); iter != instance.m_priv->watchdogs.end(); iter++) { if (*iter == watchdog) { instance.m_priv->watchdogs.erase(iter); return; } } } void APRInitializer::addObject(size_t key, const ObjectPtr& pObject) { #if APR_HAS_THREADS std::unique_lock lock(m_priv->mutex); #endif m_priv->objects[key] = pObject; } const ObjectPtr& APRInitializer::findOrAddObject(size_t key, std::function creator) { #if APR_HAS_THREADS std::unique_lock lock(m_priv->mutex); #endif 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.1.0/src/main/cpp/levelmatchfilter.cpp000644 001750 001750 00000005353 14354342764 023531 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::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::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.1.0/src/main/cpp/fixedwindowrollingpolicy.cpp000644 001750 001750 00000022150 14354342764 025327 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::helpers; using namespace log4cxx::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::pattern::PatternMap FixedWindowRollingPolicy::getFormatSpecifiers() const { PatternMap specs; RULES_PUT("i", IntegerPatternConverter); RULES_PUT("index", IntegerPatternConverter); return specs; } apache-log4cxx-1.1.0/src/main/cpp/propertiespatternconverter.cpp000644 001750 001750 00000006047 14354342764 025722 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::pattern; using namespace log4cxx::spi; using namespace log4cxx::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 PatternConverterPtr 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 /* '{' */); LoggingEvent::KeySet keySet(event->getMDCKeySet()); for (LoggingEvent::KeySet::const_iterator iter = keySet.begin(); iter != keySet.end(); iter++) { toAppendTo.append(1, (logchar) 0x7B /* '{' */); toAppendTo.append(*iter); toAppendTo.append(1, (logchar) 0x2C /* ',' */); event->getMDC(*iter, toAppendTo); toAppendTo.append(1, (logchar) 0x7D /* '}' */); } toAppendTo.append(1, (logchar) 0x7D /* '}' */); } else { event->getMDC(priv->option, toAppendTo); } } apache-log4cxx-1.1.0/src/main/cpp/charsetdecoder.cpp000644 001750 001750 00000030412 14354342764 023150 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(CharsetDecoder) namespace log4cxx { 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::unique_lock 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::unique_lock 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::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 buf[BUFSIZE]; mbstate_t mbstate; memset(&mbstate, 0, sizeof(mbstate)); while (in.remaining() > 0) { size_t requested = in.remaining(); if (requested > BUFSIZE - 1) { requested = BUFSIZE - 1; } memset(buf, 0, BUFSIZE * sizeof(wchar_t)); const char* src = in.current(); if (*src == 0) { out.append(1, (logchar) 0); in.position(in.position() + 1); } else { size_t converted = mbsrtowcs(buf, &src, requested, &mbstate); if (converted == (size_t) -1) { stat = APR_BADARG; in.position(src - in.data()); break; } else { stat = append(out, buf); in.position(in.position() + requested); } } } 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 an embedded CharsetDecoder consistent * with current locale settings. */ class LocaleCharsetDecoder : public CharsetDecoder { public: LocaleCharsetDecoder() : pool(), decoder(), encoding() { } virtual ~LocaleCharsetDecoder() { } virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { const char* p = in.current(); size_t i = in.position(); #if !LOG4CXX_CHARSET_EBCDIC for (; i < in.limit() && ((unsigned int) *p) < 0x80; i++, p++) { out.append(1, *p); } in.position(i); #endif if (i < in.limit()) { Pool subpool; const char* enc = apr_os_locale_encoding(subpool.getAPRPool()); { std::unique_lock lock(mutex); if (enc == 0) { if (decoder == 0) { encoding = "C"; decoder.reset( new USASCIICharsetDecoder() ); } } else if (encoding != enc) { encoding = enc; try { LogString e; Transcoder::decode(encoding, e); decoder = getDecoder(e); } catch (IllegalArgumentException&) { decoder.reset( new USASCIICharsetDecoder() ); } } } return decoder->decode(in, out); } return APR_SUCCESS; } private: Pool pool; std::mutex mutex; CharsetDecoderPtr decoder; std::string encoding; }; } // 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 CharsetDecoderPtr 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 == 0) { return CharsetDecoderPtr( createDefaultDecoder() ); } return decoder; } CharsetDecoderPtr CharsetDecoder::getUTF8Decoder() { static CharsetDecoderPtr 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 == 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"))) { 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"))) { 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"))) { return std::make_shared(); } #if APR_HAS_XLATE return std::make_shared(charset); #else throw IllegalArgumentException(charset); #endif } apache-log4cxx-1.1.0/src/main/cpp/relativetimedateformat.cpp000644 001750 001750 00000002563 14354342764 024740 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 log4cxx::helpers::RelativeTimeDateFormat::RelativeTimeDateFormat() : DateFormat(), startTime(log4cxx::spi::LoggingEvent::getStartTime()) { } void log4cxx::helpers::RelativeTimeDateFormat::format( LogString& s, log4cxx_time_t date, Pool& p) const { int64_t interval = (date - startTime) / APR_INT64_C(1000); StringHelper::toString(interval, p, s); } apache-log4cxx-1.1.0/src/main/cpp/logger.cpp000644 001750 001750 00000060315 14354342764 021455 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; struct Logger::LoggerPrivate { LoggerPrivate(Pool& p, const LogString& name1): name(name1), repositoryRaw(0), aai(p), additive(true) {} /** 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 log4cxx::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; }; IMPLEMENT_LOG4CXX_OBJECT(Logger) Logger::Logger(Pool& p, const LogString& name1) : m_priv(std::make_unique(p, name1)) , m_threshold(0) { } 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 ( std::vector::const_iterator it = appenders.cbegin(); it != appenders.cend(); it++ ) { m_priv->aai.addAppender( *it ); if (auto rep = getHierarchy()) { rep->fireAddAppenderEvent(this, it->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() { AppenderList appenders = getAllAppenders(); for (AppenderList::iterator it = appenders.begin(); it != appenders.end(); ++it) { (*it)->close(); } } void Logger::forcedLog(const LevelPtr& level1, const std::string& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; Pool p; LOG4CXX_DECODE_CHAR(msg, message); auto event = std::make_shared(m_priv->name, level1, msg, location); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::string& message) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; Pool p; LOG4CXX_DECODE_CHAR(msg, message); auto event = std::make_shared(m_priv->name, level1, msg, LocationInfo::getLocationUnavailable()); callAppenders(event, p); } void Logger::forcedLogLS(const LevelPtr& level1, const LogString& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; Pool p; auto event = std::make_shared(m_priv->name, level1, message, location); 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); } forcedLogLS(level1, 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() { m_priv->aai.removeAllAppenders(); } void Logger::removeAppender(const AppenderPtr appender) { m_priv->aai.removeAppender(appender); } void Logger::removeAppender(const LogString& name1) { m_priv->aai.removeAppender(name1); } 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) { 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::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg, location); } } void Logger::trace(const std::string& msg) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg); } } void Logger::debug(const std::string& msg, const log4cxx::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg, location); } } void Logger::debug(const std::string& msg) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg); } } void Logger::error(const std::string& msg, const log4cxx::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg, location); } } void Logger::error(const std::string& msg) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg); } } void Logger::fatal(const std::string& msg, const log4cxx::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg, location); } } void Logger::fatal(const std::string& msg) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg); } } void Logger::info(const std::string& msg, const log4cxx::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg, location); } } void Logger::info(const std::string& msg) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg); } } void Logger::log(const LevelPtr& level1, const std::string& message, const log4cxx::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::spi::LocationInfo& location) const { if (isEnabledFor(level1)) { forcedLogLS(level1, message, location); } } void Logger::warn(const std::string& msg, const log4cxx::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg, location); } } void Logger::warn(const std::string& msg) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg); } } LoggerPtr Logger::getLoggerLS(const LogString& name) { return LogManager::getLoggerLS(name); } #if LOG4CXX_WCHAR_T_API void Logger::forcedLog(const LevelPtr& level1, const std::wstring& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; Pool p; LOG4CXX_DECODE_WCHAR(msg, message); auto event = std::make_shared(m_priv->name, level1, msg, location); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::wstring& message) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; Pool p; LOG4CXX_DECODE_WCHAR(msg, message); auto event = std::make_shared(m_priv->name, level1, msg, LocationInfo::getLocationUnavailable()); callAppenders(event, p); } 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::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg, location); } } void Logger::trace(const std::wstring& msg) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg); } } void Logger::debug(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg, location); } } void Logger::debug(const std::wstring& msg) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg); } } void Logger::error(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg, location); } } void Logger::error(const std::wstring& msg) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg); } } void Logger::fatal(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg, location); } } void Logger::fatal(const std::wstring& msg) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg); } } void Logger::info(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg, location); } } void Logger::info(const std::wstring& msg) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg); } } void Logger::log(const LevelPtr& level1, const std::wstring& message, const log4cxx::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::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg, location); } } void Logger::warn(const std::wstring& msg) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg); } } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API void Logger::forcedLog(const LevelPtr& level1, const std::basic_string& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; Pool p; LOG4CXX_DECODE_UNICHAR(msg, message); auto event = std::make_shared(m_priv->name, level1, msg, location); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::basic_string& message) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; Pool p; LOG4CXX_DECODE_UNICHAR(msg, message); auto event = std::make_shared(m_priv->name, level1, msg, LocationInfo::getLocationUnavailable()); callAppenders(event, p); } #endif #if LOG4CXX_UNICHAR_API 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::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg, location); } } void Logger::trace(const std::basic_string& msg) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg); } } void Logger::debug(const std::basic_string& msg, const log4cxx::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg, location); } } void Logger::debug(const std::basic_string& msg) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg); } } void Logger::error(const std::basic_string& msg, const log4cxx::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg, location); } } void Logger::error(const std::basic_string& msg) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg); } } void Logger::fatal(const std::basic_string& msg, const log4cxx::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg, location); } } void Logger::fatal(const std::basic_string& msg) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg); } } void Logger::info(const std::basic_string& msg, const log4cxx::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg, location); } } void Logger::info(const std::basic_string& msg) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg); } } void Logger::log(const LevelPtr& level1, const std::basic_string& message, const log4cxx::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::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg, location); } } void Logger::warn(const std::basic_string& msg) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg); } } #endif #if LOG4CXX_CFSTRING_API void Logger::forcedLog(const LevelPtr& level1, const CFStringRef& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; Pool p; LOG4CXX_DECODE_CFSTRING(msg, message); auto event = std::make_shared(name, level1, msg, location); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const CFStringRef& message) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; Pool p; LOG4CXX_DECODE_CFSTRING(msg, message); auto event = std::make_shared(name, level1, msg, LocationInfo::getLocationUnavailable()); callAppenders(event, p); } void Logger::getName(CFStringRef& rv) const { rv = Transcoder::encode(name); } LoggerPtr Logger::getLogger(const CFStringRef& name) { return LogManager::getLogger(name); } void Logger::trace(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg, location); } } void Logger::trace(const CFStringRef& msg) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg); } } void Logger::debug(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg, location); } } void Logger::debug(const CFStringRef& msg) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg); } } void Logger::error(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg, location); } } void Logger::error(const CFStringRef& msg) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg); } } void Logger::fatal(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg, location); } } void Logger::fatal(const CFStringRef& msg) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg); } } void Logger::info(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg, location); } } void Logger::info(const CFStringRef& msg) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg); } } void Logger::log(const LevelPtr& level1, const CFStringRef& message, const log4cxx::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::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg, location); } } void Logger::warn(const CFStringRef& msg) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg); } } #endif apache-log4cxx-1.1.0/src/main/cpp/aprsocket.cpp000644 001750 001750 00000007404 14424032606 022156 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 { namespace helpers { struct APRSocket::APRSocketPriv : public Socket::SocketPrivate { APRSocketPriv() : 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()){ 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.1.0/src/main/cpp/transform.cpp000644 001750 001750 00000005330 14353331212 022166 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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 LogString CDATA_END(LOG4CXX_STR("]]>")); static const LogString CDATA_EMBEDED_END(LOG4CXX_STR("]]>]]> #include using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(InputStream) InputStream::InputStream() { } InputStream::~InputStream() { } apache-log4cxx-1.1.0/src/main/cpp/stringmatchfilter.cpp000644 001750 001750 00000005612 14354342764 023726 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::filter; using namespace log4cxx::spi; using namespace log4cxx::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::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.1.0/src/main/cpp/andfilter.cpp000644 001750 001750 00000004327 14354342764 022147 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; #define priv static_cast(m_priv.get()) struct AndFilter::AndFilterPrivate : public FilterPrivate { AndFilterPrivate() : FilterPrivate(), headFilter(), tailFilter(), acceptOnMatch(true) {} log4cxx::spi::FilterPtr headFilter; log4cxx::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.1.0/src/main/cpp/writer.cpp000644 001750 001750 00000002022 14354342764 021501 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::helpers; IMPLEMENT_LOG4CXX_OBJECT(Writer) Writer::Writer() { } Writer::~Writer() { } apache-log4cxx-1.1.0/src/main/cpp/class.cpp000644 001750 001750 00000012466 14354342764 021307 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; using namespace log4cxx::filter; using namespace log4cxx::xml; using namespace log4cxx::rolling; uint32_t libraryVersion(){ // This function defined in log4cxx.h return LOG4CXX_VERSION; } Class::Class() { } Class::~Class() { } LogString Class::toString() const { return getName(); } 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 ClassMap 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() { #if APR_HAS_THREADS AsyncAppender::registerClass(); #endif ConsoleAppender::registerClass(); FileAppender::registerClass(); log4cxx::db::ODBCAppender::registerClass(); #if (defined(WIN32) || defined(_WIN32)) #if !defined(_WIN32_WCE) log4cxx::nt::NTEventLogAppender::registerClass(); #endif log4cxx::nt::OutputDebugStringAppender::registerClass(); #endif SMTPAppender::registerClass(); HTMLLayout::registerClass(); PatternLayout::registerClass(); SimpleLayout::registerClass(); XMLLayout::registerClass(); LevelMatchFilter::registerClass(); LevelRangeFilter::registerClass(); StringMatchFilter::registerClass(); LocationInfoFilter::registerClass(); log4cxx::rolling::RollingFileAppender::registerClass(); log4cxx::rolling::SizeBasedTriggeringPolicy::registerClass(); log4cxx::rolling::TimeBasedRollingPolicy::registerClass(); log4cxx::rolling::ManualTriggeringPolicy::registerClass(); log4cxx::rolling::FixedWindowRollingPolicy::registerClass(); log4cxx::rolling::FilterBasedTriggeringPolicy::registerClass(); log4cxx::xml::DOMConfigurator::registerClass(); log4cxx::PropertyConfigurator::registerClass(); log4cxx::varia::FallbackErrorHandler::registerClass(); #if LOG4CXX_HAS_NETWORKING TelnetAppender::registerClass(); XMLSocketAppender::registerClass(); SyslogAppender::registerClass(); #endif } apache-log4cxx-1.1.0/src/main/cpp/transcoder.cpp000644 001750 001750 00000032333 14353331212 022322 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #if LOG4CXX_CFSTRING_API #include #endif using namespace log4cxx; using namespace log4cxx::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_CFSTRING_API 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) { const UniChar* chars = CFStringGetCharactersPtr(src); if (chars) { decode(chars, dst); } else { size_t length = CFStringGetLength(src); if (length > 0) { std::vector tmp(length); CFStringGetCharacters(src, CFRangeMake(0, length), &tmp[0]); #if LOG4CXX_LOGCHAR_IS_UNICHAR dst.append(&tmp[0], tmp.size()); #else decode(std::basic_string(&tmp[0], tmp.size()), dst); #endif } } } CFStringRef Transcoder::encode(const LogString& src) { LOG4CXX_ENCODE_UNICHAR(tmp, src); 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 (LogString::const_iterator iter = val.begin(); iter != val.end(); iter++) { if (*iter >= 0x20 && *iter < 0x7F) { out.append(1, asciiTable[*iter - 0x20]); } else { out.append(1, LOSSCHAR); } } return out; } apache-log4cxx-1.1.0/src/main/cpp/propertyresourcebundle.cpp000644 001750 001750 00000003331 14353331212 025000 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/loggerpatternconverter.cpp000644 001750 001750 00000003511 14354342764 024776 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::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 PatternConverterPtr 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.1.0/src/main/cpp/xmllayout.cpp000644 001750 001750 00000013131 14354342764 022226 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::spi; using namespace log4cxx::xml; struct XMLLayout::XMLLayoutPrivate { XMLLayoutPrivate() : locationInfo(false), properties(false) {} // Print no location info by default bool locationInfo; //= false bool properties; // = false }; IMPLEMENT_LOG4CXX_OBJECT(XMLLayout) XMLLayout::XMLLayout() : m_priv(std::make_unique()) { } 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)); } if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("PROPERTIES"), LOG4CXX_STR("properties"))) { setProperties(OptionConverter::toBoolean(value, false)); } } void XMLLayout::format(LogString& output, const spi::LoggingEventPtr& event, Pool& p) const { 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 (LoggingEvent::KeySet::const_iterator i = keySet.begin(); i != keySet.end(); i++) { LogString key(*i); LogString value; if (event->getMDC(key, value)) { output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); } } for (LoggingEvent::KeySet::const_iterator i2 = propertySet.begin(); i2 != propertySet.end(); i2++) { LogString key(*i2); 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.1.0/src/main/cpp/integer.cpp000644 001750 001750 00000002056 14353331212 021612 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(Integer) Integer::Integer() : val(0) { } Integer::Integer(int val1) : val(val1) { } Integer::~Integer() { } apache-log4cxx-1.1.0/src/main/cpp/timebasedrollingpolicy.cpp000644 001750 001750 00000035254 14354342764 024746 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::helpers; using namespace log4cxx::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::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::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::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::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) { snprintf(szUid, MAX_FILE_LEN, "%u", uid); } log4cxx::filesystem::path path(fileName); std::string newFilename = path.filename().string() + szUid + suffix; log4cxx::filesystem::path retval = path.parent_path() / newFilename; return retval.string(); } int TimeBasedRollingPolicy::createMMapFile(const std::string& fileName, log4cxx::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::helpers::Pool&) { return 0; } bool TimeBasedRollingPolicy::isMapFileEmpty(log4cxx::helpers::Pool&){ return true; } void TimeBasedRollingPolicy::initMMapFile(const LogString&, log4cxx::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::helpers::Pool&){ return ""; } #endif TimeBasedRollingPolicy::TimeBasedRollingPolicy() : m_priv(std::make_unique()) { } TimeBasedRollingPolicy::~TimeBasedRollingPolicy(){} void TimeBasedRollingPolicy::activateOptions(log4cxx::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::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::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.1.0/src/main/cpp/logmanager.cpp000644 001750 001750 00000012704 14354342764 022311 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::spi; using namespace log4cxx::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(); LoggerRepositoryPtr repPtr = getLoggerRepository(); getLoggerRepository()->shutdown(); } void LogManager::resetConfiguration() { getLoggerRepository()->resetConfiguration(); } apache-log4cxx-1.1.0/src/main/cpp/relativetimepatternconverter.cpp000644 001750 001750 00000003417 14354342764 026216 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(RelativeTimePatternConverter) RelativeTimePatternConverter::RelativeTimePatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Time"), LOG4CXX_STR("time")) { } PatternConverterPtr RelativeTimePatternConverter::newInstance( const std::vector& /* options */) { static PatternConverterPtr 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.1.0/src/main/cpp/sizebasedtriggeringpolicy.cpp000644 001750 001750 00000003565 14353331212 025436 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::rolling; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(SizeBasedTriggeringPolicy) SizeBasedTriggeringPolicy::SizeBasedTriggeringPolicy() : maxFileSize(10 * 1024 * 1024) { } bool SizeBasedTriggeringPolicy::isTriggeringEvent(Appender* /* appender */, const log4cxx::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.1.0/src/main/cpp/system.cpp000644 001750 001750 00000005134 14353331212 021501 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/properties.cpp000644 001750 001750 00000017627 14354342764 022402 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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()); PropertyMap::const_iterator it; for (it = properties->begin(); it != properties->end(); it++) { const LogString& key = it->first; names.push_back(key); } return names; } apache-log4cxx-1.1.0/src/main/cpp/namepatternconverter.cpp000644 001750 001750 00000004476 14354342764 024452 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::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.1.0/src/main/cpp/filelocationpatternconverter.cpp000644 001750 001750 00000003263 14354342764 026173 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::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 PatternConverterPtr 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.1.0/src/main/cpp/stringtokenizer.cpp000644 001750 001750 00000004166 14354342764 023441 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/formattinginfo.cpp000644 001750 001750 00000005520 14354342764 023221 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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 FormattingInfoPtr 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.1.0/src/main/cpp/rollingpolicy.cpp000644 001750 001750 00000001635 14353331212 023045 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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::rolling; IMPLEMENT_LOG4CXX_OBJECT(RollingPolicy) apache-log4cxx-1.1.0/src/main/cpp/mdc.cpp000644 001750 001750 00000012413 14353331212 020716 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/layout.cpp000644 001750 001750 00000002252 14353331212 021470 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(Layout) Layout::~Layout() {} LogString Layout::getContentType() const { return LOG4CXX_STR("text/plain"); } void Layout::appendHeader(LogString&, log4cxx::helpers::Pool&) {} void Layout::appendFooter(LogString&, log4cxx::helpers::Pool&) {} apache-log4cxx-1.1.0/src/main/cpp/classnamepatternconverter.cpp000644 001750 001750 00000003601 14354342764 025465 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::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 PatternConverterPtr 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.1.0/src/main/cpp/methodlocationpatternconverter.cpp000644 001750 001750 00000003276 14354342764 026540 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(MethodLocationPatternConverter) MethodLocationPatternConverter::MethodLocationPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Method"), LOG4CXX_STR("method")) { } PatternConverterPtr MethodLocationPatternConverter::newInstance( const std::vector& /* options */ ) { static PatternConverterPtr 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.1.0/src/main/cpp/configurator.cpp000644 001750 001750 00000002036 14353331212 022655 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(Configurator) Configurator::Configurator() { } apache-log4cxx-1.1.0/src/main/cpp/odbcappender.cpp000644 001750 001750 00000045434 14424433562 022624 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::db; using namespace log4cxx::spi; using namespace log4cxx::pattern; SQLException::SQLException(short fHandleType, void* hInput, const char* prolog, log4cxx::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::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()) { } 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::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::cast((pItem->second)(options)); _priv->parameterValue.push_back(paramData); } } #endif } void ODBCAppender::append(const spi::LoggingEventPtr& event, log4cxx::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::helpers::Pool& p) const { return LogString(); } void ODBCAppender::execute(const LogString& sql, log4cxx::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::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.1.0/src/main/cpp/bytebuffer.cpp000644 001750 001750 00000004606 14354342764 022334 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/fallbackerrorhandler.cpp000644 001750 001750 00000007616 14354342764 024352 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::spi; using namespace log4cxx::varia; IMPLEMENT_LOG4CXX_OBJECT(FallbackErrorHandler) struct FallbackErrorHandler::FallbackErrorHandlerPrivate { AppenderWeakPtr backup; AppenderWeakPtr primary; std::vector loggers; }; FallbackErrorHandler::FallbackErrorHandler() : m_priv(std::make_unique()) { } FallbackErrorHandler::~FallbackErrorHandler() {} void FallbackErrorHandler::setLogger(const LoggerPtr& logger) { 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 { 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) { 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); LogLog::debug(((LogString) LOG4CXX_STR("FB: Adding appender [")) + backupLocked->getName() + LOG4CXX_STR("] to logger ") + l->getName()); l->addAppender(backupLocked); } } void FallbackErrorHandler::setAppender(const AppenderPtr& primary1) { LogLog::debug(((LogString) LOG4CXX_STR("FB: Setting primary appender to [")) + primary1->getName() + LOG4CXX_STR("].")); m_priv->primary = primary1; } void FallbackErrorHandler::setBackupAppender(const AppenderPtr& backup1) { 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&) { } apache-log4cxx-1.1.0/src/main/cpp/rootlogger.cpp000644 001750 001750 00000002651 14354342764 022360 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::spi; using namespace log4cxx::helpers; RootLogger::RootLogger(Pool& pool, const LevelPtr level1) : Logger(pool, LOG4CXX_STR("root")) { setLevel(level1); } 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.1.0/src/main/cpp/writerappender.cpp000644 001750 001750 00000015706 14354342764 023235 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; using namespace log4cxx::spi; #define _priv static_cast(m_priv.get()) IMPLEMENT_LOG4CXX_OBJECT(WriterAppender) WriterAppender::WriterAppender() : AppenderSkeleton (std::make_unique()) { } WriterAppender::WriterAppender(const LayoutPtr& layout1, log4cxx::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 { static bool warnedClosed = false; static bool warnedNoWriter = false; if (_priv->closed) { if (!warnedClosed) { LogLog::warn(LOG4CXX_STR("Not allowed to write to a closed appender.")); warnedClosed = true; } return false; } if (_priv->writer == 0) { if (warnedNoWriter) { _priv->errorHandler->error( LogString(LOG4CXX_STR("No output stream or file set for the appender named [")) + _priv->name + LOG4CXX_STR("].")); warnedNoWriter = true; } return false; } if (_priv->layout == 0) { _priv->errorHandler->error( LogString(LOG4CXX_STR("No layout set for the appender named [")) + _priv->name + LOG4CXX_STR("].")); 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::unique_lock 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::helpers::WriterPtr WriterAppender::getWriter() const{ return _priv->writer; } apache-log4cxx-1.1.0/src/main/cpp/file.cpp000644 001750 001750 00000014636 14354342764 021122 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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 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.1.0/src/main/cpp/locationinfofilter.cpp000644 001750 001750 00000010152 14424032606 024047 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::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::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.1.0/src/main/cpp/simplelayout.cpp000644 001750 001750 00000002432 14353331212 022702 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(SimpleLayout) void SimpleLayout::format(LogString& output, const spi::LoggingEventPtr& event, log4cxx::helpers::Pool&) const { output.append(event->getLevel()->toString()); output.append(LOG4CXX_STR(" - ")); output.append(event->getRenderedMessage()); output.append(LOG4CXX_EOL); } apache-log4cxx-1.1.0/src/main/cpp/linelocationpatternconverter.cpp000644 001750 001750 00000003360 14354342764 026201 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(LineLocationPatternConverter) LineLocationPatternConverter::LineLocationPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Line"), LOG4CXX_STR("line")) { } PatternConverterPtr LineLocationPatternConverter::newInstance( const std::vector& /* options */) { static PatternConverterPtr 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.1.0/src/main/cpp/classregistration.cpp000644 001750 001750 00000002072 14353331212 023713 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; ClassRegistration::ClassRegistration(ClassAccessor accessor) { Class::registerClass((*accessor)()); } apache-log4cxx-1.1.0/src/main/cpp/inputstreamreader.cpp000644 001750 001750 00000005147 14354342764 023736 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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(stat); } if (buf.remaining() > 0) { memmove(buf.data(), buf.current(), buf.remaining()); buf.limit(buf.remaining()); } else { buf.clear(); } } return output; } apache-log4cxx-1.1.0/src/main/cpp/mdcpatternconverter.cpp000644 001750 001750 00000005074 14424033175 024257 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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 PatternConverterPtr 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.1.0/src/main/cpp/locale.cpp000644 001750 001750 00000003771 14354342764 021440 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/cpp/colorendpatternconverter.cpp000644 001750 001750 00000003401 14354342764 025322 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ColorEndPatternConverter) ColorEndPatternConverter::ColorEndPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Color End"), LOG4CXX_STR("colorEnd")) { } PatternConverterPtr ColorEndPatternConverter::newInstance( const std::vector& /* options */) { static PatternConverterPtr 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.1.0/src/main/cpp/domconfigurator.cpp000644 001750 001750 00000075767 14424033175 023410 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #define LOG4CXX 1 #include using namespace log4cxx; using namespace log4cxx::xml; using namespace log4cxx::helpers; using namespace log4cxx::spi; using namespace log4cxx::config; using namespace log4cxx::rolling; #define MAX_ATTRIBUTE_NAME_LEN 2000 struct DOMConfigurator::DOMConfiguratorPrivate { helpers::Properties props; spi::LoggerRepositoryPtr repository; spi::LoggerFactoryPtr loggerFactory; }; #if APR_HAS_THREADS namespace log4cxx { 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; #endif 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::helpers::Pool& p, log4cxx::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::helpers::Pool& p, log4cxx::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::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* appenderElement, apr_xml_doc* doc, AppenderMap& appenders) { LogString className(subst(getAttribute(utf8Decoder, appenderElement, CLASS_ATTR))); LogLog::debug(LOG4CXX_STR("Class name: [") + className + LOG4CXX_STR("]")); try { ObjectPtr instance = ObjectPtr(Loader::loadClass(className).newInstance()); AppenderPtr appender = log4cxx::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 (std::vector::iterator iter = filters.begin(); iter != filters.end(); iter++) { appender->addFilter(*iter); } } 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::cast(appender); if (rfa != NULL) { rfa->setRollingPolicy(rollPolicy); } } else if (tagName == TRIGGERING_POLICY_TAG) { ObjectPtr policy(parseTriggeringPolicy(p, utf8Decoder, currentElement)); RollingFileAppenderPtr rfa = log4cxx::cast(appender); TriggeringPolicyPtr policyPtr = log4cxx::cast(policy); if (rfa != NULL) { rfa->setTriggeringPolicy(policyPtr); } else { auto smtpa = log4cxx::cast(appender); if (smtpa != NULL) { auto evaluator = log4cxx::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::cast(appender); 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::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::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::cast(appender); if (appSkeleton != 0) { appSkeleton->setErrorHandler(eh); } } } /** Used internally to parse a filter element. */ void DOMConfigurator::parseFilters(Pool& p, log4cxx::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::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::helpers::Pool& p, log4cxx::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)); LogLog::debug(LOG4CXX_STR("Retreiving an instance of Logger.")); 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); 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::helpers::Pool& p, log4cxx::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.")); LogLog::debug(LOG4CXX_STR("No Logger Factory configured.")); } else { LogLog::debug(LOG4CXX_STR("Desired logger factory: [") + className + LOG4CXX_STR("]")); std::shared_ptr obj = OptionConverter::instantiateByClassName( className, LoggerFactory::getStaticClass(), 0); m_priv->loggerFactory = log4cxx::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::helpers::Pool& p, log4cxx::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::helpers::Pool& p, log4cxx::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 (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::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* layout_element) { LogString className(subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR))); LogLog::debug(LOG4CXX_STR("Parsing layout of class: \"") + className + LOG4CXX_STR("\"")); try { ObjectPtr instance = ObjectPtr(Loader::loadClass(className).newInstance()); LayoutPtr layout = log4cxx::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::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* layout_element) { LogString className = subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR)); 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::cast(instance); if (fbtp != NULL) { for (std::vector::iterator iter = filters.begin(); iter != filters.end(); iter++) { fbtp->addFilter(*iter); } } } } 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::helpers::Pool& p, log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* layout_element) { LogString className = subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR)); LogLog::debug(LOG4CXX_STR("Parsing rolling policy of class: \"") + className + LOG4CXX_STR("\"")); try { ObjectPtr instance = ObjectPtr(Loader::loadClass(className).newInstance()); RollingPolicyPtr layout = log4cxx::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::helpers::Pool& p, log4cxx::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))); 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 { 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; } } } LogLog::debug(loggerName + LOG4CXX_STR(" level set to ") + logger->getEffectiveLevel()->toString()); } void DOMConfigurator::setParameter(log4cxx::helpers::Pool& p, log4cxx::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, spi::LoggerRepositoryPtr repository1) { repository1->setConfigured(true); m_priv->repository = repository1; LogString msg(LOG4CXX_STR("DOMConfigurator configuring file ")); msg.append(filename.getPath()); msg.append(LOG4CXX_STR("...")); LogLog::debug(msg); m_priv->loggerFactory = std::make_shared(); 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; 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; } 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 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 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) { File file(filename); #if APR_HAS_THREADS 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; #else return DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); #endif } #if LOG4CXX_WCHAR_T_API spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const std::wstring& filename, long delay) { File file(filename); #if APR_HAS_THREADS 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; #else return DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); #endif } #endif #if LOG4CXX_UNICHAR_API spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const std::basic_string& filename, long delay) { File file(filename); #if APR_HAS_THREADS 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; #else return DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); #endif } #endif #if LOG4CXX_CFSTRING_API spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const CFStringRef& filename, long delay) { File file(filename); #if APR_HAS_THREADS 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; #else return DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); #endif } #endif void DOMConfigurator::parse( Pool& p, log4cxx::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 LogString NULL_STRING(LOG4CXX_STR("NULL")); 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) { LogLog::setInternalDebugging(OptionConverter::toBoolean(debugAttrib, true)); } else { LogLog::debug(LOG4CXX_STR("Ignoring internalDebug attribute.")); } LogString confDebug = subst(getAttribute(utf8Decoder, element, CONFIG_DEBUG_ATTR)); if (!confDebug.empty() && confDebug != NULL_STRING) { 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)); LogLog::debug(LOG4CXX_STR("Threshold =\"") + thresholdStr + LOG4CXX_STR("\".")); if (!thresholdStr.empty() && thresholdStr != NULL_STRING) { m_priv->repository->setThreshold(thresholdStr); } LogString threadSignalValue = subst(getAttribute(utf8Decoder, element, THREAD_CONFIG_ATTR)); if ( !threadSignalValue.empty() && threadSignalValue != NULL_STRING ) { 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::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.1.0/src/main/cpp/basicconfigurator.cpp000644 001750 001750 00000003237 14354342764 023702 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; void BasicConfigurator::configure(const LayoutPtr& layoutArg) { LogManager::getLoggerRepository()->setConfigured(true); auto layout = layoutArg; if (!layout) { static const LogString 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.1.0/src/main/cpp/shortfilelocationpatternconverter.cpp000644 001750 001750 00000003413 14354342764 027250 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::pattern; using namespace log4cxx::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 PatternConverterPtr instance(new ShortFileLocationPatternConverter()); return instance; } void ShortFileLocationPatternConverter::format( const LoggingEventPtr &event, LogString &toAppendTo, Pool & /* p */ ) const { append(toAppendTo, event->getLocationInformation().getShortFileName()); } apache-log4cxx-1.1.0/src/main/cpp/date.cpp000644 001750 001750 00000003515 14354342764 021112 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::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.1.0/src/main/resources/000755 001750 001750 00000000000 14424433605 020706 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/main/resources/MSG00001.bin000644 001750 001750 00000000244 14353331212 022377 0ustar00robertrobert000000 000000 Trace Debug Info Warn Error Fatal %1 apache-log4cxx-1.1.0/src/main/resources/log4cxx.rc000644 001750 001750 00000007761 14353331212 022627 0ustar00robertrobert000000 000000 // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT 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.1.0/src/main/resources/CMakeLists.txt000644 001750 001750 00000001557 14353331212 023446 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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(WIN32) target_sources(log4cxx PRIVATE ../resources/log4cxx.rc ) endif() apache-log4cxx-1.1.0/src/main/resources/EventLogCategories.mc000644 001750 001750 00000002032 14353331212 024745 0ustar00robertrobert000000 000000 ; ; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, ; software distributed under the License is distributed on an ; "AS IS" BASIS, WITHOUT 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.1.0/src/CMakeLists.txt000644 001750 001750 00000003415 14424032606 020507 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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) add_subdirectory(examples/cpp) endif() add_subdirectory(site) apache-log4cxx-1.1.0/src/examples/000755 001750 001750 00000000000 14424433605 017566 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/examples/cpp/000755 001750 001750 00000000000 14424433605 020350 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/examples/cpp/auto-configured.xml000644 001750 001750 00000001010 14354342764 024164 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/examples/cpp/stream.cpp000644 001750 001750 00000003637 14353331212 022350 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.1.0/src/examples/cpp/auto-configured.cpp000644 001750 001750 00000002123 14354342764 024154 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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" extern auto rootLogger = com::foo::getLogger(); static 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.1.0/src/examples/cpp/com/000755 001750 001750 00000000000 14424433605 021126 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/examples/cpp/com/foo/000755 001750 001750 00000000000 14424433605 021711 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/examples/cpp/com/foo/config3.cpp000644 001750 001750 00000012213 14354342764 023753 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #ifdef WIN32 #include #elif __APPLE__ #include #else #include /* getpid */ #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); #else std::ostringstream exeLink; exeLink << "/proc/" << getpid() << "/exe"; bufCount = readlink(exeLink.str().c_str(), buf, bufSize); if (0 < bufCount) buf[bufCount] = 0; #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 defined(_DEBUG) LogString msg1 = LOG4CXX_STR("Alternate prefix ["); helpers::Transcoder::decode(altPrefix, msg1); msg1 += LOG4CXX_STR("]"); helpers::LogLog::debug(msg1); #endif // Add a local directory relative name result.push_back(programFileName.substr(slashIndex + 1)); #if defined(_DEBUG) LogString msg2(LOG4CXX_STR("Alternate configuration file name [")); helpers::Transcoder::decode(result.back(), msg2); msg2 += LOG4CXX_STR("]"); helpers::LogLog::debug(msg2); #endif // 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 defined(_DEBUG) LogString msg3(LOG4CXX_STR("Alternate configuration file name [")); helpers::Transcoder::decode(result.back(), msg3); msg3 += LOG4CXX_STR("]"); helpers::LogLog::debug(msg3); #endif } } else if (!programFileName.empty()) { auto dotIndex = result.back().rfind('.'); if (std::string::npos != dotIndex) { programFileName.erase(dotIndex); result.push_back(programFileName); #if defined(_DEBUG) LogString msg(LOG4CXX_STR("Alternate configuration file name [")); helpers::Transcoder::decode(result.back(), msg); msg += LOG4CXX_STR("]"); helpers::LogLog::debug(msg); #endif } } 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? break; } } } // namespace namespace com { namespace foo { // Retrieve the \c name logger pointer. // Configure Log4cxx on the first call. auto getLogger(const std::string& name) -> LoggerPtr { static struct log4cxx_initializer { log4cxx_initializer() { SelectConfigurationFile(); } ~log4cxx_initializer() { log4cxx::LogManager::shutdown(); } } initialiser; return name.empty() ? log4cxx::LogManager::getRootLogger() : log4cxx::LogManager::getLogger(name); } } } // namespace com::foo apache-log4cxx-1.1.0/src/examples/cpp/com/foo/config1.cpp000644 001750 001750 00000001105 14354342764 023747 0ustar00robertrobert000000 000000 #include "com/foo/config.h" #include #include namespace com { namespace foo { auto getLogger(const std::string& name) -> LoggerPtr { static struct log4cxx_initializer { log4cxx_initializer() { // Set up a simple configuration that logs on the console. log4cxx::BasicConfigurator::configure(); } ~log4cxx_initializer() { log4cxx::LogManager::shutdown(); } } initAndShutdown; return name.empty() ? log4cxx::LogManager::getRootLogger() : log4cxx::LogManager::getLogger(name); } } } // namespace com::foo apache-log4cxx-1.1.0/src/examples/cpp/com/foo/config.h000644 001750 001750 00000000653 14354342764 023342 0ustar00robertrobert000000 000000 #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.1.0/src/examples/cpp/com/foo/bar.h000644 001750 001750 00000000356 14354342764 022641 0ustar00robertrobert000000 000000 #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.1.0/src/examples/cpp/com/foo/bar.cpp000644 001750 001750 00000000251 14354342764 023166 0ustar00robertrobert000000 000000 #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.1.0/src/examples/cpp/com/foo/config2.cpp000644 001750 001750 00000001037 14354342764 023754 0ustar00robertrobert000000 000000 #include "com/foo/config.h" #include #include namespace com { namespace foo { auto getLogger(const std::string& name) -> LoggerPtr { static struct log4cxx_initializer { log4cxx_initializer() { log4cxx::PropertyConfigurator::configure("MyApp.properties"); } ~log4cxx_initializer() { log4cxx::LogManager::shutdown(); } } initAndShutdown; return name.empty() ? log4cxx::LogManager::getRootLogger() : log4cxx::LogManager::getLogger(name); } } } // namespace com::foo apache-log4cxx-1.1.0/src/examples/cpp/custom-appender.xml000644 001750 001750 00000001344 14353331212 024172 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/examples/cpp/CMakeLists.txt000644 001750 001750 00000006032 14354342764 023120 0ustar00robertrobert000000 000000 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 trivial custom-appender MyApp1 MyApp2) 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) add_executable(${exampleName} ${exampleName}.cpp) if(${exampleName} STREQUAL MyApp2) target_sources(${exampleName} PRIVATE com/foo/config2.cpp com/foo/bar.cpp) endif() if(${exampleName} STREQUAL auto-configured) target_sources(${exampleName} PRIVATE com/foo/config3.cpp ) endif() target_compile_definitions(${exampleName} PRIVATE ${EXAMPLE_COMPILE_DEFINITIONS} ${LOG4CXX_COMPILE_DEFINITIONS} ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS} ) target_include_directories(${exampleName} PRIVATE ${CMAKE_CURRENT_LIST_DIR} $) target_link_libraries(${exampleName} PRIVATE log4cxx ${APR_UTIL_LIBRARIES} ${EXPAT_LIBRARIES} ${APR_LIBRARIES} ${APR_SYSTEM_LIBS}) if( WIN32 ) set_target_properties(${exampleName} PROPERTIES VS_DEBUGGER_ENVIRONMENT "PATH=${ESCAPED_PATH}" VS_DEBUGGER_WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} ) endif() endforeach() configure_file( custom-appender.xml ${CMAKE_CURRENT_BINARY_DIR}/custom-appender.xml COPYONLY ) # 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}" ) endif() endif(${fmt_FOUND}) apache-log4cxx-1.1.0/src/examples/cpp/MyApp.properties000644 001750 001750 00000001236 14354342764 023525 0ustar00robertrobert000000 000000 # 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.1.0/src/examples/cpp/MyApp2.cpp000644 001750 001750 00000000570 14354342764 022175 0ustar00robertrobert000000 000000 #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.1.0/src/examples/cpp/sample_table.sql000644 001750 001750 00000000244 14421030455 023512 0ustar00robertrobert000000 000000 CREATE TABLE logs (thread VARCHAR(200), log VARCHAR(200), time VARCHAR(200), level VARCHAR(10), file VARCHAR(200), line VARCHAR(10), message VARCHAR(1000) ); apache-log4cxx-1.1.0/src/examples/cpp/trivial.cpp000644 001750 001750 00000003336 14353331212 022523 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; 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_DEBUG(rootLogger, "debug message"); LOG4CXX_INFO(rootLogger, "info message"); LOG4CXX_WARN(rootLogger, "warn message"); LOG4CXX_ERROR(rootLogger, "error message"); LOG4CXX_FATAL(rootLogger, "fatal message"); NDC::pop(); } catch(std::exception&) { result = EXIT_FAILURE; } return result; } apache-log4cxx-1.1.0/src/examples/cpp/console.cpp000644 001750 001750 00000007715 14353331212 022520 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 #ifndef WIN32 #include #endif using namespace log4cxx; using namespace log4cxx::helpers; /** * Configures console appender. * @param err if true, use stderr, otherwise stdout. */ static void configure(bool err) { log4cxx::ConsoleAppenderPtr appender(new log4cxx::ConsoleAppender()); if (err) { appender->setTarget(LOG4CXX_STR("System.err")); } log4cxx::LayoutPtr layout(new log4cxx::SimpleLayout()); appender->setLayout(layout); log4cxx::helpers::Pool pool; appender->activateOptions(pool); log4cxx::Logger::getRootLogger()->addAppender(appender); LogManager::getLoggerRepository()->setConfigured(true); } /** * 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.1.0/src/examples/cpp/custom-appender.cpp000644 001750 001750 00000004511 14354342764 024172 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 namespace log4cxx { 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 false; } 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 { 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 ){ log4cxx::xml::DOMConfigurator::configure( "custom-appender.xml" ); log4cxx::LoggerPtr rootLogger = log4cxx::Logger::getRootLogger(); log4cxx::LoggerPtr nullLogger = log4cxx::Logger::getLogger( "NullLogger" ); LOG4CXX_INFO( rootLogger, "This is some root message" ); LOG4CXX_INFO( nullLogger, "This message will be discarded" ); } apache-log4cxx-1.1.0/src/examples/cpp/format-string.cpp000644 001750 001750 00000004127 14353331212 023644 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; using namespace log4cxx::helpers; struct MyStruct { int x; }; std::ostream& operator<<( std::ostream& stream, const MyStruct& mystruct ){ stream << "[MyStruct x:" << mystruct.x << "]"; return stream; } #if FMT_VERSION >= (9 * 10000) template <> struct fmt::formatter : ostream_formatter {}; #endif int main() { setlocale(LC_ALL, ""); BasicConfigurator::configure(); LoggerPtr rootLogger = Logger::getRootLogger(); LOG4CXX_INFO_FMT( rootLogger, "This is a {} mesage", "test" ); LOG4CXX_INFO_FMT( rootLogger, fmt::fg(fmt::color::red), "Messages can be colored" ); LOG4CXX_INFO_FMT( rootLogger, "We can also align text to the {:<10} or {:>10}", "left", "right" ); MyStruct mine; 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.1.0/src/examples/cpp/MyApp1.cpp000644 001750 001750 00000001472 14354342764 022176 0ustar00robertrobert000000 000000 #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.1.0/src/examples/cpp/delayedloop.cpp000644 001750 001750 00000006603 14353331212 023352 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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") { #if APR_HAS_THREADS xml::DOMConfigurator::configureAndWatch(configFile, 3000); #else xml::DOMConfigurator::configure(configFile); #endif } else { #if APR_HAS_THREADS PropertyConfigurator::configureAndWatch(configFile, 3000); #else PropertyConfigurator::configure(configFile); #endif } } 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.1.0/src/site/000755 001750 001750 00000000000 14424433605 016714 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/site/markdown/000755 001750 001750 00000000000 14424433605 020536 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/site/markdown/library-design.md000644 001750 001750 00000006552 14354342764 024012 0ustar00robertrobert000000 000000 # Library 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.1.0/src/site/markdown/performance.md000644 001750 001750 00000006030 14353331212 023350 0ustar00robertrobert000000 000000 Log4cxx Performance {#performance} === [TOC] # Log4cxx 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 handle 2,000,000 log messages/second, when the log statement is disabled(not logged), this can go to over 20,000,000 messages/second, thus not unduly slowing down an application when logging is disabled. For the best performance, the `LOG4CXX_[level]_FMT` series of macros should be utilized, as they use the [{fmt}](https://fmt.dev/latest/index.html) library(note that you must include the headers from {fmt} manually). Using {fmt} over `operator<<` for log messages is both cleaner from a code standpoint, and is also significantly faster(approximately 2x as fast). 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. ``` for( int x = 0; x < howmany; x++ ){ LOG4CXX_INFO( logger, "Hello logger: msg number " << x); } ``` ``` 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 the [{google benchmark}](https://github.com/google/benchmark) library and may be built by specifying `BUILD_BENCHMARK_CHECKS` with CMake when building Log4cxx.apache-log4cxx-1.1.0/src/site/markdown/multiprocess.md000644 001750 001750 00000003007 14354342764 023620 0ustar00robertrobert000000 000000 Multiprocess Logging {#multiprocess-logging} === # Logging With Multiple Processes 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 supplies a `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.1.0/src/site/markdown/3-development.md000644 001750 001750 00000002141 14354342764 023547 0ustar00robertrobert000000 000000 Development {#development-overview} === See the following pages for development information: * @subpage source-repository * @subpage dependencies * @subpage building * @subpage build-cmake * @subpage build-vcpkg * @subpage library-design apache-log4cxx-1.1.0/src/site/markdown/download.md.in000644 001750 001750 00000010151 14353331212 023262 0ustar00robertrobert000000 000000 Download {#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) | [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz] | [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz.sha512] | [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz.asc] | | Apache Log4cxx ${LOG4CXX_RELEASE_VERSION} (zip) | [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip] | [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip.sha512] | [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.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](https://www.apache.org/dist/logging/KEYS) as well as the asc signature file for the relevant distribution. Make sure you get these files from the [main distribution directory](https://www.apache.org/dist/logging/), rather than from a mirror. Then verify the signatures using: ~~~ % gpg --import KEYS % gpg --verify apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz.asc apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz ~~~ * apache-log4cxx-${LOG4CXX_RELEASE_VERSION} is signed by ${releaseManager} (${releaseKey}) 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 All previous releases of Apache Log4cxx can be found in the [archive repository](https://archive.apache.org/dist/logging/log4cxx). [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz]:https://www.apache.org/dyn/closer.cgi/logging/log4cxx/${LOG4CXX_RELEASE_VERSION}/apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz.sha512]:https://www.apache.org/dist/logging/log4cxx/${LOG4CXX_RELEASE_VERSION}/apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz.sha512 [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz.asc]:https://www.apache.org/dist/logging/log4cxx/${LOG4CXX_RELEASE_VERSION}/apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.tar.gz.asc [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip]:https://www.apache.org/dyn/closer.cgi/logging/log4cxx/${LOG4CXX_RELEASE_VERSION}/apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip.sha512]:https://www.apache.org/dist/logging/log4cxx/${LOG4CXX_RELEASE_VERSION}/apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip.sha512 [apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip.asc]:https://www.apache.org/dist/logging/log4cxx/${LOG4CXX_RELEASE_VERSION}/apache-log4cxx-${LOG4CXX_RELEASE_VERSION}.zip.asc apache-log4cxx-1.1.0/src/site/markdown/change-report-gh.md000644 001750 001750 00000316473 14424041063 024221 0ustar00robertrobert000000 000000 Changelog {#changelog} === # Release History | Version | Date | Description | | -------------------------------------------------------------------------------------- | ---------- | -------------------- | | [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.1.0 - 2023-05-01 {#rel_1_1_0} This is a general maintenance release. The following bugs/issues have been fixed: * 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 --- - \[[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 ----------- - \[[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 ----------- - \[[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 --- - \[[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 ----------- - \[[LOGCXX-529](https://issues.apache.org/jira/browse/LOGCXX-529)\] - Support color and highlight conversion patterns Improvement ----------- - \[[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 ---- - \[[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 --- - \[[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 --- - \[[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 ----------- - \[[LOGCXX-515](https://issues.apache.org/jira/browse/LOGCXX-515)\] - Add macros to utilize libfmt formatting for messages Improvement ----------- - \[[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.1.0/src/site/markdown/extending.md000644 001750 001750 00000010760 14353331212 023041 0ustar00robertrobert000000 000000 Extending 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 in the src/examples/cpp directory. 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} namespace log4cxx { class NullWriterAppender : public log4cxx::AppenderSkeleton { }; } ~~~ Next, we need to add in a few macros in order to properly register our new appender with Log4cxx: ~~~{.cpp} namespace log4cxx { 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() }; IMPLEMENT_LOG4CXX_OBJECT(NullWriterAppender) } ~~~ These macros tell Log4cxx what the name of our class is, as well as giving Log4cxx a way of instansiating our class. Without these macros, the custom class will not work. 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(){} virtual void close(){} virtual bool requiresLayout() const { return false; } virtual void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p){ // This gets called whenever there is a valid event for our appender. } virtual void activateOptions(log4cxx::helpers::Pool& /* pool */) { // Given all of our options, do something useful(e.g. open a file) } virtual void setOption(const LogString& option, const LogString& value){ 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) apache-log4cxx-1.1.0/src/site/markdown/configuration-samples.md000644 001750 001750 00000021475 14354342764 025411 0ustar00robertrobert000000 000000 Configuration Samples {#configuration-samples} === The following snippets show various ways of configuring Log4cxx. [TOC] # Patterns {#patterns} The basic way of outputing messages is by using a [PatternLayout](@ref log4cxx.PatternLayout), and then sending the messages to stderr/stdout/file. 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). # 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. In this case, the file will be in our working directory. The pattern has also been updated to match with pattern example 1 ~~~{.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. ~~~{.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. apache-log4cxx-1.1.0/src/site/markdown/community/000755 001750 001750 00000000000 14424433605 022562 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/site/markdown/community/issue-tracking.md000644 001750 001750 00000005122 14354342764 026043 0ustar00robertrobert000000 000000 Issue Tracking {#issue-tracking} === # Overview This project uses [JIRA](https://www.atlassian.com/software/jira), a J2EE-based issue tracking and project management application. Issues may also be filed through GitHub. # Issue Tracking *Bugs* and *feature requests* should be submitted to the following issue tracking system for this project. https://issues.apache.org/jira/browse/LOGCXX If you do not have a JIRA account, you may email private@logging.apache.org due to the Apache Software Foundation restricting signups([more information](https://infra.apache.org/jira-guidelines.html#who)). Issues may also be filed via the github mirror: https://github.com/apache/logging-log4cxx/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 don't work for you and you need some help, please subscribe to the [users mailing list] and describe the issue you have, the more detailed the better. The mailing list is a far better place to discuss things than JIRA, besides that there are more users than developers of the project and issues created in JIRA are only forwarded to the latter. There's always the chance to create an issue in JIRA later, hopefully with a specific explanation of the problem and even a solution already. As a rule of thumb, if you already digged through the code and found a problem in it or its build tools, feel free to directly create a bug in [JIRA](https://issues.apache.org/jira/browse/LOGCXX). But if things really only don't work and you don't have any clue why, please use the [users mailing list] instead. Thanks! [users mailing list]:@ref mailing-lists apache-log4cxx-1.1.0/src/site/markdown/community/mailing-lists.md000644 001750 001750 00000013441 14354342764 025672 0ustar00robertrobert000000 000000 Mailing Lists {#mailing-lists} === These are the mailing lists that have been established for this project. For each list, there is a subscribe, unsubscribe, and an archive link. | | | | | | | | -------------------------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- | | Name | Subscribe | Unsubscribe | Post | Archive | Other Archives | | Log4cxx usage | [Subscribe](mailto:log4cxx-user-subscribe@logging.apache.org) | [Unsubscribe](mailto:log4cxx-user-unsubscribe@logging.apache.org) | [Post](mailto:log4cxx-user@logging.apache.org) | [mail-archives.apache.org](http://mail-archives.apache.org/mod_mbox/logging-log4cxx-user/) | [markmail.org](http://markmail.org/search/list:org.apache.logging.log4cxx-user) | | \- | \- | \- | \- | \- | [marc.info](http://marc.info/?l=log4cxx-user) | | \- | \- | \- | \- | \- | [dir.gmane.org](http://dir.gmane.org/gmane.comp.apache.logging.log4cxx.user) | | Log4cxx development | [Subscribe](mailto:dev-subscribe@logging.apache.org) | [Unsubscribe](mailto:dev-unsubscribe@logging.apache.org) | [Post](mailto:dev@logging.apache.org) | [mail-archives.apache.org](http://mail-archives.apache.org/mod_mbox/logging-dev/) | [markmail.org](http://markmail.org/search/list:org.apache.logging.dev) | | \- | \- | \- | \- | \- | [marc.info](http://marc.info/?l=dev) | | \- | \- | \- | \- | \- | [dir.gmane.org](http://dir.gmane.org/gmane.comp.apache.logging.devel) | | Old Log4cxx development (NOT USED ANYMORE\!) | [Subscribe](mailto:log4cxx-dev-subscribe@logging.apache.org) | [Unsubscribe](mailto:log4cxx-dev-unsubscribe@logging.apache.org) | [Post](mailto:log4cxx-dev@logging.apache.org) | [mail-archives.apache.org](http://mail-archives.apache.org/mod_mbox/logging-log4cxx-dev/) | [markmail.org](http://markmail.org/search/list:org.apache.logging.log4cxx-dev) | | \- | \- | \- | \- | \- | [marc.info](http://marc.info/?l=log4cxx-dev) | | \- | \- | \- | \- | \- | [dir.gmane.org](http://dir.gmane.org/gmane.comp.apache.logging.log4cxx.devel) | apache-log4cxx-1.1.0/src/site/markdown/license.md000644 001750 001750 00000030221 14353331212 022470 0ustar00robertrobert000000 000000 License {#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.1.0/src/site/markdown/2-get.md000644 001750 001750 00000001675 14353331212 021777 0ustar00robertrobert000000 000000 Get {#get} === * @subpage download * @subpage changelog * @subpage license apache-log4cxx-1.1.0/src/site/markdown/environment-variables.md000644 001750 001750 00000003630 14354342764 025403 0ustar00robertrobert000000 000000 Environment Variables {#environment-variables} === # Environment Variables Used by Log4cxx 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.1.0/src/site/markdown/usage.md000644 001750 001750 00000104354 14354342764 022202 0ustar00robertrobert000000 000000 Loggers, Appenders and Layouts {#usage} === [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. # 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 assumes that the logging space, that is, the space of all possible logging statements, is categorized according to some developer-chosen criteria. Loggers are named entities. Logger names are case-sensitive and they follow the hierarchical naming rule: ## Hierarchy {#hierarchy} 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. The root logger resides at the top of the logger hierarchy. It is exceptional in two ways: 1. it always exists, 2. it cannot be retrieved by name. Invoking the class static log4cxx::Logger::getRootLogger method retrieves it. All other loggers are instantiated and retrieved with the class static log4cxx::Logger::getLogger method. This method takes the name of the desired logger as a parameter. Some of the basic methods in the Logger class 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 // or most right-hand side expressions of an // std::basic_string::operator<<. // #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) ... ~~~ ## Levels {#levels} Loggers *may* be assigned levels. The pre-defined levels: TRACE, DEBUG, INFO, WARN, ERROR and FATAL are defined in the log4cxx::Level class which provides accessor functions. If a given logger is not assigned a level, then it inherits one from its closest ancestor with an assigned level. More formally: ### Level Inheritance {#level-inheritance} The *inherited level* for a given logger *C*, is equal to the first non-null level in the logger hierarchy, starting at *C* 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 inherited levels according to the above rule. | Logger name | Assigned level | Inherited level | | ----------- | -------------- | --------------- | | root | Proot | Proot | | X | none | Proot | | X.Y | none | Proot | | X.Y.Z | none | Proot | Example 1 In example 1 above, only the root logger is assigned a level. This level value, *Proot*, is inherited by the other loggers *X*, *X.Y* and *X.Y.Z*. | Logger name | Assigned level | Inherited level | | ----------- | -------------- | --------------- | | root | Proot | Proot | | X | Px | Px | | X.Y | Pxy | Pxy | | X.Y.Z | Pxyz | Pxyz | Example 2 In example 2, all loggers have an assigned level value. There is no need for level inheritence. | Logger name | Assigned level | Inherited level | | ----------- | -------------- | --------------- | | root | Proot | Proot | | X | Px | Px | | X.Y | none | Px | | X.Y.Z | Pxyz | Pxyz | Example 3 In example 3, the loggers *root*, *X* and *X.Y.Z* are assigned the levels *Proot*, *Px* and *Pxyz* respectively. The logger *X.Y* inherits its level value from its parent *X*. | Logger name | Assigned level | Inherited level | | ----------- | -------------- | --------------- | | root | Proot | Proot | | X | Px | Px | | X.Y | none | Px | | X.Y.Z | none | Px | Example 4 In example 4, the loggers *root* and *X* and are assigned the levels *Proot* and *Px* respectively. The loggers *X.Y* and *X.Y.Z* inherits their level value from their nearest parent *X* having an assigned level. ## 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."); ~~~ 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. ## 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"); ~~~ 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. Configuration of the Log4cxx environment is typically done at application initialization. The preferred way is by reading a configuration file. This approach will be discussed shortly. 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. # 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 socket server](@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. 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 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 Programs {#coding} 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 *com/foo/config.h* defines the com::foo::getLogger() function and a *LoggerPtr* type for convenience. \include com/foo/config.h The file *com/foo/config.cpp* which 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. \include com/foo/config1.cpp 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. # Default Initialization {#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. # Nested Diagnostic Contexts {#nested-diagnostic-contexts} Most real-world systems have to deal with multiple clients simultaneously. In a typical multithreaded implementation of such a system, different threads will handle different clients. Logging is especially well suited to trace and debug complex distributed applications. A common approach to differentiate the logging output of one client from another is to instantiate a new separate logger for each client. This promotes the proliferation of loggers and increases the management overhead of logging. A lighter technique is to uniquely stamp each log request initiated from the same client interaction. Neil Harrison described this method in the book "Patterns for Logging Diagnostic Messages," in *Pattern Languages of Program Design 3*, edited by R. Martin, D. Riehle, and F. Buschmann (Addison-Wesley, 1997). To uniquely stamp each request, the user pushes contextual information into the NDC, the abbreviation of *Nested Diagnostic Context*. The NDC class is shown below. ~~~{.cpp} namespace log4cxx { class NDC { public: // pushes the value on construction and pops on destruction. NDC(const std::string& value); NDC(const std::wstring& value); // Remove the top of the context from the NDC. static LogString pop(); // Add diagnostic context for the current thread. static void push(const std::string& message); static void push(const std::wstring& message); } } ~~~ The NDC is managed per thread as a *stack* of contextual information. Note that all methods of the *log4cxx::NDC* class are static. Assuming that NDC printing is turned on, every time a log request is made, the appropriate Log4cxx component will include the *entire* NDC stack for the current thread in the log output. This is done without the intervention of the user, who is responsible only for placing the correct information in the NDC by using the *push* and *pop* methods 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. # 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] ~~~ # Logging with {fmt} {#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, one popular library(that has been standardized as part of C++20) is [{fmt}](https://fmt.dev/latest/index.html). Supporting positional arguments and printf-like formatting, it makes for much clearer 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 ); ~~~ 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. 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. # Internal 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. # 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 statements {#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`). 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. # Conclusions {#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. \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. \example com/foo/config3.cpp This file is an example of how to use the current module name to select the Log4cxx configuration file. \example format-string.cpp This example shows logging using the [{fmt}](https://fmt.dev/latest/index.html) library. apache-log4cxx-1.1.0/src/site/markdown/index.md000644 001750 001750 00000006157 14424032606 022174 0ustar00robertrobert000000 000000 # Short introduction to Apache Log4cxx 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. Informational, warning and error log messages should be saved in persistent medium available for study at a later time. 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. More information on how to use Log4cxx can be found on the [usage] page. For a more general overview of what logging is, the logging services committee has 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/ [usage]:usage.html [Open Source Initiative]:https://opensource.org/ [Performance]:performance.html [logging overview]:https://logging.apache.org/what-is-logging.html apache-log4cxx-1.1.0/src/site/markdown/filters/000755 001750 001750 00000000000 14424433605 022206 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/site/markdown/filters/LocationInfoFilter.md000644 001750 001750 00000007136 14354342764 026300 0ustar00robertrobert000000 000000 LocationInfoFilter {#location-info-filter} === The 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. apache-log4cxx-1.1.0/src/site/markdown/filters/filters.md000644 001750 001750 00000005644 14354342764 024220 0ustar00robertrobert000000 000000 Filtering Log Messages {#filters} === [TOC] # Filtering Messages {#filtering} 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. When defining filters, note that they can only be defined 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 The following pages have information on specific filters: * @subpage map-filter * @subpage location-info-filter apache-log4cxx-1.1.0/src/site/markdown/filters/MapFilter.md000644 001750 001750 00000012525 14353331212 024410 0ustar00robertrobert000000 000000 MapFilter {#map-filter} === The MapFilter allows filtering against data elements that are in the Mapped Diagnostic Context (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 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 ``` apache-log4cxx-1.1.0/src/site/markdown/stacktrace.md000644 001750 001750 00000005017 14354342764 023216 0ustar00robertrobert000000 000000 Stacktrace Support {#stacktrace-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.1.0/src/site/markdown/faq.md000644 001750 001750 00000012266 14353331212 021626 0ustar00robertrobert000000 000000 FAQ {#faq} === # Frequently Asked Technical Questions ## Table of contents
  1. How do I add a custom level to Apache Log4cxx?
  2. My application on Windows crashes on shutdown?
  3. Does Apache Log4cxx support Unicode?
## How do I add a custom level to Apache Log4cxx? 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? 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? 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 Unicode representations selected by the `--with-logchar` 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. FileAppenders support an encoding property as well, which should be explicitly specified to `UTF-8` or `UTF-16` for e.g. XML files. The important point is to get the chain of input, internal processing and output correct and that might need some additional setup in the app using Log4cxx: 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`. One might need to explicitly tell the app at startup to use the locale of the environment and make things compatible with Unicode this way. See also [some SO post](https://stackoverflow.com/questions/571359/how-do-i-set-the-proper-initial-locale-for-a-c-program-on-windows) on setting the default locale in C++. ``` std::setlocale( LC_ALL, "" ); /* Set locale for C functions */ std::locale::global(std::locale("")); /* set locale for C++ functions */ ``` See [LOGCXX-483](https://issues.apache.org/jira/browse/LOGCXX-483) or [GHPR #31](https://github.com/apache/logging-log4cxx/pull/31#issuecomment-668870727) for additional details. apache-log4cxx-1.1.0/src/site/markdown/macros-influencing-log4cxx.md000644 001750 001750 00000004054 14354342764 026243 0ustar00robertrobert000000 000000 Macros Influencing Log4cxx {#macros-influencing-log4cxx} === # Macros that influence 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](usage.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. | apache-log4cxx-1.1.0/src/site/markdown/threading.md000644 001750 001750 00000012100 14353331212 023007 0ustar00robertrobert000000 000000 Threading {#threading} === [TOC] # Threading Notes with Log4cxx {#threading-notes} 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.1.0/src/site/markdown/qt-support.md000644 001750 001750 00000003157 14353331212 023214 0ustar00robertrobert000000 000000 Qt 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 separate library, log4cxx-qt, which contains useful utilities for working with Qt. 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. apache-log4cxx-1.1.0/src/site/markdown/0-community.md000644 001750 001750 00000001764 14353331212 023241 0ustar00robertrobert000000 000000 Community {#community} === See the following pages for community information: * @subpage issue-tracking * @subpage mailing-lists apache-log4cxx-1.1.0/src/site/markdown/development/000755 001750 001750 00000000000 14424433605 023060 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/site/markdown/development/build-vcpkg.md000644 001750 001750 00000003027 14353331212 025603 0ustar00robertrobert000000 000000 Building with vcpkg {#build-vcpkg} === # Building Apache Log4cxx with 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.1.0/src/site/markdown/development/build-cmake.md000644 001750 001750 00000014544 14354342764 025576 0ustar00robertrobert000000 000000 Build with CMake {#build-cmake} === # Building Apache Log4cxx with CMake ## Quick start: Building and testing Log4cxx on a Unix platform with packaged APR and APR-Util. Make sure cmake 3.13+, g++ and make are available, install or build apr 1.x, apr-util 1.x, gzip and zip. Linux example: ~~~ $ apt-get install build-essential libapr1-dev libaprutil1-dev gzip zip $ cd apache-Log4cxx-x.x.x $ mkdir build $ cd build $ ccmake .. $ make $ sudo make install ~~~ Windows Example: Building and testing Log4cxx on a Microsoft Windows with APR, Expat and APR-Util built from source extracted into apr-1.7.0, libexpat(from github) and apr-util-1.6.1 in %HOMEPATH%/Libraries. ~~~ $ 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.0 -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.1 -B buildtrees/apr-util -DCMAKE_INSTALL_PREFIX=%HOMEPATH%/Libraries/installed $ cmake --build buildtrees/apr-util --target install --config Release $ cmake -S apache-Log4cxx-x.x.x -B buildtrees/Log4cxx -DCMAKE_INSTALL_PREFIX=%HOMEPATH%/Libraries/installed $ cmake --build buildtrees/Log4cxx --target install --config Release ~~~ ## ccmake options | Option | Usage | |------------------------|-------| | -DLOG4CXX_WCHAR_T=no | Enable wchar_t API methods, choice of yes (default), no. | | -DLOG4CXX_UNICHAR=yes | Enable UniChar API methods, choice of yes, no (default). | | -DLOG4CXX_CFSTRING=yes | Enable CFString API methods, requires Mac OS/X CoreFoundation, choice of yes, no (default). | | -DBUILD_TESTING=off | Do not build tests. Tests are built by default | | -DBUILD_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. | | -DAPU_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. | | -DAPR_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. | |-DLOG4CXX_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. | | -DPREFER_BOOST=on | Prefer the Boost version of dependent libraries over standard library | ## A note on C++ version and Boost By default, Log4cxx attempts to use at least C++17 to compile. 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 libaries 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. # Platform specific notes: ## 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". ## Debian: APR, APR-Util, openssl, gzip and zip may be installed by: ~~~ $ sudo apt-get install libssl-dev libapr1-dev libaprutil1-dev gzip zip ~~~ CMake can be built from source by typing: ~~~ $ wget https://github.com/Kitware/CMake/releases/download/v3.16.4/cmake-3.16.4.tar.gz $ tar xf cmake-3.16.4.tar.gz $ cd cmake-3.16.4 $ ./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 ~~~ ## Windows: The easiest way to get dependencies installed is to use vcpkg(for APR/expat), and msys2 for the command-line utilities(zip, grep, sed). Msys2 can be downloaded from: https://www.msys2.org/ By default, this will be installed under C:\\msys2, so you can add that to the build PATH by setting LOG4CXX_TEST_PROGRAM_PATH=C:/msys64/usr/bin in your build settings. For 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`. # Using Log4cxx in a CMake build A log4cxxConfig.cmake and log4cxxConfigVersion.cmake is installed to allow use of find_package() in your CMakeLists.txt. Below are example cmake commands that compile and link "myApplication" with Log4cxx. ~~~ find_package(log4cxx 0.11) add_executable(myApplication myMain.cpp) target_include_directories(myApplication PRIVATE $) target_link_libraries( myApplication PRIVATE log4cxx) ~~~ apache-log4cxx-1.1.0/src/site/markdown/development/building.md000644 001750 001750 00000004024 14353331212 025167 0ustar00robertrobert000000 000000 Building {#building} === # Building Apache Log4cxx As of version 0.11.0, the only supported build system for Log4cxx is CMake. Have a look at the [build with CMake](build-cmake.html) page for more information. If you have trouble building, either create an issue in [Jira](https://issues.apache.org/jira/projects/LOGCXX/issues) or send a message to the [users mailing list]. ## Covered by the team The following list 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. The following platforms/compilers are expected to work correctly: * Windows 10(32 and 64-bit) - MSVC * Windows 10(32-bit) - Embarcadero C++ Builder XE 4 * Debian 10(32 and 64-bit) - gcc 8.3.0, clang-7 * Ubuntu 20.04(32 and 64-bit) - gcc, clang * Mac OSX - clang 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. [users mailing list]:@ref mailing-lists apache-log4cxx-1.1.0/src/site/markdown/development/source-repository.md000644 001750 001750 00000003042 14353331212 027106 0ustar00robertrobert000000 000000 Source 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.1.0/src/site/markdown/development/dependencies.md000644 001750 001750 00000006075 14353331212 026030 0ustar00robertrobert000000 000000 Dependencies {#dependencies} === # Log4cxx Dependencies As of version 0.12.0, Log4cxx requires a minimum C++ version of C++11. If C++17 is not available, then Log4cxx requires Boost Thread in order to build, which in turn requires chrono and date\_time. 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 |Boost |any? |Compile/runtime. Not required if your compiler supports C++17|https://boost.org |gzip |any |Test/Runtime(optional)|https://gzip.org |sed |any |Test|N/A |zip |any |Test/Runtime(optional)|N/A |log4j |1.2.14 |Test |https://http://logging.apache.org/log4j/2.x/ |java |>=6 |Test |https://adoptopenjdk.net ## 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`. ## log4j+Java log4j and Java are needed to run some tests to ensure that log4cxx has binary compatability with log4j. Note that the correct binary for log4j will be downloaded and used automatically if CMAKE is used to build the project, otherwise one needs to get that manually. Java needs to be installed on the system already in all cases, but with CMAKE again, if it's not, the corresponding tests are skipped entirely automatically. # Licenses(direct dependencies only) **Apache License, Version 2.0**: log4cxx, APR, APR-util **Boost License, Version 1.0**: boost apache-log4cxx-1.1.0/src/site/markdown/1-usage.md000644 001750 001750 00000002366 14354342764 022340 0ustar00robertrobert000000 000000 Usage {#usage-overview} === See the following pages for usage information: * @subpage usage * @subpage filters * @subpage threading * @subpage extending-log4cxx * @subpage stacktrace-support * @subpage faq * @subpage configuration-samples * @subpage qt-support * @subpage performance * @subpage multiprocess-logging * @subpage environment-variables * @subpage macros-influencing-log4cxx apache-log4cxx-1.1.0/src/site/doxy/000755 001750 001750 00000000000 14424433605 017677 5ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/site/doxy/DoxygenLayout.xml000644 001750 001750 00000014265 14353331212 023234 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/site/doxy/license_notice_footer.txt000644 001750 001750 00000001420 14353331212 024766 0ustar00robertrobert000000 000000 apache-log4cxx-1.1.0/src/site/doxy/Doxyfile.in000644 001750 001750 00000324035 14354342764 022030 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.8.13 # 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 (\" \"). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config 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 http://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 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. # The default value is: NO. CREATE_SUBDIRS = NO # 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, Catalan, Chinese, # Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), # Esperanto, Farsi (Persian), Finnish, French, German, Greek, 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 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 # 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:\n" # 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:". You can put \n's in the value part of an alias to insert # newlines. ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding "class=itcl::class" # will allow you to use the command class in the itcl::class meaning. 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 # 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, # C#, C, C++, D, PHP, Objective-C, Python, 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), VHDL. 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. 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 http://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: 0. # 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: # http://www.riverbankcomputing.co.uk/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 #--------------------------------------------------------------------------- # 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_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 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 # 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 # (class|struct|union) 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 # If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file # names in lower-case letters. If set to YES, upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. # The default value is: system dependent. 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_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. # # 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 http://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 not documenting some parameters # in a documented function, or documenting parameters that don't exist or using # markup commands wrongly. # The default value is: YES. WARN_IF_DOC_ERROR = 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 or incomplete # parameter documentation, but not about the absence of documentation. # The default value is: NO. WARN_NO_PARAMDOC = NO # If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when # a warning is encountered. # 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) # The default value is: $file:$line: $text. WARN_FORMAT = "$file:$line: $text" # 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). 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: http://www.gnu.org/software/libiconv) for the list of # possible encodings. # The default value is: UTF-8. INPUT_ENCODING = UTF-8 # 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. # # 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++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, # *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, # *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf. 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, # AClass::ANamespace, 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 # 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 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 #--------------------------------------------------------------------------- # 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 # function 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 http://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 config 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 # If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the # clang parser (see: http://clang.llvm.org/) for more accurate parsing at the # cost of reduced performance. This can be particularly helpful with template # rich C++ code for which doxygen's built-in parser lacks the necessary type # information. # Note: The availability of this option depends on whether or not doxygen was # generated with the -Duse-libclang=ON option for CMake. # The default value is: NO. CLANG_ASSISTED_PARSING = NO # If clang assisted parsing is enabled you can provide the compiler with command # line options that you would normally use when invoking the compiler. Note that # the include paths will already be set by doxygen for the files and directories # specified with INPUT and INCLUDE_PATH. # This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. CLANG_OPTIONS = #--------------------------------------------------------------------------- # 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 # In case all classes in a project start with a common prefix, all classes will # be put under the same header in the alphabetical index. 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. # 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 = # 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). 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_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 colorwheel, see # http://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 grayscales 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_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: http://developer.apple.com/tools/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 http://developer.apple.com/tools/creatingdocsetswithdoxygen.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 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 # (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on # Windows. # # 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 master .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: http://qt-project.org/doc/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: http://qt-project.org/doc/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: http://qt-project.org/doc/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: http://qt-project.org/doc/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: # http://qt-project.org/doc/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 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. 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 # 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 # 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 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are not # supported properly for IE 6.0, but are supported on all modern browsers. # # Note that when changing this option you need to delete any form_*.png files in # the HTML output directory before the changes have effect. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see # http://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 # When MathJax is enabled you can set the default output format to be used for # the MathJax output. See the MathJax site (see: # http://docs.mathjax.org/en/latest/output.html) for more details. # Possible values are: HTML-CSS (which is slower, but has the best # compatibility), NativeMML (i.e. MathML) 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 http://www.mathjax.org before deployment. # The default value is: http://cdn.mathjax.org/mathjax/latest. # 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 # MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols # 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/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 # , /