apache-log4cxx-0.12.1/liblog4cxx.pc.in000644 001750 001750 00000002005 14120250670 020240 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/LICENSE000644 001750 001750 00000026136 14120250670 016250 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-0.12.1/liblog4cxx-qt.pc.in000644 001750 001750 00000002006 14120250670 020663 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/INSTALL000644 001750 001750 00000001737 14120250670 016274 0ustar00robertrobert000000 000000 Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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-0.12.1/.github/000755 001750 001750 00000000000 14122472744 016605 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/.github/workflows/000755 001750 001750 00000000000 14122472744 020642 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/.github/workflows/abi-compatibility.yml000644 001750 001750 00000003542 14120250670 024761 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 . - uses: actions/upload-artifact@v2 with: name: abi-compatibility-report path: main/build/src/main/cpp/compat_reports/log4cxx/11_to_11/compat_report.html apache-log4cxx-0.12.1/.github/workflows/log4cxx.yml000644 001750 001750 00000006773 14120250670 022760 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 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: [ubuntu18-gcc, ubuntu18-clang, osx, windows-2019] include: - name: windows-2019 os: windows-2019 cxx: cl.exe cc: cl.exe - name: ubuntu18-gcc os: ubuntu-18.04 cxx: g++ cc: gcc - name: ubuntu18-clang os: ubuntu-18.04 cxx: clang++ cc: clang - name: osx os: macos-latest cxx: clang++ cc: clang steps: - uses: actions/checkout@v2 with: path: main - name: 'Configure Dependencies - Ubuntu' if: matrix.name == 'ubuntu18-gcc' || matrix.name == 'ubuntu18-clang' run: | sudo apt-get update sudo apt-get install -y libapr1-dev libaprutil1-dev - name: 'Restore Prebuilt Dependencies - Windows' id: restore-vcpkg-cache if: matrix.name == 'windows-2019' || matrix.name == 'windows-2016' uses: actions/cache@v2 with: path: vcpkg key: ${{ runner.os }}-${{ matrix.name }}-cache - name: 'Checkout VCPKG - Windows' if: (matrix.name == 'windows-2019' || matrix.name == 'windows-2016') && steps.restore-vcpkg-cache.outputs.cache-hit != 'true' uses: actions/checkout@v2 with: repository: microsoft/vcpkg path: vcpkg ref: ec6fe06e8da05a8157dc8581fa96b36b571c1bd5 - name: 'Configure Dependencies - Windows' if: (matrix.name == 'windows-2019' || matrix.name == 'windows-2016') && 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 - name: 'run cmake - win' if: (matrix.name == 'windows-2019' || matrix.name == 'windows-2016') shell: pwsh run: | $THISDIR=Get-Location cd main mkdir build cd build cmake -DLOG4CXX_TEST_PROGRAM_PATH=C:\msys64\usr\bin "-DCMAKE_TOOLCHAIN_FILE=$THISDIR/vcpkg/scripts/buildsystems/vcpkg.cmake" -DCMAKE_CXX_COMPILER=${{ matrix.cxx }} -DCMAKE_C_COMPILER=${{ matrix.cc }} .. cmake --build . - name: 'run cmake - *nix' if: matrix.name != 'windows-2019' run: | cd main mkdir build cd build cmake -DCMAKE_CXX_COMPILER=${{ matrix.cxx }} -DCMAKE_C_COMPILER=${{ matrix.cc }} .. cmake --build . - name: run unit tests shell: pwsh run: | cd main cd build ctest -C Debug --output-on-failure -V apache-log4cxx-0.12.1/KEYS000644 001750 001750 00000034774 14120250670 015750 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-0.12.1/.asf.yaml000644 001750 001750 00000001735 14120250670 016754 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 apache-log4cxx-0.12.1/CMakeLists.txt000644 001750 001750 00000022533 14121416667 020013 0ustar00robertrobert000000 000000 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 set(LIBLOG4CXX_LIB_VERSION ${log4cxx_VERSION_MINOR}.${log4cxx_VERSION_PATCH}.${log4cxx_VERSION_TWEAK}) set(LIBLOG4CXX_LIB_SOVERSION ${log4cxx_VERSION_MINOR}) # 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() # Find Apache Runtime find_package(APR REQUIRED) # Find Apache Runtime Utilities find_package(APR-Util REQUIRED) find_package( Threads REQUIRED ) # Find expat for XML parsing find_package(EXPAT REQUIRED) # 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 include(GNUInstallDirs) install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/src/main/include/log4cxx DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} FILES_MATCHING PATTERN "*.h" ) install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/src/main/include/log4cxx DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} FILES_MATCHING PATTERN "*.h" ) 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_DATAROOTDIR}/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_DATAROOTDIR}/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 share/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 share/cmake/log4cxx ) if(LOG4CXX_QT_SUPPORT) install(EXPORT log4cxx-qtTargets FILE log4cxx-qtConfig.cmake DESTINATION share/cmake/log4cxx ) # 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 share/cmake/log4cxx ) 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_ODBC DIRECTORY src/main/include DEFINITION HAS_ODBC ) get_directory_property( HAS_SYSLOG DIRECTORY src/main/include DEFINITION HAS_SYSLOG ) get_directory_property( THREAD_IMPL DIRECTORY src/main/include DEFINITION THREAD_IMPL ) get_directory_property( SMART_PTR_IMPL DIRECTORY src/main/include DEFINITION SMART_PTR_IMPL ) get_directory_property( MUTEX_IMPL DIRECTORY src/main/include DEFINITION MUTEX_IMPL ) get_directory_property( SHARED_MUTEX_IMPL DIRECTORY src/main/include DEFINITION SHARED_MUTEX_IMPL ) get_directory_property( ATOMIC_IMPL DIRECTORY src/main/include DEFINITION ATOMIC_IMPL ) foreach(varName HAS_STD_LOCALE HAS_ODBC HAS_MBSRTOWCS HAS_WCSTOMBS HAS_FWIDE HAS_LIBESMTP HAS_SYSLOG) if(${varName} EQUAL 0) set(${varName} "OFF" ) elseif(${varName} EQUAL 1) set(${varName} "ON" ) else() set(${varName} "UNKNOWN" ) endif() endforeach() # # 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 # if( "${SHARED_MUTEX_IMPL}" STREQUAL "NONE" ) message( FATAL_ERROR "No shared_mutex implementation found. Requires Boost or C++17" ) endif() # # Output configuration information # Similar to APR CMake configuration # message(STATUS "") message(STATUS "") message(STATUS "log4cxx configuration summary:") message(STATUS "") 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 " log4cxx char API ................ : ${LOG4CXX_CHAR}") message(STATUS " log4cxx wchar API ............... : ${LOG4CXX_WCHAR_T}") message(STATUS " log4cxx unichar API ............. : ${LOG4CXX_UNICHAR}") if(APPLE) message(STATUS " log4cxx cfstring API ............ : ${LOG4CXX_CFSTRING}") endif() message(STATUS " logchar type .................... : ${LOG4CXX_CHAR}") message(STATUS " charset ......................... : ${LOG4CXX_CHARSET}") message(STATUS " Using libESMTP .................. : ${HAS_LIBESMTP}") message(STATUS " ODBC library .................... : ${HAS_ODBC}") message(STATUS " syslog .......................... : ${HAS_SYSLOG}") message(STATUS " Qt support ...................... : ${LOG4CXX_QT_SUPPORT}") message(STATUS " shared_mutex implementation ..... : ${SHARED_MUTEX_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) apache-log4cxx-0.12.1/.astylerc000644 001750 001750 00000001730 14120250670 017063 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 --recursive --style=break --suffix=none apache-log4cxx-0.12.1/.gitignore000644 001750 001750 00000000747 14121417332 017234 0ustar00robertrobert000000 000000 .deps .dirstamp *.lo *.m4 *.o *.swp ar-lib config** !configuration-samples.md depcomp install-sh liblog4cxx.pc libtool ltmain.sh Makefile Makefile.in missing pom.xml.releaseBackup release.properties autom4te.cache/ src/.vs 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/out src/site/doxy/Doxyfile src/site/doxy/manual/ src/test/resources/org/ src/test/resources/output/ target/ apache-log4cxx-0.12.1/NOTICE000644 001750 001750 00000000250 14121416517 016141 0ustar00robertrobert000000 000000 Apache log4cxx Copyright 2004-2021 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). apache-log4cxx-0.12.1/.gitattributes.swp000644 001750 001750 00000030000 14121417452 020733 0ustar00robertrobert000000 000000 b0VIM 8.1QAab'robertdebian~robert/logging-log4cxx/.gitattributesutf-8 3210#"! UtpadOOsrc/test/resources/input/propertiestestcase.properties binarysrc/main/resources/log4cxx.rc eol=crlf# This is a windows-specific file*.jpg binary*.png binary* text eol=lfapache-log4cxx-0.12.1/src/000755 001750 001750 00000000000 14122472745 016035 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/000755 001750 001750 00000000000 14122472745 017014 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/CMakeLists.txt000644 001750 001750 00000000222 14120250671 021536 0ustar00robertrobert000000 000000 find_package(Java COMPONENTS Development) if(Java_Development_FOUND) add_subdirectory(java) endif(Java_Development_FOUND) add_subdirectory(cpp) apache-log4cxx-0.12.1/src/test/cpp/000755 001750 001750 00000000000 14122472744 017575 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/mdctestcase.cpp000644 001750 001750 00000003206 14120250671 022570 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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() { log4cxx::spi::LoggerRepositoryPtr rep = Logger::getRootLogger()->getLoggerRepository().lock(); 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-0.12.1/src/test/cpp/util/000755 001750 001750 00000000000 14122472744 020552 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/util/absolutedateandtimefilter.h000644 001750 001750 00000002111 14120250671 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. */ #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-0.12.1/src/test/cpp/util/filenamefilter.h000644 001750 001750 00000002232 14120250671 023677 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/util/compare.h000644 001750 001750 00000002342 14120250671 022341 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/transformer.cpp000644 001750 001750 00000013566 14120250671 023622 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; for (log4cxx::Filter::PatternList::const_iterator iter = patterns.begin(); iter != patterns.end(); iter++) { tmp = "sQ"; tmp.append(iter->first); tmp.append(1, 'Q'); tmp.append(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-0.12.1/src/test/cpp/util/linenumberfilter.h000644 001750 001750 00000002061 14120250671 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. */ #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-0.12.1/src/test/cpp/util/controlfilter.cpp000644 001750 001750 00000001760 14120250671 024137 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/xmltimestampfilter.cpp000644 001750 001750 00000001767 14120250671 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 "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-0.12.1/src/test/cpp/util/transformer.h000644 001750 001750 00000003103 14120250671 023251 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/util/absolutedateandtimefilter.cpp000644 001750 001750 00000001754 14120250671 026500 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/controlfilter.h000644 001750 001750 00000002162 14120250671 023601 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/util/xmlthreadfilter.cpp000644 001750 001750 00000001737 14120250671 024453 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/binarycompare.h000644 001750 001750 00000002044 14120250671 023545 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/threadfilter.h000644 001750 001750 00000002032 14120250671 023364 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/util/relativetimefilter.cpp000644 001750 001750 00000001716 14120250671 025152 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/filenamefilter.cpp000644 001750 001750 00000002524 14120250671 024236 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/relativetimefilter.h000644 001750 001750 00000002054 14120250671 024613 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/util/serializationtesthelper.h000644 001750 001750 00000002665 14120250671 025700 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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_SERIALIZATIONTESTHELPER_H #define _LOG4CXX_TESTS_UTIL_SERIALIZATIONTESTHELPER_H #include namespace log4cxx { namespace util { class SerializationTestHelper { public: static bool compare(const char* filename, const log4cxx::spi::LoggingEventPtr& event, size_t stopCompare); static bool compare(const char* filename, const std::vector& array, size_t stopCompare, log4cxx::helpers::Pool& p); private: SerializationTestHelper(); SerializationTestHelper(const SerializationTestHelper&); SerializationTestHelper& operator=(SerializationTestHelper&); }; } } #endif apache-log4cxx-0.12.1/src/test/cpp/util/CMakeLists.txt000644 001750 001750 00000001371 14120250671 023303 0ustar00robertrobert000000 000000 # Components required by all tests add_library(testingUtilities STATIC serializationtesthelper.cpp 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-0.12.1/src/test/cpp/util/linenumberfilter.cpp000644 001750 001750 00000002044 14120250671 024613 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/filter.h000644 001750 001750 00000004063 14120250671 022202 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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; }; } #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_TESTS_UTIL_FILTER_H apache-log4cxx-0.12.1/src/test/cpp/util/xmltimestampfilter.h000644 001750 001750 00000002073 14120250671 024646 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/util/serializationtesthelper.cpp000644 001750 001750 00000005160 14120250671 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 "serializationtesthelper.h" #include #include #include #include #include #include "apr_pools.h" using namespace log4cxx; using namespace log4cxx::util; using namespace log4cxx::helpers; using namespace log4cxx::spi; bool SerializationTestHelper::compare( const char* witness, const LoggingEventPtr& event, size_t endCompare) { ByteArrayOutputStreamPtr memOut = ByteArrayOutputStreamPtr( new ByteArrayOutputStream() ); Pool p; ObjectOutputStream objOut(memOut, p); event->write(objOut, p); objOut.close(p); return compare(witness, memOut->toByteArray(), endCompare, p); } /** * Asserts the serialized form of an object. * @param witness file name of expected serialization. * @param actual byte array of actual serialization. * @param skip positions to skip comparison. * @param endCompare position to stop comparison. * @throws IOException thrown on IO or serialization exception. */ bool SerializationTestHelper::compare( const char* witness, const std::vector& actual, size_t endCompare, Pool& p) { File witnessFile(witness); char* expected = p.pstralloc(actual.size()); FileInputStreamPtr is(new FileInputStream(witnessFile)); ByteBuffer readBuffer(expected, actual.size()); int bytesRead = is->read(readBuffer); is->close(); if (bytesRead < endCompare) { puts("Witness file is shorter than expected"); return false; } size_t endScan = actual.size(); if (endScan > endCompare) { endScan = endCompare; } for (size_t i = 0; i < endScan; i++) { if (((unsigned char) expected[i]) != actual[i]) { printf("Difference at offset %d, expected %x, actual %x\n", i, expected[i], actual[i]); return false; } } return true; } apache-log4cxx-0.12.1/src/test/cpp/util/iso8601filter.cpp000644 001750 001750 00000001670 14120250671 023570 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/xmlfilenamefilter.cpp000644 001750 001750 00000002257 14120250671 024762 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/absolutetimefilter.cpp000644 001750 001750 00000001716 14120250671 025155 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/absolutetimefilter.h000644 001750 001750 00000002054 14120250671 024616 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/util/xmlthreadfilter.h000644 001750 001750 00000002054 14120250671 024111 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/util/xmllineattributefilter.cpp000644 001750 001750 00000002012 14120250671 026042 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/utilfilter.cpp000644 001750 001750 00000002124 14120250671 023427 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/compare.cpp000644 001750 001750 00000010032 14120250671 022667 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/iso8601filter.h000644 001750 001750 00000002042 14120250671 023227 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/util/xmllineattributefilter.h000644 001750 001750 00000002122 14120250671 025511 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/util/binarycompare.cpp000644 001750 001750 00000005056 14120250671 024106 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/util/threadfilter.cpp000644 001750 001750 00000001706 14120250671 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 "threadfilter.h" using namespace log4cxx; using namespace log4cxx::helpers; ThreadFilter::ThreadFilter() : Filter("\\[[0-9A-Fa-fXx]*]", "\\[main]") {} apache-log4cxx-0.12.1/src/test/cpp/util/xmlfilenamefilter.h000644 001750 001750 00000002154 14120250671 024423 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/hierarchytest.cpp000644 001750 001750 00000003555 14120250671 023156 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/test/cpp/abts.cpp000644 001750 001750 00000022600 14120250671 021221 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 == 0) { fprintf(stdout, "SUCCESS\n"); fflush(stdout); } else { fprintf(stdout, "FAILED %d of %d\n", last->failed, 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 = (sub_suite*) malloc(sizeof(*subsuite)); subsuite->num_test = 0; subsuite->failed = 0; 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); } else { subsuite->name = suite_name; } if (list_tests) { fprintf(stdout, "%s\n", subsuite->name); } subsuite->not_run = 0; if (suite == NULL) { suite = (abts_suite*) malloc(sizeof(*suite)); suite->head = subsuite; suite->tail = subsuite; } else { suite->tail->next = subsuite; suite->tail = subsuite; } if (!should_test_run(subsuite->name)) { subsuite->not_run = 1; return suite; } reset_status(); fprintf(stdout, "%-20s: ", subsuite->name); update_status(); fflush(stdout); return suite; } void abts_run_test(abts_suite* ts, test_func f, void* value) { abts_case tc; sub_suite* ss; if (!should_test_run(ts->tail->name)) { return; } ss = ts->tail; tc.failed = 0; tc.suite = ss; ss->num_test++; update_status(); f(&tc, value); if (tc.failed) { ss->failed++; } } static int report(abts_suite* suite) { int 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; } 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 != 0) { float percent = ((float)dptr->failed / (float)dptr->num_test); fprintf(stdout, "%-15s\t\t%5d\t%4d\t%6.2f%%\n", dptr->name, dptr->num_test, dptr->failed, percent * 100); } 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 i; int rv; int list_provided = 0; abts_suite* suite = NULL; initialize(); #if defined(_MSC_VER) quiet = 1; #else quiet = !isatty(STDOUT_FILENO); #endif for (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 (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 // sub_suite* next; for (sub_suite* head = suite->head; head != NULL; head = next) { next = head->next; free((void*) head->name); free(head); } free(suite); } return rv; } apache-log4cxx-0.12.1/src/test/cpp/leveltestcase.cpp000644 001750 001750 00000006411 14120250671 023135 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/insertwide.h000644 001750 001750 00000002266 14120250671 022120 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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-0.12.1/src/test/cpp/testutil.h000644 001750 001750 00000001704 14120250671 021614 0ustar00robertrobert000000 000000 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/helpers/000755 001750 001750 00000000000 14122472744 021237 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/helpers/stringhelpertestcase.cpp000644 001750 001750 00000006646 14120250671 026210 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/test/cpp/helpers/propertiestestcase.cpp000644 001750 001750 00000017521 14120250671 025670 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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(testCRLF1); LOGUNIT_TEST(testEscT1); LOGUNIT_TEST(testEscT2); LOGUNIT_TEST(testEscN1); LOGUNIT_TEST(testEscN2); LOGUNIT_TEST(testEscR1); LOGUNIT_TEST(testEscR2); 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 in value continuation, see LOGCXX-292. */ void testCRLF1() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString actual(properties.getProperty(LOG4CXX_STR("propertiestestcase.crlf1"))); 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); } }; LOGUNIT_TEST_SUITE_REGISTRATION(PropertiesTestCase); apache-log4cxx-0.12.1/src/test/cpp/helpers/transcodertestcase.cpp000644 001750 001750 00000024006 14120250671 025634 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/helpers/messagebuffertest.cpp000644 001750 001750 00000014274 14120250671 025460 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/test/cpp/helpers/syslogwritertest.cpp000644 001750 001750 00000002446 14120250671 025415 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/helpers/cacheddateformattestcase.cpp000644 001750 001750 00000046264 14120250671 026760 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/helpers/charsetdecodertestcase.cpp000644 001750 001750 00000006223 14120250671 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. */ #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; #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) strcat_s(buf, sizeof buf, "Hello"); #else strcat(buf, "Hello"); #endif 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-0.12.1/src/test/cpp/helpers/timezonetestcase.cpp000644 001750 001750 00000006430 14120250671 025323 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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); #if !defined(__BORLANDC__) LOGUNIT_TEST(test3); #endif 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-0.12.1/src/test/cpp/helpers/localechanger.cpp000644 001750 001750 00000002646 14120250671 024531 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #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::runtime_error&) { } catch (std::exception&) { } } /** * Restores previous locale. */ LocaleChanger::~LocaleChanger() { if (effective) { std::locale::global(initial); } } #endif apache-log4cxx-0.12.1/src/test/cpp/helpers/absolutetimedateformattestcase.cpp000644 001750 001750 00000013011 14120250671 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. */ #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-0.12.1/src/test/cpp/helpers/CMakeLists.txt000644 001750 001750 00000002071 14122472113 023765 0ustar00robertrobert000000 000000 set(HELPER_TESTS absolutetimedateformattestcase cacheddateformattestcase casttestcase charsetdecodertestcase charsetencodertestcase cyclicbuffertestcase datetimedateformattestcase filewatchdogtest inetaddresstestcase iso8601dateformattestcase messagebuffertest optionconvertertestcase propertiestestcase relativetimedateformattestcase stringhelpertestcase stringtokenizertestcase syslogwritertest timezonetestcase transcodertestcase ) 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-0.12.1/src/test/cpp/helpers/inetaddresstestcase.cpp000644 001750 001750 00000004730 14120250671 025777 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/helpers/localechanger.h000644 001750 001750 00000003012 14120250671 024162 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/helpers/casttestcase.cpp000644 001750 001750 00000003252 14120250671 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. */ #include "../logunit.h" #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_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); } }; LOGUNIT_TEST_SUITE_REGISTRATION(CastTestCase); apache-log4cxx-0.12.1/src/test/cpp/helpers/charsetencodertestcase.cpp000644 001750 001750 00000021543 14120250671 026464 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/helpers/stringtokenizertestcase.cpp000644 001750 001750 00000007645 14120250671 026743 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/test/cpp/helpers/cyclicbuffertestcase.cpp000644 001750 001750 00000010105 14120250671 026123 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/helpers/filewatchdogtest.cpp000644 001750 001750 00000003442 14120250671 025275 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/test/cpp/helpers/datetimedateformattestcase.cpp000644 001750 001750 00000015750 14120250671 027341 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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-0.12.1/src/test/cpp/helpers/relativetimedateformattestcase.cpp000644 001750 001750 00000004572 14120250671 030237 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/helpers/optionconvertertestcase.cpp000644 001750 001750 00000013571 14120250671 026735 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/helpers/iso8601dateformattestcase.cpp000644 001750 001750 00000011324 14120250671 026647 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/test/cpp/encodingtest.cpp000644 001750 001750 00000011376 14120250671 022766 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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() { log4cxx::spi::LoggerRepositoryPtr rep = Logger::getRootLogger()->getLoggerRepository().lock(); 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-0.12.1/src/test/cpp/consoleappendertestcase.cpp000644 001750 001750 00000003406 14120250671 025210 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/l7dtestcase.cpp000644 001750 001750 00000006357 14120250671 022525 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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() { log4cxx::spi::LoggerRepositoryPtr rep = root->getLoggerRepository().lock(); 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/temp"), LOG4CXX_FILE("witness/l7d.1"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(L7dTestCase); apache-log4cxx-0.12.1/src/test/cpp/logunit.h000644 001750 001750 00000017171 14120250671 021425 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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__) #if defined(_MSC_VER) #pragma warning (pop) #endif #endif apache-log4cxx-0.12.1/src/test/cpp/fileappendertestcase.h000644 001750 001750 00000002216 14120250671 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. */ #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-0.12.1/src/test/cpp/ndctestcase.cpp000644 001750 001750 00000005346 14120250671 022600 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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() { log4cxx::spi::LoggerRepositoryPtr rep = logger->getLoggerRepository().lock(); 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/temp"); LoggerPtr NDCTestCase::logger(Logger::getLogger("org.apache.log4j.NDCTestCase")); LOGUNIT_TEST_SUITE_REGISTRATION(NDCTestCase); apache-log4cxx-0.12.1/src/test/cpp/nt/000755 001750 001750 00000000000 14122472744 020216 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/nt/CMakeLists.txt000644 001750 001750 00000000204 14120250671 022741 0ustar00robertrobert000000 000000 add_executable(eventlogtests nteventlogappendertestcase.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} eventlogtests PARENT_SCOPE) apache-log4cxx-0.12.1/src/test/cpp/nt/nteventlogappendertestcase.cpp000644 001750 001750 00000006172 14120250671 026357 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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-0.12.1/src/test/cpp/appenderskeletontestcase.cpp000644 001750 001750 00000003035 14120250671 025370 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/spi/000755 001750 001750 00000000000 14122472744 020370 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/spi/CMakeLists.txt000644 001750 001750 00000000166 14120250671 023122 0ustar00robertrobert000000 000000 add_executable(spitestcase loggingeventtest.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} spitestcase PARENT_SCOPE) apache-log4cxx-0.12.1/src/test/cpp/spi/loggingeventtest.cpp000644 001750 001750 00000006622 14120250671 024461 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "../util/serializationtesthelper.h" #include #include #include #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::util; using namespace log4cxx::spi; using namespace std; /** Unit tests for LoggingEvent */ LOGUNIT_CLASS(LoggingEventTest) { LOGUNIT_TEST_SUITE(LoggingEventTest); LOGUNIT_TEST(testSerializationSimple); LOGUNIT_TEST(testSerializationWithLocation); LOGUNIT_TEST(testSerializationNDC); LOGUNIT_TEST(testSerializationMDC); LOGUNIT_TEST_SUITE_END(); public: void setUp() { NDC::clear(); MDC::clear(); } void tearDown() { LogManager::shutdown(); } /** * Serialize a simple logging event and check it against * a witness. * @throws Exception if exception during test. */ void testSerializationSimple() { LoggingEventPtr event = LoggingEventPtr( new LoggingEvent( LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LocationInfo::getLocationUnavailable())); LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare( "witness/serialization/simple.bin", event, 237)); } /** * Serialize a logging event with an exception and check it against * a witness. * @throws Exception if exception during test. * */ void testSerializationWithLocation() { LoggingEventPtr event = LoggingEventPtr( new LoggingEvent( LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LOG4CXX_LOCATION)); LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare( "witness/serialization/location.bin", event, 237)); } /** * Serialize a logging event with ndc. * @throws Exception if exception during test. * */ void testSerializationNDC() { NDC::push("ndc test"); LoggingEventPtr event = LoggingEventPtr( new LoggingEvent( LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LocationInfo::getLocationUnavailable())); LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare( "witness/serialization/ndc.bin", event, 237)); } /** * Serialize a logging event with mdc. * @throws Exception if exception during test. * */ void testSerializationMDC() { MDC::put("mdckey", "mdcvalue"); LoggingEventPtr event = LoggingEventPtr( new LoggingEvent( LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LocationInfo::getLocationUnavailable())); LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare( "witness/serialization/mdc.bin", event, 237)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(LoggingEventTest); apache-log4cxx-0.12.1/src/test/cpp/logunit.cpp000644 001750 001750 00000013751 14120250671 021760 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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_func func) { test_funcs.push_back(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, NULL); } return suite; } LogUnit::SuiteList& LogUnit::getAllSuites() { static LogUnit::SuiteList allSuites; return allSuites; } apache-log4cxx-0.12.1/src/test/cpp/patternlayouttest.cpp000644 001750 001750 00000035226 14120250671 024113 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(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(); log4cxx::spi::LoggerRepositoryPtr rep = root->getLoggerRepository().lock(); 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 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/temp")); const LogString PatternLayoutTest::FILTERED(LOG4CXX_STR("output/filtered")); LOGUNIT_TEST_SUITE_REGISTRATION(PatternLayoutTest); apache-log4cxx-0.12.1/src/test/cpp/customlogger/000755 001750 001750 00000000000 14122472744 022307 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/customlogger/xlogger.h000644 001750 001750 00000006203 14120250671 024117 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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(); virtual LoggerPtr makeNewLoggerInstance( log4cxx::helpers::Pool& pool, const LogString& name) const; }; 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-0.12.1/src/test/cpp/customlogger/CMakeLists.txt000644 001750 001750 00000000211 14120250671 025030 0ustar00robertrobert000000 000000 add_executable(xloggertestcase xloggertestcase.cpp xlogger.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} xloggertestcase PARENT_SCOPE) apache-log4cxx-0.12.1/src/test/cpp/customlogger/xlogger.cpp000644 001750 001750 00000005537 14120250671 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. */ #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) { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); if (rep->isDisabled(XLevel::LETHAL_INT)) { return; } if (XLevel::getLethal()->isGreaterOrEqual(this->getEffectiveLevel())) { forcedLog(XLevel::getLethal(), message, locationInfo); } } void XLogger::lethal(const LogString& message) { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); 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) { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); if (rep->isDisabled(XLevel::TRACE_INT)) { return; } if (XLevel::getTrace()->isGreaterOrEqual(this->getEffectiveLevel())) { forcedLog(XLevel::getTrace(), message, locationInfo); } } void XLogger::trace(const LogString& message) { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); 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-0.12.1/src/test/cpp/customlogger/xloggertestcase.cpp000644 001750 001750 00000004641 14120250671 026212 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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() { log4cxx::spi::LoggerRepositoryPtr rep = logger->getLoggerRepository().lock(); 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/temp"); 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-0.12.1/src/test/cpp/defaultinit/000755 001750 001750 00000000000 14122472744 022105 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/defaultinit/testcase3.cpp000644 001750 001750 00000003454 14120250671 024504 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/defaultinit/testcase2.cpp000644 001750 001750 00000003524 14120250671 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. */ #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-0.12.1/src/test/cpp/defaultinit/CMakeLists.txt000644 001750 001750 00000000251 14120250671 024632 0ustar00robertrobert000000 000000 add_executable(defaultinittestcase testcase1.cpp testcase2.cpp testcase3.cpp testcase4.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} defaultinittestcase PARENT_SCOPE) apache-log4cxx-0.12.1/src/test/cpp/defaultinit/testcase4.cpp000644 001750 001750 00000003616 14120250671 024505 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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-0.12.1/src/test/cpp/defaultinit/testcase1.cpp000644 001750 001750 00000002517 14120250671 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 "../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-0.12.1/src/test/cpp/CMakeLists.txt000644 001750 001750 00000011345 14120250671 022330 0ustar00robertrobert000000 000000 # 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 asyncappendertestcase consoleappendertestcase decodingtest encodingtest fileappendertest filetestcase hierarchytest hierarchythresholdtestcase jsonlayouttest l7dtestcase leveltestcase loggertestcase mdctestcase minimumtestcase ndctestcase patternlayouttest propertyconfiguratortest rollingfileappendertestcase streamtestcase multithreadtest ) 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(LOG4CXX_HAS_ODBC OR WIN32) 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(spi) add_subdirectory(varia) add_subdirectory(xml) # 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() endif( WIN32 ) foreach(testName IN LISTS ALL_LOG4CXX_TESTS) target_compile_definitions(${testName} PRIVATE ${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) add_test(NAME ${testName} COMMAND ${testName} -v WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/../resources ) set_tests_properties( ${testName} PROPERTIES TIMEOUT 120 ) if(WIN32) if(${testName} STREQUAL socketservertestcase) set_tests_properties(socketservertestcase PROPERTIES ENVIRONMENT "SOCKET_SERVER_PARAMETER_FILE=${START_SOCKET_SERVER_PARAMETER_FILE};PATH=${ESCAPED_PATH}" ) else() set_tests_properties(${testName} PROPERTIES ENVIRONMENT "TOTO=wonderful;key1=value1;key2=value2;PATH=${ESCAPED_PATH}" ) endif() else() if(${testName} STREQUAL socketservertestcase) set_tests_properties(socketservertestcase PROPERTIES ENVIRONMENT "SOCKET_SERVER_PARAMETER_FILE=${START_SOCKET_SERVER_PARAMETER_FILE}" ) else() set_tests_properties(${testName} PROPERTIES ENVIRONMENT "TOTO=wonderful;key1=value1;key2=value2" ) endif() endif() endforeach() apache-log4cxx-0.12.1/src/test/cpp/vectorappender.cpp000644 001750 001750 00000002302 14120250671 023306 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 (this->closed) { return; } this->closed = true; } apache-log4cxx-0.12.1/src/test/cpp/net/000755 001750 001750 00000000000 14122472744 020363 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/net/socketappendertestcase.cpp000644 001750 001750 00000002733 14120250671 025626 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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" #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_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::SocketAppender(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SocketAppenderTestCase); #endif apache-log4cxx-0.12.1/src/test/cpp/net/telnetappendertestcase.cpp000644 001750 001750 00000005224 14120250671 025627 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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 }; public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::TelnetAppender(); } void testActivateClose() { TelnetAppenderPtr appender(new TelnetAppender()); appender->setLayout(LayoutPtr(new TTCCLayout())); appender->setPort(TEST_PORT); Pool p; appender->activateOptions(p); appender->close(); } void testActivateSleepClose() { TelnetAppenderPtr appender(new TelnetAppender()); appender->setLayout(LayoutPtr(new TTCCLayout())); 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(LayoutPtr(new TTCCLayout())); 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-0.12.1/src/test/cpp/net/socketservertestcase.h000644 001750 001750 00000001701 14120250671 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. */ #ifndef _LOG4CXX_NET_SOCKETSERVER_TESTCASE_H #define _LOG4CXX_NET_SOCKETSERVER_TESTCASE_H #define PORT 12345 #endif //_LOG4CXX_NET_SOCKETSERVER_TESTCASE_H apache-log4cxx-0.12.1/src/test/cpp/net/socketservertestcase.cpp000644 001750 001750 00000032533 14120250671 025337 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 "socketservertestcase.h" #include "../util/compare.h" #include "../util/transformer.h" #include "../util/controlfilter.h" #include "../util/absolutedateandtimefilter.h" #include "../util/threadfilter.h" #include "../util/filenamefilter.h" #include #include #include #include #include #include "../testchar.h" #include "../logunit.h" #include //Define INT64_C for compilers that don't have it #if (!defined(INT64_C)) #define INT64_C(value) value ## LL #endif #if defined(WIN32) || defined(_WIN32) #include #endif using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; #define REGEX_STR(x) x // %5p %x [%t] %c %m%n // DEBUG T1 [thread] org.apache.log4j.net.SocketAppenderTestCase Message 1 #define PAT1 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T1 \\[0x[0-9A-F]*]\\ ") \ REGEX_STR(".* Message [0-9]\\{1,2\\}") // DEBUG T2 [thread] patternlayouttest.cpp(?) Message 1 #define PAT2 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T2 \\[0x[0-9A-F]*]\\ ") \ REGEX_STR(".*socketservertestcase.cpp\\([0-9]\\{1,4\\}\\) Message [0-9]\\{1,2\\}") // DEBUG T3 [thread] patternlayouttest.cpp(?) Message 1 #define PAT3 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T3 \\[0x[0-9A-F]*]\\ ") \ REGEX_STR(".*socketservertestcase.cpp\\([0-9]\\{1,4\\}\\) Message [0-9]\\{1,2\\}") // DEBUG some T4 MDC-TEST4 [thread] SocketAppenderTestCase - Message 1 // DEBUG some T4 MDC-TEST4 [thread] SocketAppenderTestCase - Message 1 #define PAT4 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some T4 MDC-TEST4 \\[0x[0-9A-F]*]\\") \ REGEX_STR(" (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") #define PAT5 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some5 T5 MDC-TEST5 \\[0x[0-9A-F]*]\\") \ REGEX_STR(" (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") #define PAT6 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some6 T6 client-test6 MDC-TEST6") \ REGEX_STR(" \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") #define PAT7 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some7 T7 client-test7 MDC-TEST7") \ REGEX_STR(" \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") // DEBUG some8 T8 shortSocketServer MDC-TEST7 [thread] SocketServerTestCase - Message 1 #define PAT8 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some8 T8 shortSocketServer") \ REGEX_STR(" MDC-TEST8 \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") /** * This test checks receipt of SocketAppender messages by the ShortSocketServer * class from log4j. That class must be started externally to this class * for this test to succeed. */ LOGUNIT_CLASS(SocketServerTestCase) { LOGUNIT_TEST_SUITE(SocketServerTestCase); 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(); SocketAppenderPtr socketAppender; LoggerPtr logger; LoggerPtr root; class LineNumberFilter : public Filter { public: LineNumberFilter() { patterns.push_back(PatternReplacement("cpp:[0-9]*", "cpp:XXX")); } }; public: void setUp() { logger = Logger::getLogger(LOG4CXX_STR("org.apache.log4j.net.SocketServerTestCase")); root = Logger::getRootLogger(); } void tearDown() { socketAppender = 0; log4cxx::spi::LoggerRepositoryPtr rep = root->getLoggerRepository().lock(); if (rep) { rep->resetConfiguration(); } logger = 0; root = 0; } /** We are testing NDC functionality across the wire. */ void test1() { SocketAppenderPtr socketAppender1 = SocketAppenderPtr( new SocketAppender(LOG4CXX_STR("localhost"), PORT)); root->addAppender(socketAppender1); common("test1", LOG4CXX_STR("T1"), LOG4CXX_STR("key1"), LOG4CXX_STR("MDC-TEST1")); delay(1); ControlFilter cf; cf << PAT1; ThreadFilter threadFilter; std::vector filters; filters.push_back(&cf); filters.push_back(&threadFilter); 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/socketServer.1"))); } void test2() { SocketAppenderPtr socketAppender1 = SocketAppenderPtr( new SocketAppender(LOG4CXX_STR("localhost"), PORT)); root->addAppender(socketAppender1); common("test2", LOG4CXX_STR("T2"), LOG4CXX_STR("key2"), LOG4CXX_STR("MDC-TEST2")); delay(1); ControlFilter cf; cf << PAT2; ThreadFilter threadFilter; LineNumberFilter lineNumberFilter; LogString thisFile; FilenameFilter filenameFilter(__FILE__, "socketservertestcase.cpp"); std::vector filters; filters.push_back(&filenameFilter); filters.push_back(&cf); filters.push_back(&threadFilter); filters.push_back(&lineNumberFilter); 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/socketServer.2"))); } void test3() { SocketAppenderPtr socketAppender1 = SocketAppenderPtr( new SocketAppender(LOG4CXX_STR("localhost"), PORT)); root->addAppender(socketAppender1); common("test3", LOG4CXX_STR("T3"), LOG4CXX_STR("key3"), LOG4CXX_STR("MDC-TEST3")); delay(1); ControlFilter cf; cf << PAT3; ThreadFilter threadFilter; LineNumberFilter lineNumberFilter; LogString thisFile; FilenameFilter filenameFilter(__FILE__, "socketservertestcase.cpp"); std::vector filters; filters.push_back(&filenameFilter); filters.push_back(&cf); filters.push_back(&threadFilter); filters.push_back(&lineNumberFilter); 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/socketServer.3"))); } void test4() { SocketAppenderPtr socketAppender1 = SocketAppenderPtr( new SocketAppender(LOG4CXX_STR("localhost"), PORT)); root->addAppender(socketAppender1); NDC::push(LOG4CXX_TEST_STR("some")); common("test4", LOG4CXX_STR("T4"), LOG4CXX_STR("key4"), LOG4CXX_STR("MDC-TEST4")); NDC::pop(); delay(1); ControlFilter cf; cf << PAT4; ThreadFilter threadFilter; std::vector filters; filters.push_back(&cf); filters.push_back(&threadFilter); 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/socketServer.4"))); } void test5() { SocketAppenderPtr socketAppender1 = SocketAppenderPtr( new SocketAppender(LOG4CXX_STR("localhost"), PORT)); AsyncAppenderPtr asyncAppender = AsyncAppenderPtr(new AsyncAppender()); root->addAppender(socketAppender1); root->addAppender(asyncAppender); NDC::push(LOG4CXX_TEST_STR("some5")); common("test5", LOG4CXX_STR("T5"), LOG4CXX_STR("key5"), LOG4CXX_STR("MDC-TEST5")); NDC::pop(); delay(2); ControlFilter cf; cf << PAT5; ThreadFilter threadFilter; std::vector filters; filters.push_back(&cf); filters.push_back(&threadFilter); 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/socketServer.5"))); } void test6() { SocketAppenderPtr socketAppender1 = SocketAppenderPtr( new SocketAppender(LOG4CXX_STR("localhost"), PORT)); AsyncAppenderPtr asyncAppender = AsyncAppenderPtr(new AsyncAppender()); root->addAppender(socketAppender1); root->addAppender(asyncAppender); NDC::push(LOG4CXX_TEST_STR("some6")); MDC::put(LOG4CXX_TEST_STR("hostID"), LOG4CXX_TEST_STR("client-test6")); common("test6", LOG4CXX_STR("T6"), LOG4CXX_STR("key6"), LOG4CXX_STR("MDC-TEST6")); NDC::pop(); MDC::remove(LOG4CXX_TEST_STR("hostID")); delay(2); ControlFilter cf; cf << PAT6; ThreadFilter threadFilter; std::vector filters; filters.push_back(&cf); filters.push_back(&threadFilter); 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/socketServer.6"))); } void test7() { SocketAppenderPtr socketAppender1 = SocketAppenderPtr( new SocketAppender(LOG4CXX_STR("localhost"), PORT)); AsyncAppenderPtr asyncAppender = AsyncAppenderPtr(new AsyncAppender()); root->addAppender(socketAppender1); root->addAppender(asyncAppender); NDC::push(LOG4CXX_TEST_STR("some7")); MDC::put(LOG4CXX_TEST_STR("hostID"), LOG4CXX_TEST_STR("client-test7")); common("test7", LOG4CXX_STR("T7"), LOG4CXX_STR("key7"), LOG4CXX_STR("MDC-TEST7")); NDC::pop(); MDC::remove(LOG4CXX_TEST_STR("hostID")); delay(2); ControlFilter cf; cf << PAT7; ThreadFilter threadFilter; std::vector filters; filters.push_back(&cf); filters.push_back(&threadFilter); 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/socketServer.7"))); } void test8() { SocketAppenderPtr socketAppender1 = SocketAppenderPtr( new SocketAppender(LOG4CXX_STR("localhost"), PORT)); root->addAppender(socketAppender1); NDC::push(LOG4CXX_TEST_STR("some8")); common("test8", LOG4CXX_STR("T8"), LOG4CXX_STR("key8"), LOG4CXX_STR("MDC-TEST8")); NDC::pop(); delay(2); ControlFilter cf; cf << PAT8; ThreadFilter threadFilter; std::vector filters; filters.push_back(&cf); filters.push_back(&threadFilter); 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/socketServer.8"))); } void common(const std::string & testName, const LogString & dc, const LogString & key, const LogString & val) { int i = -1; NDC::push(dc); MDC::put(key, val); logger->setLevel(Level::getDebug()); root->setLevel(Level::getDebug()); LOG4CXX_TRACE(logger, "Message " << i); i++; logger->setLevel(Level::getTrace()); root->setLevel(Level::getTrace()); LOG4CXX_TRACE(logger, "Message " << ++i); LOG4CXX_TRACE(root, "Message " << ++i); LOG4CXX_DEBUG(logger, "Message " << ++i); LOG4CXX_DEBUG(root, "Message " << ++i); LOG4CXX_INFO(logger, "Message " << ++i); LOG4CXX_WARN(logger, "Message " << ++i); LOG4CXX_FATAL(logger, "Message " << ++i); //5 std::string exceptionMsg("\njava.lang.Exception: Just testing\n" "\tat org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX)\n" "\tat org.apache.log4j.net.SocketServerTestCase."); exceptionMsg.append(testName); exceptionMsg.append("(SocketServerTestCase.java:XXX)\n" "\tat junit.framework.TestCase.runTest(TestCase.java:XXX)\n" "\tat junit.framework.TestCase.runBare(TestCase.java:XXX)\n" "\tat junit.framework.TestResult$1.protect(TestResult.java:XXX)\n" "\tat junit.framework.TestResult.runProtected(TestResult.java:XXX)\n" "\tat junit.framework.TestResult.run(TestResult.java:XXX)\n" "\tat junit.framework.TestCase.run(TestCase.java:XXX)\n" "\tat junit.framework.TestSuite.runTest(TestSuite.java:XXX)\n" "\tat junit.framework.TestSuite.run(TestSuite.java:XXX)"); LOG4CXX_DEBUG(logger, "Message " << ++i << exceptionMsg); LOG4CXX_ERROR(root, "Message " << ++i << exceptionMsg); NDC::pop(); MDC::remove(key); } void delay(int secs) { apr_sleep(APR_USEC_PER_SEC * secs); } private: static const File TEMP; static const File FILTERED; }; const File SocketServerTestCase::TEMP("output/temp"); const File SocketServerTestCase::FILTERED("output/filtered"); LOGUNIT_TEST_SUITE_REGISTRATION(SocketServerTestCase) apache-log4cxx-0.12.1/src/test/cpp/net/smtpappendertestcase.cpp000644 001750 001750 00000006716 14120250671 025326 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #if LOG4CXX_HAVE_SMTP #include #include "../appenderskeletontestcase.h" #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; using namespace log4cxx::xml; using namespace log4cxx::spi; namespace log4cxx { namespace net { class MockTriggeringEventEvaluator : public virtual spi::TriggeringEventEvaluator, public virtual helpers::ObjectImpl { public: DECLARE_LOG4CXX_OBJECT(MockTriggeringEventEvaluator) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(MockTriggeringEventEvaluator) LOG4CXX_CAST_ENTRY(spi::TriggeringEventEvaluator) END_LOG4CXX_CAST_MAP() MockTriggeringEventEvaluator() { } virtual bool isTriggeringEvent(const spi::LoggingEventPtr& event) { return true; } private: MockTriggeringEventEvaluator(const MockTriggeringEventEvaluator&); MockTriggeringEventEvaluator& operator=(const MockTriggeringEventEvaluator&); }; } } 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_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() { DOMConfigurator::configure("input/xml/smtpAppender1.xml"); SMTPAppenderPtr appender(Logger::getRootLogger()->getAppender(LOG4CXX_STR("A1"))); TriggeringEventEvaluatorPtr evaluator(appender->getEvaluator()); LOGUNIT_ASSERT_EQUAL(true, evaluator->instanceof(MockTriggeringEventEvaluator::getStaticClass())); } void testInvalid() { SMTPAppenderPtr appender(new SMTPAppender()); appender->setSMTPHost(LOG4CXX_STR("smtp.invalid")); appender->setTo(LOG4CXX_STR("you@example.invalid")); appender->setFrom(LOG4CXX_STR("me@example.invalid")); appender->setLayout(new TTCCLayout()); Pool p; appender->activateOptions(p); LoggerPtr root(Logger::getRootLogger()); root->addAppender(appender); LOG4CXX_INFO(root, "Hello, World.") LOG4CXX_ERROR(root, "Sending Message") } }; LOGUNIT_TEST_SUITE_REGISTRATION(SMTPAppenderTestCase); #endif apache-log4cxx-0.12.1/src/test/cpp/net/xmlsocketappendertestcase.cpp000644 001750 001750 00000002762 14120250671 026351 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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" #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_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::XMLSocketAppender(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(XMLSocketAppenderTestCase); #endif apache-log4cxx-0.12.1/src/test/cpp/net/socketserverstarter.cpp000644 001750 001750 00000011520 14120250671 025201 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/net/syslogappendertestcase.cpp000644 001750 001750 00000002733 14120250671 025656 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/test/cpp/net/CMakeLists.txt000644 001750 001750 00000001244 14120250671 023113 0ustar00robertrobert000000 000000 # Tests defined in this directory set(NET_TESTS socketappendertestcase sockethubappendertestcase syslogappendertestcase telnetappendertestcase xmlsocketappendertestcase ) if(HAS_LIBESMPT) list(APPEND NET_TESTS smtpappendertestcase) endif(HAS_LIBESMPT) foreach(fileName IN LISTS NET_TESTS) add_executable(${fileName} "${fileName}.cpp") endforeach() if(Java_Development_FOUND) add_executable(socketservertestcase socketserverstarter.cpp socketservertestcase.cpp) add_dependencies(socketservertestcase test-classes) list(APPEND NET_TESTS socketservertestcase) endif() set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} ${NET_TESTS} PARENT_SCOPE) apache-log4cxx-0.12.1/src/test/cpp/net/sockethubappendertestcase.cpp000644 001750 001750 00000004564 14120250671 026331 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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" #include using namespace log4cxx; using namespace log4cxx::net; using namespace log4cxx::helpers; #if APR_HAS_THREADS /** Unit tests of log4cxx::SocketHubAppender */ class SocketHubAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(SocketHubAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(testActivateClose); LOGUNIT_TEST(testActivateSleepClose); LOGUNIT_TEST(testActivateWriteClose); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::SocketHubAppender(); } void testActivateClose() { SocketHubAppenderPtr hubAppender(new SocketHubAppender()); Pool p; hubAppender->activateOptions(p); hubAppender->close(); } void testActivateSleepClose() { SocketHubAppenderPtr hubAppender(new SocketHubAppender()); Pool p; hubAppender->activateOptions(p); std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) ); hubAppender->close(); } void testActivateWriteClose() { SocketHubAppenderPtr hubAppender(new SocketHubAppender()); Pool p; hubAppender->activateOptions(p); LoggerPtr root(Logger::getRootLogger()); root->addAppender(hubAppender); for (int i = 0; i < 50; i++) { LOG4CXX_INFO(root, "Hello, World " << i); } hubAppender->close(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SocketHubAppenderTestCase); #endif apache-log4cxx-0.12.1/src/test/cpp/fileappendertestcase.cpp000644 001750 001750 00000007353 14120250671 024472 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/appenderskeletontestcase.h000644 001750 001750 00000002162 14120250671 025035 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/filter/000755 001750 001750 00000000000 14122472744 021062 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/filter/loggermatchfiltertest.cpp000644 001750 001750 00000006512 14120250671 026163 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/filter/levelrangefiltertest.cpp000644 001750 001750 00000011165 14120250671 026013 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/filter/levelmatchfiltertest.cpp000644 001750 001750 00000007740 14120250671 026017 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/filter/CMakeLists.txt000644 001750 001750 00000000436 14120250671 023614 0ustar00robertrobert000000 000000 add_executable(filtertests andfiltertest.cpp denyallfiltertest.cpp levelmatchfiltertest.cpp levelrangefiltertest.cpp loggermatchfiltertest.cpp mapfiltertest.cpp stringmatchfiltertest.cpp ) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} filtertests PARENT_SCOPE) apache-log4cxx-0.12.1/src/test/cpp/filter/mapfiltertest.cpp000644 001750 001750 00000012053 14120250671 024441 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/filter/stringmatchfiltertest.cpp000644 001750 001750 00000010065 14120250671 026210 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/filter/denyallfiltertest.cpp000644 001750 001750 00000003313 14120250671 025313 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/filter/andfiltertest.cpp000644 001750 001750 00000012706 14120250671 024433 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/db/000755 001750 001750 00000000000 14122472744 020162 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/db/CMakeLists.txt000644 001750 001750 00000000716 14120250671 022715 0ustar00robertrobert000000 000000 add_executable(odbcappendertestcase odbcappendertestcase.cpp) target_compile_definitions(odbcappendertestcase PRIVATE ${LOG4CXX_COMPILE_DEFINITIONS} ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS} ) target_include_directories(odbcappendertestcase PRIVATE ${CMAKE_CURRENT_LIST_DIR} $) target_link_libraries(odbcappendertestcase log4cxx testingFramework testingUtilities ${APR_LIBRARIES} ${APR_SYSTEM_LIBS}) apache-log4cxx-0.12.1/src/test/cpp/db/odbcappendertestcase.cpp000644 001750 001750 00000003042 14120250671 025036 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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" #include "../logunit.h" #define LOG4CXX_TEST 1 #include #ifdef LOG4CXX_HAVE_ODBC using namespace log4cxx; using namespace log4cxx::helpers; /** 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_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::db::ODBCAppender(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(ODBCAppenderTestCase); #endif apache-log4cxx-0.12.1/src/test/cpp/propertyconfiguratortest.cpp000644 001750 001750 00000007303 14120250671 025502 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/streamtestcase.cpp000644 001750 001750 00000051326 14120250671 023326 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #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-0.12.1/src/test/cpp/xml/000755 001750 001750 00000000000 14122472744 020375 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/xml/xmllayouttest.cpp000644 001750 001750 00000026642 14120250671 024040 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/xml/xlevel.cpp000644 001750 001750 00000004143 14120250671 022371 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/xml/xmllayouttestcase.cpp000644 001750 001750 00000022706 14120250671 024671 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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() { log4cxx::spi::LoggerRepositoryPtr rep = logger->getLoggerRepository().lock(); 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-0.12.1/src/test/cpp/xml/customleveltestcase.cpp000644 001750 001750 00000006355 14120250671 025177 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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-0.12.1/src/test/cpp/xml/CMakeLists.txt000644 001750 001750 00000000340 14122472113 023120 0ustar00robertrobert000000 000000 add_executable(xmltests domtestcase xmllayouttest xmllayouttestcase ) target_link_libraries(xmltests PRIVATE ${APR_UTIL_LIBRARIES} EXPAT::EXPAT) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} xmltests PARENT_SCOPE) apache-log4cxx-0.12.1/src/test/cpp/xml/xlevel.h000644 001750 001750 00000003616 14120250671 022042 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/xml/domtestcase.cpp000644 001750 001750 00000015705 14120250671 023413 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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() { log4cxx::spi::LoggerRepositoryPtr rep = root->getLoggerRepository().lock(); 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-0.12.1/src/test/cpp/rolling/000755 001750 001750 00000000000 14122472744 021243 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/rolling/filterbasedrollingtest.cpp000644 001750 001750 00000010474 14120250671 026517 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/rolling/obsoletedailyrollingfileappendertest.cpp000644 001750 001750 00000007746 14120250671 031461 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::xml; using namespace log4cxx::filter; using namespace log4cxx::helpers; /** * Tests the emulation of org.apache.log4j.DailyRollingFileAppender * * * */ LOGUNIT_CLASS(ObsoleteDailyRollingFileAppenderTest) { LOGUNIT_TEST_SUITE(ObsoleteDailyRollingFileAppenderTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST_SUITE_END(); public: void tearDown() { LogManager::shutdown(); } /** * Test basic rolling functionality. */ void test1() { PropertyConfigurator::configure(File("input/rolling/obsoleteDRFA1.properties")); int preCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test1.log.")); LoggerPtr logger(Logger::getLogger("org.apache.log4j.ObsoleteDailyRollingFileAppenderTest")); char msg[11]; strcpy(msg, "Hello---??"); 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 basic rolling functionality. * @deprecated Class under test is deprecated. */ void test2() { PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%m%n"))); log4cxx::DailyRollingFileAppenderPtr rfa(new log4cxx::DailyRollingFileAppender()); 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("org.apache.log4j.ObsoleteDailyRollingAppenderTest")); int preCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test2.log.")); char msg[11]; strcpy(msg, "Hello---??"); 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); } 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(ObsoleteDailyRollingFileAppenderTest); apache-log4cxx-0.12.1/src/test/cpp/rolling/CMakeLists.txt000644 001750 001750 00000000665 14120250671 024001 0ustar00robertrobert000000 000000 # Tests defined in this directory set(ROLLING_TESTS filenamepatterntestcase filterbasedrollingtest manualrollingtest obsoletedailyrollingfileappendertest obsoleterollingfileappendertest sizebasedrollingtest timebasedrollingtest ) 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-0.12.1/src/test/cpp/rolling/manualrollingtest.cpp000644 001750 001750 00000023346 14120250671 025512 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; /** * 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_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->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"))); } } }; LOGUNIT_TEST_SUITE_REGISTRATION(ManualRollingTest); apache-log4cxx-0.12.1/src/test/cpp/rolling/timebasedrollingtest.cpp000644 001750 001750 00000051752 14120250671 026174 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 "../util/compare.h" #include "../logunit.h" #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") 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_SUITE_END(); private: static LoggerPtr logger; /** * Currently running test. *

* Number of currently running test, used e.g. for some generic code in {@link setUp()}. *

*/ size_t num_test; /** * 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] fileNames * param[in,opt] withCompression * param[in,opt] startInFuture */ template void buildTsFileNames( Pool & pool, const logchar * prefix, LogString (&fileNames)[N], bool withCompression = false, bool startInFuture = false) { SimpleDateFormat sdf(DATE_PATTERN_STR); apr_time_t now(apr_time_now()); LogString ext(withCompression ? LOG4CXX_STR(".gz") : LOG4CXX_STR("")); now += startInFuture ? APR_USEC_PER_SEC : 0; for (size_t i = 0; i < N; ++i) { fileNames[i].assign(LogString(LOG4CXX_STR("output/")) + prefix); sdf.format(fileNames[i], now, pool); fileNames[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__, \ 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); apr_sleep(APR_USEC_PER_SEC * waitFactor); } #undef LOG4CXX_LOCATION #define LOG4CXX_LOCATION ::log4cxx::spi::LocationInfo( \ __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] fileName * @param[in] witnessIdx * @param[in] srcLine */ void compareWitness( Pool & pool, const logchar * prefix, const LogString & fileName, size_t witnessIdx, size_t srcLine) { LogString witness(LOG4CXX_STR("witness/rolling/tbr-")); witness.append(prefix); StringHelper::toString(witnessIdx, pool, witness); LOGUNIT_ASSERT_SRCL(Compare::compare(fileName, 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] fileNames * @param[in] srcLine */ template void compareWitnesses( Pool & pool, const logchar * prefix, LogString (&fileNames)[N], size_t srcLine) { for (int i = 0; i < N; ++i) { this->compareWitness(pool, prefix, fileNames[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 schould have the same name in all * compilers and is easily to add for the caller. *

* @param[in,out] pool * @param[in] prefix * @param[in] fileNames * @param[in] srcLine */ template void checkFilesExist( Pool & pool, const logchar * prefix, LogString (&fileNames)[N], size_t srcLine) { for (int i = 0; i < N - 1; ++i) { LOGUNIT_ASSERT_EQUAL_SRCL(true, File(fileNames[0]).exists(pool), srcLine); } this->compareWitness(pool, prefix, fileNames[N - 1], N - 1, 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(size_t millis = 100) { apr_time_t now = apr_time_now(); apr_time_t next = ((now / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC + millis * 1000L; apr_sleep(next - now); } /** * 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(size_t millis = 100) { std::cout << "Waiting until next second and " << millis << " millis."; delayUntilNextSecond(millis); std::cout << "Done waiting." << std::endl; } /** * Delete generic log files. *

* 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 their internal names. Such a date may * be from the arbitrary past, but ost of the test assumes operations like rollovers within few * seconds around "new". Thos assumptions will fail for older existing files. So this method can * be called during {@link setUp()} of an test to clear such generically named files for each * test. We currently only care about {@code output/testxy.log}. *

* @param[in] num_test */ void deleteGenericLogFilePerTest(size_t num_test) { Pool pool; LogString path(LOG4CXX_STR("output/test")); StringHelper::toString(num_test, pool, path); path.append(LOG4CXX_STR(".log")); File(path).deleteFile(pool); } /** * Setup for internal test call. *

* This method has a similar intention like {@link setUp()}, only that it focusses on internal * calls of the tests, where we don't need to create some loggers and such, but may need to * delete some files etc. to make tests work. *

* @param[in] num_test */ void internalSetUp(size_t num_test) { this->deleteGenericLogFilePerTest(num_test); } /** * Counterpart for {@like internalSetUp(size_t)}. *

* Counterpart for {@like internalSetUp(size_t)}. *

*/ void internalTearDown() { // Nothing to do currently. } public: /** * Extract number of current test. *

* {@code setUp()} needs the number of the current runnign test for some generic work and this * is the only place where we can extract and save it in the instance. *

*/ void setCase(abts_case * tc) { LogUnit::TestFixture::setCase(tc); this->num_test = tc->suite->num_test; } void setUp() { LoggerPtr root(Logger::getRootLogger()); root->addAppender( ConsoleAppenderPtr(new ConsoleAppender( PatternLayoutPtr(new PatternLayout( LOG4CXX_STR("%d{ABSOLUTE} [%t] %level %c{2}#%M:%L - %m%n")))))); this->internalSetUp(this->num_test); } void tearDown() { this->internalTearDown(); LogManager::shutdown(); } /** * Test rolling without compression, activeFileName left blank, no stop/start */ void test1() { Pool pool; const size_t nrOfFileNames = 4; LogString fileNames[nrOfFileNames]; PatternLayoutPtr layout( new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa( new RollingFileAppender()); rfa->setLayout(layout); TimeBasedRollingPolicyPtr tbrp(new TimeBasedRollingPolicy()); tbrp->setFileNamePattern(LOG4CXX_STR("output/test1-%d{" DATE_PATTERN "}")); tbrp->activateOptions(pool); rfa->setRollingPolicy(tbrp); rfa->activateOptions(pool); logger->addAppender(rfa); this->buildTsFileNames(pool, LOG4CXX_STR("test1-"), fileNames); this->delayUntilNextSecondWithMsg(); this->logMsgAndSleep( pool, nrOfFileNames + 1, __LOG4CXX_FUNC__, __LINE__); this->compareWitnesses( pool, LOG4CXX_STR("test1."), fileNames, __LINE__); } /** * No compression, with stop/restart, activeFileName left blank */ void test2() { Pool pool; const size_t nrOfFileNames = 4; LogString fileNames[nrOfFileNames]; PatternLayoutPtr layout1(new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa1( new RollingFileAppender()); rfa1->setLayout(layout1); TimeBasedRollingPolicyPtr tbrp1(new TimeBasedRollingPolicy()); tbrp1->setFileNamePattern(LOG4CXX_STR("output/test2-%d{" DATE_PATTERN "}")); tbrp1->activateOptions(pool); rfa1->setRollingPolicy(tbrp1); rfa1->activateOptions(pool); logger->addAppender(rfa1); this->buildTsFileNames(pool, LOG4CXX_STR("test2-"), fileNames); 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("output/test2-%d{" DATE_PATTERN "}")); tbrp2->activateOptions(pool); rfa2->setRollingPolicy(tbrp2); rfa2->activateOptions(pool); logger->addAppender(rfa2); this->logMsgAndSleep( pool, 2, __LOG4CXX_FUNC__, __LINE__, 3); this->compareWitnesses( pool, LOG4CXX_STR("test2."), fileNames, __LINE__); } /** * With compression, activeFileName left blank, no stop/restart */ void test3() { Pool pool; const size_t nrOfFileNames = 4; LogString fileNames[nrOfFileNames]; 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("output/test3-%d{" DATE_PATTERN "}.gz"))); tbrp->activateOptions(pool); rfa->setRollingPolicy(tbrp); rfa->activateOptions(pool); logger->addAppender(rfa); this->buildTsFileNames(pool, LOG4CXX_STR("test3-"), fileNames, true); fileNames[3].resize(fileNames[3].size() - 3); this->delayUntilNextSecondWithMsg(); this->logMsgAndSleep( pool, nrOfFileNames + 1, __LOG4CXX_FUNC__, __LINE__); this->checkFilesExist( pool, LOG4CXX_STR("test3."), fileNames, __LINE__); } /** * Without compression, activeFileName set, with stop/restart */ void test4() { Pool pool; const size_t nrOfFileNames = 4; LogString fileNames[nrOfFileNames]; PatternLayoutPtr layout1(new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa1( new RollingFileAppender()); rfa1->setLayout(layout1); TimeBasedRollingPolicyPtr tbrp1 = TimeBasedRollingPolicyPtr(new TimeBasedRollingPolicy()); rfa1->setFile(LOG4CXX_STR("output/test4.log")); tbrp1->setFileNamePattern(LOG4CXX_STR("output/test4-%d{" DATE_PATTERN "}")); tbrp1->activateOptions(pool); rfa1->setRollingPolicy(tbrp1); rfa1->activateOptions(pool); logger->addAppender(rfa1); this->buildTsFileNames(pool, LOG4CXX_STR("test4-"), fileNames); fileNames[3].assign(rfa1->getFile()); 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("output/test4-%d{" DATE_PATTERN "}")); rfa2->setFile(fileNames[3]); tbrp2->activateOptions(pool); rfa2->setRollingPolicy(tbrp2); rfa2->activateOptions(pool); logger->addAppender(rfa2); this->logMsgAndSleep( pool, 2, __LOG4CXX_FUNC__, __LINE__, 3); this->compareWitnesses( pool, LOG4CXX_STR("test4."), fileNames, __LINE__); } /** * No compression, activeFileName set, without stop/restart */ void test5() { Pool pool; const size_t nrOfFileNames = 4; LogString fileNames[nrOfFileNames]; PatternLayoutPtr layout( new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa( new RollingFileAppender()); rfa->setLayout(layout); TimeBasedRollingPolicyPtr tbrp = TimeBasedRollingPolicyPtr(new TimeBasedRollingPolicy()); tbrp->setFileNamePattern(LOG4CXX_STR("output/test5-%d{" DATE_PATTERN "}")); rfa->setFile(LOG4CXX_STR("output/test5.log")); tbrp->activateOptions(pool); rfa->setRollingPolicy(tbrp); rfa->activateOptions(pool); logger->addAppender(rfa); this->buildTsFileNames(pool, LOG4CXX_STR("test5-"), fileNames); fileNames[3].assign(rfa->getFile()); this->delayUntilNextSecondWithMsg(); this->logMsgAndSleep( pool, nrOfFileNames + 1, __LOG4CXX_FUNC__, __LINE__); this->compareWitnesses( pool, LOG4CXX_STR("test5."), fileNames, __LINE__); } /** * With compression, activeFileName set, no stop/restart, */ void test6() { Pool pool; const size_t nrOfFileNames = 4; LogString fileNames[nrOfFileNames]; 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("output/test6-%d{" DATE_PATTERN "}.gz"))); rfa->setFile(LOG4CXX_STR("output/test6.log")); tbrp->activateOptions(pool); rfa->setRollingPolicy(tbrp); rfa->activateOptions(pool); logger->addAppender(rfa); this->buildTsFileNames(pool, LOG4CXX_STR("test6-"), fileNames, true); fileNames[3].assign(rfa->getFile()); this->delayUntilNextSecondWithMsg(); this->logMsgAndSleep( pool, nrOfFileNames + 1, __LOG4CXX_FUNC__, __LINE__); this->checkFilesExist( pool, LOG4CXX_STR("test6."), fileNames, __LINE__); } /** * Repeat some test with generic file name.s *

* 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->internalSetUp(numTest); (this->*test)(); this->internalTearDown(); } } }; LoggerPtr TimeBasedRollingTest::logger(Logger::getLogger("org.apache.log4j.TimeBasedRollingTest")); LOGUNIT_TEST_SUITE_REGISTRATION(TimeBasedRollingTest); apache-log4cxx-0.12.1/src/test/cpp/rolling/filenamepatterntestcase.cpp000644 001750 001750 00000013104 14120250671 026647 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/rolling/obsoleterollingfileappendertest.cpp000644 001750 001750 00000010673 14120250671 030427 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 using namespace log4cxx; using namespace log4cxx::xml; using namespace log4cxx::filter; using namespace log4cxx::helpers; /** * Tests the emulation of org.apache.log4j.RollingFileAppender * * * */ LOGUNIT_CLASS(ObsoleteRollingFileAppenderTest) { LOGUNIT_TEST_SUITE(ObsoleteRollingFileAppenderTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(testIsOptionHandler); LOGUNIT_TEST(testClassForName); LOGUNIT_TEST_SUITE_END(); public: void tearDown() { LogManager::shutdown(); } /** * Test basic rolling functionality. */ void test1() { PropertyConfigurator::configure(File("input/rolling/obsoleteRFA1.properties")); char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', '?', 0}; LoggerPtr 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] = (char) ('0' + i); LOG4CXX_DEBUG(logger, msg); } else if (i < 100) { msg[7] = (char) ('0' + i / 10); msg[8] = (char) ('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. * @deprecated Class under test is deprecated. */ void test2() { PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%m\n"))); log4cxx::RollingFileAppenderPtr rfa( new log4cxx::RollingFileAppender()); 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); LoggerPtr root(Logger::getRootLogger()); root->addAppender(rfa); char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', '?', 0}; LoggerPtr 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] = (char) ('0' + i); LOG4CXX_DEBUG(logger, msg); } else if (i < 100) { msg[7] = (char) ('0' + i / 10); msg[8] = (char) ('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)); } /** * Tests if class is declared to support the OptionHandler interface. * See LOGCXX-136. */ void testIsOptionHandler() { RollingFileAppenderPtr rfa(new RollingFileAppender()); LOGUNIT_ASSERT_EQUAL(true, rfa->instanceof(log4cxx::spi::OptionHandler::getStaticClass())); } void testClassForName() { LogString className(LOG4CXX_STR("org.apache.log4j.RollingFileAppender")); const Class& myclass = Class::forName(className); LOGUNIT_ASSERT_EQUAL(className, LogString(myclass.getName())); } }; LOGUNIT_TEST_SUITE_REGISTRATION(ObsoleteRollingFileAppenderTest); apache-log4cxx-0.12.1/src/test/cpp/rolling/sizebasedrollingtest.cpp000644 001750 001750 00000030053 14120250671 026177 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; /** * * 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() { PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%d %level %c -%m%n"))); AppenderPtr ca(new ConsoleAppender(layout)); ca->setName(LOG4CXX_STR("CONSOLE")); root = Logger::getRootLogger(); root->addAppender(ca); 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()); 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()); 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-0.12.1/src/test/cpp/minimumtestcase.cpp000644 001750 001750 00000015354 14120250671 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 "logunit.h" #include #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; #define TTCC_PAT \ ABSOLUTE_DATE_AND_TIME_PAT \ " \\[0x[0-9A-F]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]\\{1,2\\}" #define TTCC2_PAT \ ABSOLUTE_DATE_AND_TIME_PAT \ " \\[0x[0-9A-F]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - " \ "Messages should bear numbers 0 through 23\\." LOGUNIT_CLASS(MinimumTestCase) { LOGUNIT_TEST_SUITE(MinimumTestCase); LOGUNIT_TEST(simple); LOGUNIT_TEST(ttcc); LOGUNIT_TEST_SUITE_END(); public: void setUp() { root = Logger::getRootLogger(); root->removeAllAppenders(); } void tearDown() { log4cxx::spi::LoggerRepositoryPtr rep = root->getLoggerRepository().lock(); 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"))); } void ttcc() { LayoutPtr layout = TTCCLayoutPtr( new TTCCLayout(LOG4CXX_STR("DATE"))); AppenderPtr appender = FileAppenderPtr(new FileAppender(layout, LOG4CXX_STR("output/ttcc"), false)); root->addAppender(appender); common(); ControlFilter filter1; filter1 << TTCC_PAT << TTCC2_PAT; AbsoluteDateAndTimeFilter filter2; ThreadFilter filter3; std::vector filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { const File output("output/ttcc"); Transformer::transform(output, FILTERED, filters); } catch (std::exception& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } const File witness("witness/ttcc"); LOGUNIT_ASSERT(Compare::compare(FILTERED, witness)); } 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/filtered"); LOGUNIT_TEST_SUITE_REGISTRATION(MinimumTestCase); apache-log4cxx-0.12.1/src/test/cpp/testchar.h000644 001750 001750 00000002227 14120250671 021555 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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-0.12.1/src/test/cpp/jsonlayouttest.cpp000644 001750 001750 00000030441 14120250671 023401 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 /** * 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", "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", "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", "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", "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-0.12.1/src/test/cpp/multithreadtest.cpp000644 001750 001750 00000005724 14120250671 023522 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 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. */ 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::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() { // root->getLoggerRepository()->resetConfiguration(); } 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-0.12.1/src/test/cpp/writerappendertestcase.cpp000644 001750 001750 00000002027 14120250671 025060 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/varia/000755 001750 001750 00000000000 14122472744 020677 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/varia/levelmatchfiltertestcase.cpp000644 001750 001750 00000011752 14120250671 026466 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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() { log4cxx::spi::LoggerRepositoryPtr rep = root->getLoggerRepository().lock(); 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-0.12.1/src/test/cpp/varia/errorhandlertestcase.cpp000644 001750 001750 00000006420 14120250671 025617 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 "../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_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); logger = Logger::getLogger("test"); } void tearDown() { log4cxx::spi::LoggerRepositoryPtr rep = logger->getLoggerRepository().lock(); 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/temp", "output/filtered", filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare("output/filtered", "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-0.12.1/src/test/cpp/varia/CMakeLists.txt000644 001750 001750 00000000467 14120250671 023435 0ustar00robertrobert000000 000000 # 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-0.12.1/src/test/cpp/varia/levelrangefiltertestcase.cpp000644 001750 001750 00000016141 14120250671 026463 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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() { log4cxx::spi::LoggerRepositoryPtr rep = root->getLoggerRepository().lock(); 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-0.12.1/src/test/cpp/rollingfileappendertestcase.cpp000644 001750 001750 00000002712 14120250671 026053 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/test/cpp/filetestcase.cpp000644 001750 001750 00000012376 14120250671 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 "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-0.12.1/src/test/cpp/asyncappendertestcase.cpp000644 001750 001750 00000022046 14120250671 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 "logunit.h" #include #include #include #include "vectorappender.h" #include #include "appenderskeletontestcase.h" #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&) { throw NullPointerException(LOG4CXX_STR("Intentional NullPointerException")); } void close() { } bool requiresLayout() const { 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) { 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); // // TODO: test fails on Linux. //LOGUNIT_TEST(testBadAppender); LOGUNIT_TEST(testLocationInfoTrue); LOGUNIT_TEST(testConfiguration); LOGUNIT_TEST_SUITE_END(); 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()); } /** * Tests that a bad appender will switch async back to sync. */ void testBadAppender() { AppenderPtr nullPointerAppender = AppenderPtr(new NullPointerAppender()); AsyncAppenderPtr asyncAppender = AsyncAppenderPtr(new AsyncAppender()); asyncAppender->addAppender(nullPointerAppender); asyncAppender->setBufferSize(5); Pool p; asyncAppender->activateOptions(p); LoggerPtr root = Logger::getRootLogger(); root->addAppender(asyncAppender); LOG4CXX_INFO(root, "Message"); std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); try { LOG4CXX_INFO(root, "Message"); LOGUNIT_FAIL("Should have thrown exception"); } catch (NullPointerException&) { } } /** * Tests non-blocking behavior. */ void testLocationInfoTrue() { BlockableVectorAppenderPtr blockableAppender = BlockableVectorAppenderPtr(new BlockableVectorAppender()); AsyncAppenderPtr async = AsyncAppenderPtr(new AsyncAppender()); 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-0.12.1/src/test/cpp/abts_tests.h000644 001750 001750 00000001635 14120250671 022115 0ustar00robertrobert000000 000000 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/test/cpp/pattern/000755 001750 001750 00000000000 14122472744 021252 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/cpp/pattern/num343patternconverter.h000644 001750 001750 00000002436 14120250671 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. */ #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; }; } } apache-log4cxx-0.12.1/src/test/cpp/pattern/patternparsertestcase.cpp000644 001750 001750 00000016573 14120250671 026407 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 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_SUITE_END(); LoggingEventPtr event; public: void setUp() { 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("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); } }; // // See bug LOGCXX-204 // #if !defined(_MSC_VER) || _MSC_VER > 1200 LOGUNIT_TEST_SUITE_REGISTRATION(PatternParserTestCase); #endif apache-log4cxx-0.12.1/src/test/cpp/pattern/CMakeLists.txt000644 001750 001750 00000000252 14120250671 024000 0ustar00robertrobert000000 000000 add_executable(patternparsertestcase patternparsertestcase.cpp num343patternconverter.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} patternparsertestcase PARENT_SCOPE) apache-log4cxx-0.12.1/src/test/cpp/pattern/num343patternconverter.cpp000644 001750 001750 00000002760 14120250671 026331 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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-0.12.1/src/test/cpp/fileappendertest.cpp000644 001750 001750 00000004765 14120250671 023642 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/vectorappender.h000644 001750 001750 00000003234 14120250671 022760 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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 { /** 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); const std::vector& getVector() const { return vector; } void close(); bool isClosed() const { return closed; } bool requiresLayout() const { return false; } }; typedef std::shared_ptr VectorAppenderPtr; } apache-log4cxx-0.12.1/src/test/cpp/writerappendertestcase.h000644 001750 001750 00000002226 14120250671 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. */ #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-0.12.1/src/test/cpp/decodingtest.cpp000644 001750 001750 00000011044 14120250671 022744 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/test/cpp/abts.h000644 001750 001750 00000006323 14120250671 020672 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 #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 { const char* name; int num_test; int 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, 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-0.12.1/src/test/cpp/hierarchythresholdtestcase.cpp000644 001750 001750 00000007414 14120250671 025725 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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() { log4cxx::spi::LoggerRepositoryPtr rep = logger->getLoggerRepository().lock(); 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/temp")); LoggerPtr HierarchyThresholdTestCase::logger = Logger::getLogger(LOG4CXX_TEST_STR("HierarchyThresholdTestCase")); LOGUNIT_TEST_SUITE_REGISTRATION(HierarchyThresholdTestCase); apache-log4cxx-0.12.1/src/test/cpp/loggertestcase.cpp000644 001750 001750 00000032277 14120250671 023316 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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() {} void append(const spi::LoggingEventPtr& /*event*/, Pool& /*p*/) { counter++; } bool requiresLayout() const { 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()); a->addAppender(ca1); abc->addAppender(ca2); 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()); 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->debug(MSG); 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); LoggerRepositoryPtr 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); } 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(false, root->isTraceEnabled()); } protected: static LogString MSG; LoggerPtr logger; AppenderPtr a1; AppenderPtr a2; }; LogString LoggerTestCase::MSG(LOG4CXX_STR("M")); LOGUNIT_TEST_SUITE_REGISTRATION(LoggerTestCase); apache-log4cxx-0.12.1/src/test/resources/000755 001750 001750 00000000000 14122472745 021026 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/L7D_fr.properties000644 001750 001750 00000001751 14120250671 024213 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/000755 001750 001750 00000000000 14122472744 022164 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/patternLayout3.properties000644 001750 001750 00000002164 14120250671 027232 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/socketServer3.properties000644 001750 001750 00000002203 14120250671 027030 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/propertiestestcase.properties000644 001750 001750 00000002514 14121417414 030224 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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.crlf1=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-0.12.1/src/test/resources/input/socketServer2.properties000644 001750 001750 00000002204 14120250671 027030 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/patternLayout6.properties000644 001750 001750 00000002141 14120250671 027230 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp 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-0.12.1/src/test/resources/input/hierarchyThreshold1.properties000644 001750 001750 00000002025 14120250671 030204 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-0.12.1/src/test/resources/input/hierarchyThreshold7.properties000644 001750 001750 00000002066 14120250671 030217 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-0.12.1/src/test/resources/input/socketServer4.properties000644 001750 001750 00000002216 14120250671 027035 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/patternLayout10.properties000644 001750 001750 00000002125 14120250671 027305 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp 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-0.12.1/src/test/resources/input/patternLayout11.properties000644 001750 001750 00000002123 14120250671 027304 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp 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-0.12.1/src/test/resources/input/socketServer7.properties000644 001750 001750 00000002221 14120250671 027034 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/patternLayout1.properties000644 001750 001750 00000002112 14120250671 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/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p - %m%napache-log4cxx-0.12.1/src/test/resources/input/xml/000755 001750 001750 00000000000 14122472744 022764 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/fallback1.xml000644 001750 001750 00000004360 14120250671 025320 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/log4j.dtd000644 001750 001750 00000015076 14120250671 024500 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/DOMTestCase1.xml000644 001750 001750 00000003402 14120250671 025630 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/customLevel4.xml000644 001750 001750 00000002574 14120250671 026073 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/DOMTestCase4.xml000644 001750 001750 00000002534 14120250671 025640 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/customLevel3.xml000644 001750 001750 00000003225 14120250671 026064 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/filters.LevelMatchFilter.test4.2.xml000644 001750 001750 00000003007 14120250671 031540 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/filters.LevelMatchFilter.test4.1.xml000644 001750 001750 00000003007 14120250671 031537 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/filters.LevelMatchFilter.test4.3.xml000644 001750 001750 00000003010 14120250671 031533 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/filters.LevelMatchFilter.test4.0.xml000644 001750 001750 00000003010 14120250671 031530 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/smtpAppender1.xml000644 001750 001750 00000003043 14120250671 026220 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/customLogger2.xml000644 001750 001750 00000003241 14120250671 026231 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/DOMTestCase3.xml000644 001750 001750 00000002532 14120250671 025635 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/customLevel1.xml000644 001750 001750 00000002540 14120250671 026061 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/DOMTestCase2.xml000644 001750 001750 00000003406 14120250671 025635 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/filters.LevelMatchFilter.test4.4.xml000644 001750 001750 00000003010 14120250671 031534 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/customLevel2.xml000644 001750 001750 00000003124 14120250671 026061 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/asyncAppender1.xml000644 001750 001750 00000002515 14120250671 026355 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/defaultInit.xml000644 001750 001750 00000002374 14120250671 025753 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/xml/customLogger1.xml000644 001750 001750 00000002616 14120250671 026235 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/rolling/000755 001750 001750 00000000000 14122472744 023632 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/rolling/time1.xml000644 001750 001750 00000003434 14120250671 025366 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/rolling/obsoleteERFA1.properties000644 001750 001750 00000002643 14120250671 030277 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/rolling/filter1.xml000644 001750 001750 00000004164 14120250671 025716 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/rolling/obsoleteDRFA1.properties000644 001750 001750 00000002604 14120250671 030273 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/rolling/obsoleteRFA1.properties000644 001750 001750 00000002553 14120250671 030172 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 # 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-0.12.1/src/test/resources/input/socketServer5.properties000644 001750 001750 00000002216 14120250671 027036 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/hierarchyThreshold6.properties000644 001750 001750 00000002027 14120250671 030213 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-0.12.1/src/test/resources/input/ndc/000755 001750 001750 00000000000 14122472744 022730 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/ndc/NDC1.properties000644 001750 001750 00000002464 14120250671 025530 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp 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-0.12.1/src/test/resources/input/patternLayout2.properties000644 001750 001750 00000002145 14120250671 027230 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp 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-0.12.1/src/test/resources/input/hierarchyThreshold8.properties000644 001750 001750 00000002030 14120250671 030207 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-0.12.1/src/test/resources/input/hierarchyThreshold2.properties000644 001750 001750 00000002027 14120250671 030207 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-0.12.1/src/test/resources/input/hierarchyThreshold3.properties000644 001750 001750 00000002027 14120250671 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.threshold=ERROR log4j.rootLogger=,A 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=%p %c = %m%n apache-log4cxx-0.12.1/src/test/resources/input/patternLayout9.properties000644 001750 001750 00000002124 14120250671 027234 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %.16c : %m%napache-log4cxx-0.12.1/src/test/resources/input/patternLayout4.properties000644 001750 001750 00000002140 14120250671 027225 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp 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-0.12.1/src/test/resources/input/patternLayout8.properties000644 001750 001750 00000002127 14120250671 027236 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp 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-0.12.1/src/test/resources/input/defaultInit3.properties000644 001750 001750 00000002037 14120250671 026626 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/l7d1.properties000644 001750 001750 00000002114 14120250671 025036 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=T1 %5p - %m%n apache-log4cxx-0.12.1/src/test/resources/input/socketServer1.properties000644 001750 001750 00000002171 14120250671 027032 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/hierarchyThreshold5.properties000644 001750 001750 00000002026 14120250671 030211 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-0.12.1/src/test/resources/input/socketServer8.properties000644 001750 001750 00000002221 14120250671 027035 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/decoding/000755 001750 001750 00000000000 14122472744 023740 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/input/decoding/UTF-16LE.txt000644 001750 001750 00000000020 14120250671 025563 0ustar00robertrobert000000 000000 A0 N apache-log4cxx-0.12.1/src/test/resources/input/decoding/UTF-16.txt000644 001750 001750 00000000022 14120250671 025344 0ustar00robertrobert000000 000000 A0 N apache-log4cxx-0.12.1/src/test/resources/input/decoding/UTF-8.txt000644 001750 001750 00000000020 14120250671 025263 0ustar00robertrobert000000 000000 A؅԰আ七Ѐ ¹apache-log4cxx-0.12.1/src/test/resources/input/decoding/latin1.txt000644 001750 001750 00000000010 14120250671 025647 0ustar00robertrobert000000 000000 A????? apache-log4cxx-0.12.1/src/test/resources/input/decoding/UTF-16BE.txt000644 001750 001750 00000000020 14120250671 025551 0ustar00robertrobert000000 000000 A0 N apache-log4cxx-0.12.1/src/test/resources/input/decoding/ascii.txt000644 001750 001750 00000000010 14120250671 025547 0ustar00robertrobert000000 000000 A????? ?apache-log4cxx-0.12.1/src/test/resources/input/patternLayout.mdc.1.properties000644 001750 001750 00000002113 14120250671 030042 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p - %m %Xapache-log4cxx-0.12.1/src/test/resources/input/patternLayout7.properties000644 001750 001750 00000002146 14120250671 027236 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp 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-0.12.1/src/test/resources/input/hierarchyThreshold4.properties000644 001750 001750 00000002026 14120250671 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.threshold=WARN log4j.rootLogger=,A 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=%p %c = %m%n apache-log4cxx-0.12.1/src/test/resources/input/patternLayout5.properties000644 001750 001750 00000002162 14120250671 027232 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp 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-0.12.1/src/test/resources/input/socketServer6.properties000644 001750 001750 00000002221 14120250671 027033 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/input/patternLayout12.properties000644 001750 001750 00000002125 14120250671 027307 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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/temp 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-0.12.1/src/test/resources/witness/000755 001750 001750 00000000000 14122472745 022522 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/patternLayout.9000644 001750 001750 00000000547 14120250671 025463 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-0.12.1/src/test/resources/witness/xmlLayout.3000644 001750 001750 00000001246 14120250671 024575 0ustar00robertrobert000000 000000 hi]]>]]> hi]]>]]> apache-log4cxx-0.12.1/src/test/resources/witness/patternLayout.1000644 001750 001750 00000000264 14120250671 025447 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-0.12.1/src/test/resources/witness/serialization/000755 001750 001750 00000000000 14122472744 025376 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/serialization/ndc.bin000644 001750 001750 00000000631 14120250671 026623 0ustar00robertrobert000000 000000 sr!org.apache.log4j.spi.LoggingEvent#t ? ZmdcCopyLookupRequiredZndcLookupRequiredJ timeStampL categoryNametLjava/lang/String;L locationInfot#Lorg/apache/log4j/spi/LocationInfo;LmdcCopytLjava/util/Hashtable;Lndcq~LrenderedMessageq~L threadNameq~L throwableInfot+Lorg/apache/log4j/spi/ThrowableInformation;xp&!5trootpptndc testt Hello, world.tmainpwN pxapache-log4cxx-0.12.1/src/test/resources/witness/serialization/exception.bin000644 001750 001750 00000003463 14120250671 030063 0ustar00robertrobert000000 000000 sr!org.apache.log4j.spi.LoggingEvent#t ? ZmdcCopyLookupRequiredZndcLookupRequiredJ timeStampL categoryNametLjava/lang/String;L locationInfot#Lorg/apache/log4j/spi/LocationInfo;LmdcCopytLjava/util/Hashtable;Lndcq~LrenderedMessageq~L threadNameq~L throwableInfot+Lorg/apache/log4j/spi/ThrowableInformation;xp&trootpppt Hello, world.tmainsr)org.apache.log4j.spi.ThrowableInformationrQ[rept[Ljava/lang/String;xpur[Ljava.lang.String;V{Gxpt java.lang.Exception: Don't panictb at org.apache.log4j.spi.LoggingEventTest.testSerializationWithException(LoggingEventTest.java:70)t? at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)tQ at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)tY at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)t4 at java.lang.reflect.Method.invoke(Method.java:324)t7 at junit.framework.TestCase.runTest(TestCase.java:154)t7 at junit.framework.TestCase.runBare(TestCase.java:127)t= at junit.framework.TestResult$1.protect(TestResult.java:106)t@ at junit.framework.TestResult.runProtected(TestResult.java:124)t7 at junit.framework.TestResult.run(TestResult.java:109)t3 at junit.framework.TestCase.run(TestCase.java:118)t9 at junit.framework.TestSuite.runTest(TestSuite.java:208)t5 at junit.framework.TestSuite.run(TestSuite.java:203)t9 at junit.framework.TestSuite.runTest(TestSuite.java:208)t5 at junit.framework.TestSuite.run(TestSuite.java:203)t^ at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:289)ta at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:656)t_ at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:558)wN pxapache-log4cxx-0.12.1/src/test/resources/witness/serialization/mdc.bin000644 001750 001750 00000000774 14120250671 026632 0ustar00robertrobert000000 000000 sr!org.apache.log4j.spi.LoggingEvent#t ? ZmdcCopyLookupRequiredZndcLookupRequiredJ timeStampL categoryNametLjava/lang/String;L locationInfot#Lorg/apache/log4j/spi/LocationInfo;LmdcCopytLjava/util/Hashtable;Lndcq~LrenderedMessageq~L threadNameq~L throwableInfot+Lorg/apache/log4j/spi/ThrowableInformation;xp&!trootpsrjava.util.Hashtable%!JF loadFactorI thresholdxp?@wtmdckeytmdcvaluextndc testt Hello, world.tmainpwN pxapache-log4cxx-0.12.1/src/test/resources/witness/serialization/location.bin000644 001750 001750 00000000721 14120250671 027667 0ustar00robertrobert000000 000000 sr!org.apache.log4j.spi.LoggingEvent#t ? ZmdcCopyLookupRequiredZndcLookupRequiredJ timeStampL categoryNametLjava/lang/String;L locationInfot#Lorg/apache/log4j/spi/LocationInfo;LmdcCopytLjava/util/Hashtable;Lndcq~LrenderedMessageq~L threadNameq~L throwableInfot+Lorg/apache/log4j/spi/ThrowableInformation;xp&trootsr!org.apache.log4j.spi.LocationInfo홻J|LfullInfoq~xppppt Hello, world.tmainpwN pxapache-log4cxx-0.12.1/src/test/resources/witness/serialization/simple.bin000644 001750 001750 00000000617 14120250671 027354 0ustar00robertrobert000000 000000 sr!org.apache.log4j.spi.LoggingEvent#t ? ZmdcCopyLookupRequiredZndcLookupRequiredJ timeStampL categoryNametLjava/lang/String;L locationInfot#Lorg/apache/log4j/spi/LocationInfo;LmdcCopytLjava/util/Hashtable;Lndcq~LrenderedMessageq~L threadNameq~L throwableInfot+Lorg/apache/log4j/spi/ThrowableInformation;xp& trootpppt Hello, world.tmainpwN pxapache-log4cxx-0.12.1/src/test/resources/witness/serialization/info.bin000644 001750 001750 00000000074 14120250671 027013 0ustar00robertrobert000000 000000 srorg.apache.log4j.Level0s6xpwN INFOxapache-log4cxx-0.12.1/src/test/resources/witness/hierarchyThreshold.8000644 001750 001750 00000000342 14120250671 026433 0ustar00robertrobert000000 000000 TRACE HierarchyThresholdTestCase = m0 DEBUG HierarchyThresholdTestCase = m1 INFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-0.12.1/src/test/resources/witness/patternLayout.4000644 001750 001750 00000000561 14120250671 025452 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-0.12.1/src/test/resources/witness/encoding/000755 001750 001750 00000000000 14122472745 024310 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/encoding/latin1.log000644 001750 001750 00000000053 14120250671 026167 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - INFO - A????? apache-log4cxx-0.12.1/src/test/resources/witness/encoding/UTF-16BE.log000644 001750 001750 00000000126 14120250671 026071 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - INFO - A0 N apache-log4cxx-0.12.1/src/test/resources/witness/encoding/UTF-8.log000644 001750 001750 00000000063 14120250671 025603 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - ¹ INFO - A؅԰আ七Ѐ apache-log4cxx-0.12.1/src/test/resources/witness/encoding/ascii.log000644 001750 001750 00000000053 14120250671 026067 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - ? INFO - A????? apache-log4cxx-0.12.1/src/test/resources/witness/encoding/UTF-16.log000644 001750 001750 00000000130 14120250671 025655 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - INFO - A0 N apache-log4cxx-0.12.1/src/test/resources/witness/encoding/UTF-16LE.log000644 001750 001750 00000000126 14120250671 026103 0ustar00robertrobert000000 000000 INFO - Hello, World INFO - INFO - A0 N apache-log4cxx-0.12.1/src/test/resources/witness/NDCMatchFilter_deny000644 001750 001750 00000002225 14120250671 026202 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-0.12.1/src/test/resources/witness/patternLayout.6000644 001750 001750 00000000561 14120250671 025454 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-0.12.1/src/test/resources/witness/patternLayout.12000644 001750 001750 00000000751 14120250671 025532 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-0.12.1/src/test/resources/witness/dom.A1.1000644 001750 001750 00000000707 14120250671 023615 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-0.12.1/src/test/resources/witness/l7d.1000644 001750 001750 00000002157 14120250671 023265 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-0.12.1/src/test/resources/witness/hierarchyThreshold.3000644 001750 001750 00000000114 14120250671 026423 0ustar00robertrobert000000 000000 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-0.12.1/src/test/resources/witness/xmlLayout.null000644 001750 001750 00000000772 14120250671 025410 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/customLevel.3000644 001750 001750 00000000052 14120250671 025073 0ustar00robertrobert000000 000000 TRACE xml.CustomLevelTestCase - Message 5 apache-log4cxx-0.12.1/src/test/resources/witness/patternLayout.7000644 001750 001750 00000000561 14120250671 025455 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-0.12.1/src/test/resources/witness/socketServer.2000644 001750 001750 00000003666 14120250671 025265 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-0.12.1/src/test/resources/witness/patternLayout.5000644 001750 001750 00000000561 14120250671 025453 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-0.12.1/src/test/resources/witness/socketServer.5000644 001750 001750 00000003501 14120250671 025254 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-0.12.1/src/test/resources/witness/LevelRangeFilter_neutral000644 001750 001750 00000005234 14120250671 027363 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-0.12.1/src/test/resources/witness/xmlLayout.mdc.1000644 001750 001750 00000000440 14120250671 025330 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/socketServer.7000644 001750 001750 00000003666 14120250671 025272 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-0.12.1/src/test/resources/witness/xmlLayout.mdc.2000644 001750 001750 00000000534 14120250671 025335 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/socketServer.1000644 001750 001750 00000003435 14120250671 025256 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-0.12.1/src/test/resources/witness/xmlLayout.1000644 001750 001750 00000005225 14120250671 024574 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/simple000644 001750 001750 00000000750 14120250671 023726 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-0.12.1/src/test/resources/witness/ttcc000644 001750 001750 00000001522 14120250671 023370 0ustar00robertrobert000000 000000 [main] FATAL ERR - Message 0 [main] ERROR ERR - Message 1 [main] FATAL INF - Message 2 [main] ERROR INF - Message 3 [main] WARN INF - Message 4 [main] INFO INF - Message 5 [main] FATAL INF.UNDEF - Message 6 [main] ERROR INF.UNDEF - Message 7 [main] WARN INF.UNDEF - Message 8 [main] INFO INF.UNDEF - Message 9 [main] FATAL INF.ERR - Message 10 [main] ERROR INF.ERR - Message 11 [main] FATAL INF.ERR.UNDEF - Message 12 [main] ERROR INF.ERR.UNDEF - Message 13 [main] FATAL DEB - Message 14 [main] ERROR DEB - Message 15 [main] WARN DEB - Message 16 [main] INFO DEB - Message 17 [main] DEBUG DEB - Message 18 [main] FATAL UNDEF - Message 19 [main] ERROR UNDEF - Message 20 [main] WARN UNDEF - Message 21 [main] INFO UNDEF - Message 22 [main] DEBUG UNDEF - Message 23 [main] INFO INF - Messages should bear numbers 0 through 23. apache-log4cxx-0.12.1/src/test/resources/witness/patternLayout.mdc.2000644 001750 001750 00000000727 14120250671 026216 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-0.12.1/src/test/resources/witness/customLogger.1000644 001750 001750 00000000432 14120250671 025243 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-0.12.1/src/test/resources/witness/socketServer.6000644 001750 001750 00000003666 14120250671 025271 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-0.12.1/src/test/resources/witness/hierarchyThreshold.1000644 001750 001750 00000000000 14120250671 026413 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/patternLayout.2000644 001750 001750 00000000562 14120250671 025451 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-0.12.1/src/test/resources/witness/fallback1000644 001750 001750 00000000610 14120250671 024250 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-0.12.1/src/test/resources/witness/socketServer.3000644 001750 001750 00000003666 14120250671 025266 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-0.12.1/src/test/resources/witness/patternLayout.11000644 001750 001750 00000000600 14120250671 025522 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-0.12.1/src/test/resources/witness/socketServer.8000644 001750 001750 00000003743 14120250671 025267 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-0.12.1/src/test/resources/witness/patternLayout.3000644 001750 001750 00000000561 14120250671 025451 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-0.12.1/src/test/resources/witness/rolling/000755 001750 001750 00000000000 14122472745 024170 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test4.2000644 001750 001750 00000000102 14120250671 026062 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test1.0000644 001750 001750 00000000000 14120250671 026052 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test1.2000644 001750 001750 00000000102 14120250671 026057 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test5.1000644 001750 001750 00000000102 14120250671 026062 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test5.0000644 001750 001750 00000000000 14120250671 026056 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test6.3000644 001750 001750 00000000041 14120250671 026067 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---4 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test2.1000644 001750 001750 00000000102 14120250671 026057 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test5.2000644 001750 001750 00000000102 14120250671 026063 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test3.3000644 001750 001750 00000000041 14120250671 026064 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---4 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test4.3000644 001750 001750 00000000041 14120250671 026065 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---4 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/sbr-test3.1.gz000644 001750 001750 00000000104 14120250671 026500 0ustar00robertrobert000000 000000 (hAsbr-test3.1H5 ,#82L,38β,`bdapache-log4cxx-0.12.1/src/test/resources/witness/rolling/sbr-test3.0.gz000644 001750 001750 00000000104 14120250671 026477 0ustar00robertrobert000000 000000 $hAsbr-test3.0H54 ,#82L,38β,O dapache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test4.1000644 001750 001750 00000000102 14120250671 026061 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/sbr-test2.0000644 001750 001750 00000000144 14120250671 026063 0ustar00robertrobert000000 000000 Hello--10 Hello--11 Hello--12 Hello--13 Hello--14 Hello--15 Hello--16 Hello--17 Hello--18 Hello--19 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test2.3000644 001750 001750 00000000041 14120250671 026063 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---4 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/sbr-test3.log000644 001750 001750 00000000062 14120250671 026505 0ustar00robertrobert000000 000000 Hello--20 Hello--21 Hello--22 Hello--23 Hello--24 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/sbr-test4.log000644 001750 001750 00000000372 14120250671 026512 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-0.12.1/src/test/resources/witness/rolling/tbr-test2.2000644 001750 001750 00000000102 14120250671 026060 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test1.3000644 001750 001750 00000000041 14120250671 026062 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---4 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test1.1000644 001750 001750 00000000102 14120250671 026056 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test4.0000644 001750 001750 00000000000 14120250671 026055 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test5.3000644 001750 001750 00000000041 14120250671 026066 0ustar00robertrobert000000 000000 TimeBasedRollingTest - Hello---4 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/tbr-test2.0000644 001750 001750 00000000000 14120250671 026053 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/sbr-test2.1000644 001750 001750 00000000144 14120250671 026064 0ustar00robertrobert000000 000000 Hello---0 Hello---1 Hello---2 Hello---3 Hello---4 Hello---5 Hello---6 Hello---7 Hello---8 Hello---9 apache-log4cxx-0.12.1/src/test/resources/witness/rolling/sbr-test2.log000644 001750 001750 00000000062 14120250671 026504 0ustar00robertrobert000000 000000 Hello--20 Hello--21 Hello--22 Hello--23 Hello--24 apache-log4cxx-0.12.1/src/test/resources/witness/ndc/000755 001750 001750 00000000000 14122472745 023266 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/ndc/NDC.1000644 001750 001750 00000000637 14120250671 023750 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-0.12.1/src/test/resources/witness/socketServer.4000644 001750 001750 00000003470 14120250671 025260 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-0.12.1/src/test/resources/witness/customLevel.2000644 001750 001750 00000000322 14120250671 025072 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-0.12.1/src/test/resources/witness/NDCMatchFilter_accept000644 001750 001750 00000001103 14120250671 026474 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-0.12.1/src/test/resources/witness/hierarchyThreshold.5000644 001750 001750 00000000226 14120250671 026431 0ustar00robertrobert000000 000000 INFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-0.12.1/src/test/resources/witness/LevelMatchFilter_accept000644 001750 001750 00000000405 14120250671 027143 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-0.12.1/src/test/resources/witness/patternLayout.mdc.1000644 001750 001750 00000000055 14120250671 026207 0ustar00robertrobert000000 000000 DEBUG - Hello World {{key1,va11}{key2,va12}} apache-log4cxx-0.12.1/src/test/resources/witness/dom.A2.2000644 001750 001750 00000000676 14120250671 023624 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-0.12.1/src/test/resources/witness/customLevel.4000644 001750 001750 00000000322 14120250671 025074 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-0.12.1/src/test/resources/witness/patternLayout.8000644 001750 001750 00000000547 14120250671 025462 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-0.12.1/src/test/resources/witness/LevelMatchFilter_deny000644 001750 001750 00000001754 14120250671 026653 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-0.12.1/src/test/resources/witness/xmlLayout.2000644 001750 001750 00000010527 14120250671 024576 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/resources/witness/dom.A1.2000644 001750 001750 00000000707 14120250671 023616 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-0.12.1/src/test/resources/witness/hierarchyThreshold.7000644 001750 001750 00000000342 14120250671 026432 0ustar00robertrobert000000 000000 TRACE HierarchyThresholdTestCase = m0 DEBUG HierarchyThresholdTestCase = m1 INFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-0.12.1/src/test/resources/witness/hierarchyThreshold.2000644 001750 001750 00000000046 14120250671 026426 0ustar00robertrobert000000 000000 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-0.12.1/src/test/resources/witness/hierarchyThreshold.6000644 001750 001750 00000000274 14120250671 026435 0ustar00robertrobert000000 000000 DEBUG HierarchyThresholdTestCase = m1 INFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-0.12.1/src/test/resources/witness/dom.A2.1000644 001750 001750 00000000676 14120250671 023623 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-0.12.1/src/test/resources/witness/LevelRangeFilter_accept000644 001750 001750 00000005234 14120250671 027150 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-0.12.1/src/test/resources/witness/customLogger.2000644 001750 001750 00000000057 14120250671 025247 0ustar00robertrobert000000 000000 TRACE customLogger.XLoggerTestCase - Message 0 apache-log4cxx-0.12.1/src/test/resources/witness/hierarchyThreshold.4000644 001750 001750 00000000161 14120250671 026426 0ustar00robertrobert000000 000000 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-0.12.1/src/test/resources/witness/patternLayout.10000644 001750 001750 00000000751 14120250671 025530 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-0.12.1/src/test/resources/witness/customLevel.1000644 001750 001750 00000000322 14120250671 025071 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-0.12.1/src/test/resources/L7D_fr_CH.properties000644 001750 001750 00000001545 14120250671 024566 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/resources/L7D_en_US.properties000644 001750 001750 00000001603 14120250671 024611 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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-0.12.1/src/test/java/000755 001750 001750 00000000000 14122472745 017735 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/java/CMakeLists.txt000644 001750 001750 00000002216 14121416623 022466 0ustar00robertrobert000000 000000 include(FetchContent) FetchContent_Declare(log4j URL https://downloads.apache.org/logging/log4j/1.2.17/log4j-1.2.17.tar.gz URL_HASH MD5=8218714e41ee0c6509dcfeafa2e1f53f ) FetchContent_GetProperties(log4j) if(NOT log4j_POPULATED) FetchContent_Populate(log4j) endif() set(log4j_CLASSPATH "${log4j_SOURCE_DIR}/log4j-1.2.17.jar" ) set(SOCKET_SERVER_SOURCES org/apache/log4j/net/ShortSocketServer.java) add_custom_target(test-classes COMMAND ${Java_JAVAC_EXECUTABLE} -d ${CMAKE_CURRENT_BINARY_DIR} -classpath "${log4j_CLASSPATH}" ${SOCKET_SERVER_SOURCES} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} ) if(WIN32) set(SOCKET_SERVER_CLASSPATH "${CMAKE_CURRENT_BINARY_DIR};${log4j_CLASSPATH}") else() set(SOCKET_SERVER_CLASSPATH "${CMAKE_CURRENT_BINARY_DIR}:${log4j_CLASSPATH}") endif() # Use a parameter file to avoid issues with processing ';' file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/StartSocketServerParams.txt "${Java_JAVA_EXECUTABLE} -classpath ${SOCKET_SERVER_CLASSPATH} org.apache.log4j.net.ShortSocketServer 8 input/socketServer " ) set(START_SOCKET_SERVER_PARAMETER_FILE ${CMAKE_CURRENT_BINARY_DIR}/StartSocketServerParams.txt PARENT_SCOPE) apache-log4cxx-0.12.1/src/test/java/org/000755 001750 001750 00000000000 14122472745 020524 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/java/org/apache/000755 001750 001750 00000000000 14122472745 021745 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/java/org/apache/log4j/000755 001750 001750 00000000000 14122472745 022764 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/java/org/apache/log4j/net/000755 001750 001750 00000000000 14122472745 023552 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/test/java/org/apache/log4j/net/ShortSocketServer.java000644 001750 001750 00000005523 14120250671 030047 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import java.net.Socket; import java.net.ServerSocket; import java.io.IOException; import org.apache.log4j.Logger; import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.MDC; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.net.SocketNode; import org.apache.log4j.net.SocketServer; /** * This SocketServer exits after certain number of connections from a * client. This number is determined the totalsTest parameter, that is * the first argument on the commmand line. The second argument, * prefix, determines the prefix of the configuration file to * use. Each run of the server will use a different properties * file. For the i-th run, the path to the file is * (prefix+i+".properties"). * * @author Ceki Gulcu */ public class ShortSocketServer { static Logger cat = Logger.getLogger(ShortSocketServer.class); public static void main(String args[]) throws Exception { int totalTests = 0; String prefix = null; if(args.length == 2) { totalTests = Integer.parseInt(args[0]); prefix = args[1]; } else { usage("Wrong number of arguments."); } int port = Integer.valueOf(System.getProperty("port", "12345")); LogLog.debug("Listening on port " + port); ServerSocket serverSocket = new ServerSocket(port); MDC.put("hostID", "shortSocketServer"); for(int i = 1; i <= totalTests; i++) { PropertyConfigurator.configure(prefix+i+".properties"); LogLog.debug("Waiting to accept a new client."); Socket socket = serverSocket.accept(); LogLog.debug("Connected to client at " + socket.getInetAddress()); LogLog.debug("Starting new socket node."); SocketNode sn = new SocketNode(socket, LogManager.getLoggerRepository()); Thread t = new Thread(sn); t.start(); t.join(); } } static void usage(String msg) { System.err.println(msg); System.err.println( "Usage: java " +ShortSocketServer.class.getName() + " totalTests configFilePrefix"); System.exit(1); } } apache-log4cxx-0.12.1/src/cmake/000755 001750 001750 00000000000 14122472745 017115 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/cmake/FindAPR.cmake000644 001750 001750 00000004010 14120250670 021322 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) find_program(APR_CONFIG_EXECUTABLE apr-1-config PATHS /usr/local/bin /usr/local/opt/apr/bin /usr/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) set(APR_SYSTEM_LIBS ws2_32 mswsock rpcrt4) 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() find_package_handle_standard_args(APR APR_INCLUDE_DIR APR_LIBRARIES) apache-log4cxx-0.12.1/src/cmake/FindAPR-Util.cmake000644 001750 001750 00000004160 14120250670 022243 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) find_program(APR_UTIL_CONFIG_EXECUTABLE apu-1-config PATHS /usr/local/bin /usr/local/opt/apr-util/bin /usr/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}") _apu_invoke(XMLLIB_LIBRARIES --libs) 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() find_package_handle_standard_args(APR-Util APR_UTIL_INCLUDE_DIR APR_UTIL_LIBRARIES) apache-log4cxx-0.12.1/src/cmake/boost-fallback/000755 001750 001750 00000000000 14122472745 022000 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/cmake/boost-fallback/test-boostatomic.cpp000644 001750 001750 00000000131 14120250670 025764 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ boost::atomic b; } apache-log4cxx-0.12.1/src/cmake/boost-fallback/test-stdsharedptr.cpp000644 001750 001750 00000000167 14120250670 026161 0ustar00robertrobert000000 000000 #include struct foo{ int x; }; int main(int argc, char** argv){ std::shared_ptr fooptr; return 0; } apache-log4cxx-0.12.1/src/cmake/boost-fallback/boost-std-configuration.h.cmake000644 001750 001750 00000001152 14120250670 027777 0ustar00robertrobert000000 000000 #ifndef BOOST_STD_CONFIGURATION_H #define BOOST_STD_CONFIGURATION_H #cmakedefine01 STD_SHARED_MUTEX_FOUND #cmakedefine01 Boost_SHARED_MUTEX_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 #endif /* BOOST_STD_CONFIGURATION_H */ apache-log4cxx-0.12.1/src/cmake/boost-fallback/test-boostthread.cpp000644 001750 001750 00000000136 14120250670 025764 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ boost::thread th; return 0; } apache-log4cxx-0.12.1/src/cmake/boost-fallback/test-stdmutex.cpp000644 001750 001750 00000000123 14120250670 025317 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ std::mutex mutex; return 0; } apache-log4cxx-0.12.1/src/cmake/boost-fallback/test-boostmutex.cpp000644 001750 001750 00000000140 14120250670 025652 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ boost::mutex mutex; return 0; } apache-log4cxx-0.12.1/src/cmake/boost-fallback/test-boostsharedmutex.cpp000644 001750 001750 00000000162 14120250670 027045 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ boost::shared_mutex mtx; return 0; } apache-log4cxx-0.12.1/src/cmake/boost-fallback/test-stdthread.cpp000644 001750 001750 00000000122 14120250670 025423 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ std::thread th; return 0; } apache-log4cxx-0.12.1/src/cmake/boost-fallback/boost-fallback.cmake000644 001750 001750 00000006250 14121416577 025670 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 # # 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 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") find_package(Boost COMPONENTS thread) 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} ) # 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() apache-log4cxx-0.12.1/src/cmake/boost-fallback/test-boostsharedptr.cpp000644 001750 001750 00000000206 14120250670 026507 0ustar00robertrobert000000 000000 #include struct foo{ int x; }; int main(int argc, char** argv){ boost::shared_ptr fooptr; return 0; } apache-log4cxx-0.12.1/src/cmake/boost-fallback/test-stdsharedmutex.cpp000644 001750 001750 00000000142 14120250670 026507 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ std::shared_mutex shared; return 0; } apache-log4cxx-0.12.1/src/cmake/boost-fallback/test-stdatomic.cpp000644 001750 001750 00000000114 14120250670 025431 0ustar00robertrobert000000 000000 #include int main(int argc, char** argv){ std::atomic b; } apache-log4cxx-0.12.1/src/cmake/projectVersionDetails.cmake000644 001750 001750 00000000354 14122472134 024433 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 0.12.1.0) apache-log4cxx-0.12.1/src/main/000755 001750 001750 00000000000 14122472745 016761 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/cpp-qt/000755 001750 001750 00000000000 14122472745 020165 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/cpp-qt/CMakeLists.txt000644 001750 001750 00000001373 14120250670 022716 0ustar00robertrobert000000 000000 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) target_sources(log4cxx-qt PRIVATE messagehandler.cpp ) set_target_properties(log4cxx-qt PROPERTIES VERSION ${LIBLOG4CXX_LIB_VERSION} SOVERSION ${LIBLOG4CXX_LIB_SOVERSION} ) endif( LOG4CXX_QT_SUPPORT) apache-log4cxx-0.12.1/src/main/cpp-qt/messagehandler.cpp000644 001750 001750 00000003446 14120250670 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 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, 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-0.12.1/src/main/CMakeLists.txt000644 001750 001750 00000000740 14120250670 021507 0ustar00robertrobert000000 000000 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-0.12.1/src/main/include/000755 001750 001750 00000000000 14122472745 020404 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/CMakeLists.txt000644 001750 001750 00000011414 14122472113 023132 0ustar00robertrobert000000 000000 # 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) elseif(${LOG4CXX_CHAR} STREQUAL "wchar_t") set(LOGCHAR_IS_WCHAR 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() # 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(CheckIncludeFiles) include(CheckIncludeFileCXX) include(CheckLibraryExists) if(WIN32) CHECK_INCLUDE_FILES(sqlext.h HAS_ODBC) else() include(FindPkgConfig) pkg_check_modules( odbc QUIET odbc ) if(${odbc_FOUND}) set(HAS_ODBC 1) endif(${odbc_FOUND}) endif(WIN32) 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_LIBRARY_EXISTS(esmtp smtp_create_session "" HAS_LIBESMTP) CHECK_FUNCTION_EXISTS(syslog HAS_SYSLOG) foreach(varName HAS_STD_LOCALE HAS_ODBC HAS_MBSRTOWCS HAS_WCSTOMBS HAS_FWIDE HAS_LIBESMTP HAS_SYSLOG) if(${varName} EQUAL 0) continue() elseif(${varName} EQUAL 1) continue() elseif("${varName}" STREQUAL "ON") set(${varName} 1 ) elseif("${varName}" STREQUAL "OFF") set(${varName} 0 ) else() set(${varName} 0 ) endif() endforeach() # Check for standard headers that we need, fall back to boost if they're not found include(${LOG4CXX_SOURCE_DIR}/src/cmake/boost-fallback/boost-fallback.cmake) set(NAMESPACE_ALIAS log4cxx) if( ${STD_THREAD_FOUND} ) set( THREAD_IMPL "std::thread" ) elseif( ${Boost_THREAD_FOUND} ) set( THREAD_IMPL "boost::thread" ) else() set( THREAD_IMPL "NONE" ) endif() if( ${STD_MUTEX_FOUND} ) 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} ) 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} ) 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} ) set( ATOMIC_IMPL "std::atomic" ) elseif( ${Boost_ATOMIC_FOUND} ) set( ATOMIC_IMPL "boost::atomic" ) else() set( ATOMIC_IMPL "NONE" ) endif() # Configure both our private header and our public header 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/boost-std-configuration.h ) # Provide the dependencies add_custom_target(configure_log4cxx COMMAND "${CMAKE_COMMAND}" -E echo "Checking configuration" ) apache-log4cxx-0.12.1/src/main/include/log4cxx/000755 001750 001750 00000000000 14122472745 021774 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/version_info.h.in000644 001750 001750 00000000562 14120250671 025243 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-0.12.1/src/main/include/log4cxx/asyncappender.h000644 001750 001750 00000016721 14120250670 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. */ #ifndef _LOG4CXX_ASYNC_APPENDER_H #define _LOG4CXX_ASYNC_APPENDER_H #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 { 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); virtual void doAppend(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool1); void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p); /** Close this AsyncAppender by interrupting the dispatcher thread which will process all pending events before exiting. */ void close(); /** * Get iterator over attached appenders. * @return list of all attached appenders. */ AppenderList getAllAppenders() const; /** * Get appender by name. * * @param name name, may not be null. * @return matching appender or null. */ AppenderPtr getAppender(const LogString& name) const; /** * 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; virtual bool requiresLayout() const; /** * Removes and closes all attached appenders. */ void removeAllAppenders(); /** * Removes an appender. * @param appender appender to remove. */ void removeAppender(const AppenderPtr appender); /** * Remove appender by name. * @param name name. */ void removeAppender(const LogString& name); /** * 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); private: AsyncAppender(const AsyncAppender&); AsyncAppender& operator=(const AsyncAppender&); /** * The default buffer size is set to 128 events. */ enum { DEFAULT_BUFFER_SIZE = 128 }; /** * 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 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); }; /** * Map of DiscardSummary objects keyed by logger name. */ typedef std::map DiscardMap; 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; /** * Dispatch routine. */ void dispatch(); }; // class AsyncAppender LOG4CXX_PTR_DEF(AsyncAppender); } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif// _LOG4CXX_ASYNC_APPENDER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/writerappender.h000644 001750 001750 00000015046 14120250671 025174 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include namespace log4cxx { namespace helpers { class Transcoder; } /** WriterAppender appends log events to a standard output stream */ class LOG4CXX_EXPORT WriterAppender : public AppenderSkeleton { private: /** 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; 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); public: ~WriterAppender(); /** Derived appenders should override this method if option structure requires it. */ virtual void activateOptions(log4cxx::helpers::Pool& pool); /** 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 { return immediateFlush; } /** 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. */ virtual void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p); 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. */ virtual void close(); 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 log4cxx::helpers::WriterPtr createWriter( log4cxx::helpers::OutputStreamPtr& os); public: LogString getEncoding() const; void setEncoding(const LogString& value); void setOption(const LogString& option, const LogString& value); /**

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); #ifdef LOG4CXX_MULTI_PROCESS const log4cxx::helpers::WriterPtr getWriter() { return writer; }; #endif virtual bool requiresLayout() const; 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 #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_WRITER_APPENDER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/portability.h000644 001750 001750 00000001636 14120250671 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. */ #ifndef _LOG4CXX_PORTABILITY_H #define _LOG4CXX_PORTABILITY_H // // Obsolete file // #endif //_LOG4CXX_PORTABILITY_H apache-log4cxx-0.12.1/src/main/include/log4cxx/ndc.h000644 001750 001750 00000027516 14120250671 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. */ #ifndef _LOG4CXX_NDC_H #define _LOG4CXX_NDC_H #include #include #include #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif 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 #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_NDC_H apache-log4cxx-0.12.1/src/main/include/log4cxx/file.h000644 001750 001750 00000011605 14120250670 023054 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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; private: LogString path; static char* convertBackSlashes(char*); char* getPath(log4cxx::helpers::Pool& p) const; }; } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #define LOG4CXX_FILE(name) log4cxx::File(name) #endif // _LOG4CXX_FILE_H apache-log4cxx-0.12.1/src/main/include/log4cxx/defaultconfigurator.h000644 001750 001750 00000003202 14120250670 026176 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 namespace log4cxx { namespace spi { class LoggerRepository; typedef std::shared_ptr LoggerRepositoryPtr; } /** * Configures the repository from environmental settings and files. * */ class LOG4CXX_EXPORT DefaultConfigurator { private: DefaultConfigurator() {} public: /** Add a ConsoleAppender that uses PatternLayout using the PatternLayout#TTCC_CONVERSION_PATTERN and prints to stdout to the root logger.*/ static void configure(log4cxx::spi::LoggerRepositoryPtr repository); private: static const LogString getConfigurationFileName(); static const LogString getConfiguratorClass(); }; // class DefaultConfigurator } // namespace log4cxx #endif //_LOG4CXX_DEFAULT_CONFIGURATOR_H apache-log4cxx-0.12.1/src/main/include/log4cxx/ttcclayout.h000644 001750 001750 00000014110 14120250671 024323 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _LOG4CXX_TTCC_LAYOUT_H #define _LOG4CXX_TTCC_LAYOUT_H #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include namespace log4cxx { /** TTCC layout format consists of time, thread, logger name and nested diagnostic context information, hence the name.

Each of the four fields can be individually enabled or disabled. The time format depends on the DateFormat used.

Here is an example TTCCLayout output with the {@link helpers::RelativeTimeDateFormat RelativeTimeDateFormat}.

176 [main] INFO  examples.Sort - Populating an array of 2 elements in reverse order.
225 [main] INFO  examples.SortAlgo - Entered the sort method.
262 [main] DEBUG examples.SortAlgo.OUTER i=1 - Outer loop.
276 [main] DEBUG examples.SortAlgo.SWAP i=1 j=0 - Swapping intArray[0] = 1 and intArray[1] = 0
290 [main] DEBUG examples.SortAlgo.OUTER i=0 - Outer loop.
304 [main] INFO  examples.SortAlgo.DUMP - Dump of interger array:
317 [main] INFO  examples.SortAlgo.DUMP - Element [0] = 0
331 [main] INFO  examples.SortAlgo.DUMP - Element [1] = 1
343 [main] INFO  examples.Sort - The next log statement should be an error message.
346 [main] ERROR examples.SortAlgo.DUMP - Tried to dump an uninitialized array.
467 [main] INFO  examples.Sort - Exiting main method.

The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread outputting the log statement. The third field is the level, the fourth field is the logger to which the statement belongs.

The fifth field (just before the '-') is the nested diagnostic context. Note the nested diagnostic context may be empty as in the first two statements. The text after the '-' is the message of the statement.

WARNING Do not use the same TTCCLayout instance from within different appenders. The TTCCLayout is not thread safe when used in his way. However, it is perfectly safe to use a TTCCLayout instance from just one appender.

PatternLayout offers a much more flexible alternative. */ class LOG4CXX_EXPORT TTCCLayout : public helpers::DateLayout { private: // Internal representation of options bool threadPrinting; bool categoryPrefixing; bool contextPrinting; bool filePrinting; public: DECLARE_LOG4CXX_OBJECT(TTCCLayout) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(TTCCLayout) LOG4CXX_CAST_ENTRY_CHAIN(Layout) END_LOG4CXX_CAST_MAP() /** Instantiate a TTCCLayout object with {@link helpers::RelativeTimeDateFormat RelativeTimeDateFormat} as the date formatter in the local time zone. */ TTCCLayout(); /** Instantiate a TTCCLayout object using the local time zone. The DateFormat used will depend on the dateFormatType.

This constructor just calls the {@link helpers::DateLayout#setDateFormat DateLayout::setDateFormat} method. */ TTCCLayout(const LogString& dateFormatType); /** The ThreadPrinting option specifies whether the name of the current thread is part of log output or not. This is true by default. */ inline void setThreadPrinting(bool threadPrinting1) { this->threadPrinting = threadPrinting1; } /** Returns value of the ThreadPrinting option. */ inline bool getThreadPrinting() const { return threadPrinting; } /** The CategoryPrefixing option specifies whether Logger name is part of log output or not. This is true by default. */ inline void setCategoryPrefixing(bool categoryPrefixing1) { this->categoryPrefixing = categoryPrefixing1; } /** Returns value of the CategoryPrefixing option. */ inline bool getCategoryPrefixing() const { return categoryPrefixing; } /** The ContextPrinting option specifies log output will include the nested context information belonging to the current thread. This is true by default. */ inline void setContextPrinting(bool contextPrinting1) { this->contextPrinting = contextPrinting1; } /** Returns value of the ContextPrinting option. */ inline bool getContextPrinting() const { return contextPrinting; } /** The FilePrinting option specifies log output will include the file and the line where the log statement was written. */ inline void setFilePrinting(bool filePrinting1) { this->filePrinting = filePrinting1; } /** Returns value of the ContextPrinting option. */ inline bool getFilePrinting() const { return filePrinting; } /** In addition to the level of the statement and message, this function writes to the ouput stream time, thread, logger and NDC information.

Time, thread, logger and diagnostic context are printed depending on options. @param output destination to receive formatted output. @param event event to format. @param pool pool used to allocate memory needed during formatting. */ virtual void format(LogString& output, const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool) const; /** The TTCCLayout does not handle the throwable contained within {@link spi::LoggingEvent LoggingEvents}. Thus, it returns true. */ virtual bool ignoresThrowable() const { return true; } }; LOG4CXX_PTR_DEF(TTCCLayout); } #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/000755 001750 001750 00000000000 14122472745 023436 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/timezone.h000644 001750 001750 00000003606 14120250671 025434 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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(); const LogString id; }; } } #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_HELPERS_TIMEZONE_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/stringtokenizer.h000644 001750 001750 00000003216 14120250671 027040 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif namespace log4cxx { namespace helpers { class LOG4CXX_EXPORT StringTokenizer { public: StringTokenizer(const LogString& str, const LogString& delim); ~StringTokenizer(); bool hasMoreTokens() const; LogString nextToken(); protected: LogString src; LogString delim; size_t pos; private: // prevent copy and assignment statements StringTokenizer(const StringTokenizer&); StringTokenizer& operator=(const StringTokenizer&); }; // class StringTokenizer } // namespace helpers; } // namespace log4cxx; #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_HELPERS_STRING_TOKENIZER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/objectoutputstream.h000644 001750 001750 00000005670 14120250670 027547 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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_OBJECTOUTPUTSTREAM_H #define _LOG4CXX_HELPERS_OBJECTOUTPUTSTREAM_H #include #include #include #include namespace log4cxx { namespace helpers { /** * Emulates java serialization. */ class LOG4CXX_EXPORT ObjectOutputStream : public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(ObjectOutputStream) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ObjectOutputStream) END_LOG4CXX_CAST_MAP() ObjectOutputStream(OutputStreamPtr os, Pool& p); virtual ~ObjectOutputStream(); void close(Pool& p); void flush(Pool& p); void reset(Pool& p); void writeObject(const LogString&, Pool& p); void writeUTFString(const std::string&, Pool& p); void writeObject(const MDC::Map& mdc, Pool& p); void writeInt(int val, Pool& p); void writeLong(log4cxx_time_t val, Pool& p); void writeProlog(const char* className, int classDescIncrement, char* bytes, size_t len, Pool& p); void writeNull(Pool& p); enum { STREAM_MAGIC = 0xACED }; enum { STREAM_VERSION = 5 }; enum { TC_NULL = 0x70, TC_REFERENCE = 0x71, TC_CLASSDESC = 0x72, TC_OBJECT = 0x73, TC_STRING = 0x74, TC_ARRAY = 0x75, TC_CLASS = 0x76, TC_BLOCKDATA = 0x77, TC_ENDBLOCKDATA = 0x78, TC_RESET = 0x79 }; enum { SC_WRITE_METHOD = 0x01, SC_SERIALIZABLE = 0x02 }; void writeByte(char val, Pool& p); void writeBytes(const char* bytes, size_t len, Pool& p); private: ObjectOutputStream(const ObjectOutputStream&); ObjectOutputStream& operator=(const ObjectOutputStream&); OutputStreamPtr os; log4cxx::helpers::CharsetEncoderPtr utf8Encoder; const unsigned int objectHandleDefault; unsigned int objectHandle; typedef std::map ClassDescriptionMap; ClassDescriptionMap* classDescriptions; }; LOG4CXX_PTR_DEF(ObjectOutputStream); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_OUTPUTSTREAM_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/propertyresourcebundle.h000644 001750 001750 00000003740 14120250670 030426 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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); virtual LogString getString(const LogString& key) const; protected: Properties properties; }; // class PropertyResourceBundle LOG4CXX_PTR_DEF(PropertyResourceBundle); } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_PROPERTY_RESOURCE_BUNDLE_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/messagebuffer.h000644 001750 001750 00000053544 14120250670 026425 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 4275 ) #endif namespace log4cxx { namespace helpers { void MessageBufferUseStaticStream(); 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&); /** * Encapsulated std::string. */ std::basic_string buf; /** * Encapsulated stream, created on demand. */ std::basic_ostringstream* stream; }; 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&); /** * Encapsulated std::string. */ std::basic_string buf; /** * Encapsulated stream, created on demand. */ std::basic_ostringstream* stream; }; 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&); /** * Encapsulated std::string. */ std::basic_string buf; /** * Encapsulated stream, created on demand. */ std::basic_ostringstream* stream; }; 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&); /** * Character message buffer. */ CharMessageBuffer cbuf; /** * Encapsulated wide message buffer, created on demand. */ WideMessageBuffer* wbuf; #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API /** * Encapsulated wide message buffer, created on demand. */ UniCharMessageBuffer* ubuf; #endif }; 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 typedef CharMessageBuffer MessageBuffer; typedef CharMessageBuffer LogCharMessageBuffer; #endif } } #if defined(_MSC_VER) #pragma warning (pop) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/xml.h000644 001750 001750 00000006735 14120250671 024410 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_HELPERS_XML_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/fileoutputstream.h000644 001750 001750 00000004066 14120250670 027216 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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: Pool pool; apr_file_t* fileptr; 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(); virtual void close(Pool& p); virtual void flush(Pool& p); virtual void write(ByteBuffer& buf, Pool& p); #ifdef LOG4CXX_MULTI_PROCESS apr_file_t* getFilePtr() { return fileptr; } #endif 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-0.12.1/src/main/include/log4cxx/helpers/datagramsocket.h000644 001750 001750 00000007245 14120250670 026575 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 extern "C" { struct apr_socket_t; } namespace log4cxx { namespace helpers { /** This class represents a socket for sending and receiving datagram packets.*/ class LOG4CXX_EXPORT DatagramSocket : public helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(DatagramSocket) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(DatagramSocket) END_LOG4CXX_CAST_MAP() /** Constructs a datagram socket and binds it to any available port on the local host machine.*/ DatagramSocket(); /** Constructs a datagram socket and binds it to the specified port on the local host machine. */ DatagramSocket(int port); /** Creates a datagram socket, bound to the specified local address. */ DatagramSocket(int port, InetAddressPtr laddr); /** ensure the socket is closed. */ ~DatagramSocket(); /** Binds a datagram socket to a local port and address.*/ void bind(int lport, InetAddressPtr laddress); /** Creates a datagram socket.*/ void create(); /** Closes this datagram socket */ void close(); /** Connects the socket to a remote address for this socket. */ void connect(InetAddressPtr address, int port); /** Returns the address to which this socket is connected. */ inline InetAddressPtr getInetAddress() const { return address; } /** Gets the local address to which the socket is bound. */ inline InetAddressPtr getLocalAddress() const { return localAddress; } /** Returns the port number on the local host to which this socket is bound. */ inline int getLocalPort() const { return localPort; } /** Returns the port for this socket */ inline int getPort() const { return port; } /** Returns the binding state of the socket. **/ inline bool isBound() const { return localPort != 0; } /** Returns wether the socket is closed or not. */ inline bool isClosed() const { return socket != 0; } /** Returns the connection state of the socket. */ inline bool isConnected() const { return port != 0; } /** Receives a datagram packet from this socket. */ void receive(DatagramPacketPtr& p); /** Sends a datagram packet from this socket. */ void send(DatagramPacketPtr& p); private: DatagramSocket(const DatagramSocket&); DatagramSocket& operator=(const DatagramSocket&); /** The APR socket */ apr_socket_t* socket; /** The memory pool for the socket */ Pool socketPool; InetAddressPtr address; InetAddressPtr localAddress; int port; /** The local port number to which this socket is connected. */ int localPort; }; LOG4CXX_PTR_DEF(DatagramSocket); } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_DATAGRAM_SOCKET_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/bytearrayoutputstream.h000644 001750 001750 00000004021 14120250670 030270 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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: ByteList array; 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(); virtual void close(Pool& p); virtual void flush(Pool& p); virtual void write(ByteBuffer& buf, Pool& p); ByteList toByteArray() const; private: ByteArrayOutputStream(const ByteArrayOutputStream&); ByteArrayOutputStream& operator=(const ByteArrayOutputStream&); }; LOG4CXX_PTR_DEF(ByteArrayOutputStream); } // namespace helpers } //namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_HELPERS_BYTEARRAYOUTPUTSTREAM_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/datetimedateformat.h000644 001750 001750 00000002721 14120250670 027441 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/classregistration.h000644 001750 001750 00000002465 14120250670 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_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-0.12.1/src/main/include/log4cxx/helpers/strftimedateformat.h000644 001750 001750 00000003566 14120250671 027513 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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: /** * Time zone. */ TimeZonePtr timeZone; std::string pattern; }; } // namespace helpers } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_HELPERS_STRFTIME_DATE_FORMAT_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/systemerrwriter.h000644 001750 001750 00000003273 14120250671 027074 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Abstract class for writing to character streams. */ 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(); virtual void close(Pool& p); virtual void flush(Pool& p); virtual void write(const LogString& str, Pool& p); 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-0.12.1/src/main/include/log4cxx/helpers/properties.h000644 001750 001750 00000014446 14120250670 026001 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_HELPER_PROPERTIES_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/strictmath.h000644 001750 001750 00000002634 14120250671 025764 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/outputstreamwriter.h000644 001750 001750 00000004030 14120250670 027602 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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: OutputStreamPtr out; CharsetEncoderPtr enc; 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(); virtual void close(Pool& p); virtual void flush(Pool& p); virtual void write(const LogString& str, Pool& p); LogString getEncoding() const; #ifdef LOG4CXX_MULTI_PROCESS OutputStreamPtr getOutPutStreamPtr() { return out; } #endif private: OutputStreamWriter(const OutputStreamWriter&); OutputStreamWriter& operator=(const OutputStreamWriter&); }; LOG4CXX_PTR_DEF(OutputStreamWriter); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_OUTPUTSTREAMWRITER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/writer.h000644 001750 001750 00000003223 14120250671 025111 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; #ifdef LOG4CXX_MULTI_PROCESS virtual OutputStreamPtr getOutPutStreamPtr(); #endif private: Writer(const Writer&); Writer& operator=(const Writer&); }; LOG4CXX_PTR_DEF(Writer); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_WRITER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/filewatchdog.h000644 001750 001750 00000004365 14120250670 026244 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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: /** 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; protected: FileWatchdog(const File& filename); virtual void doOnChange() = 0; void checkAndConfigure(); public: /** Set the delay to observe between each check of the file changes. */ void setDelay(long delay1) { this->delay = delay1; } void start(); private: void run(); bool is_interrupted(); Pool pool; std::thread thread; std::condition_variable interrupt; std::mutex interrupt_mutex; FileWatchdog(const FileWatchdog&); FileWatchdog& operator=(const FileWatchdog&); }; } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_FILEWATCHDOG_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/cyclicbuffer.h000644 001750 001750 00000005213 14120250670 026235 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 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 { log4cxx::spi::LoggingEventList ea; int first; int last; int numElems; int maxSize; 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 { return maxSize; } /** 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 { return numElems; } /** 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-0.12.1/src/main/include/log4cxx/helpers/resourcebundle.h000644 001750 001750 00000005041 14120250671 026616 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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. */ ResourceBundlePtr parent; }; // class ResourceBundle } // namespace helpers } // namespace log4cxx #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/system.h000644 001750 001750 00000003041 14120250671 025117 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/datelayout.h000644 001750 001750 00000005432 14120250670 025753 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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_LAYOUT_H #define _LOG4CXX_HELPERS_DATE_LAYOUT_H #include #include #include #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif namespace log4cxx { namespace helpers { /** This abstract layout takes care of all the date related options and formatting work. */ class LOG4CXX_EXPORT DateLayout : public Layout { private: LogString timeZoneID; LogString dateFormatOption; protected: DateFormatPtr dateFormat; public: DateLayout(const LogString& dateLayoutOption); virtual ~DateLayout(); virtual void activateOptions(log4cxx::helpers::Pool& p); virtual void setOption(const LogString& option, const LogString& value); /** The value of the DateFormat option should be either an argument to the constructor of helpers::DateFormat or one of the strings "NULL", "RELATIVE", "ABSOLUTE", "DATE" or "ISO8601. */ inline void setDateFormat(const LogString& dateFormat1) { this->dateFormatOption.assign(dateFormat1); } /** Returns value of the DateFormat option. */ inline const LogString& getDateFormat() const { return dateFormatOption; } /** The TimeZoneID option is a time zone ID string in the format expected by the locale C++ standard class. */ inline void setTimeZone(const LogString& timeZone) { this->timeZoneID.assign(timeZone); } /** Returns value of the TimeZone option. */ inline const LogString& getTimeZone() const { return timeZoneID; } void formatDate(LogString& s, const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) const; private: // // prevent copy and assignment DateLayout(const DateLayout&); DateLayout& operator=(const DateLayout&); }; } // namespace helpers } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_HELPERS_DATE_LAYOUT_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/datagrampacket.h000644 001750 001750 00000010434 14120250670 026546 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { protected: /** 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; 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. */ inline InetAddressPtr getAddress() const { return address; } /** Returns the data received or the data to be sent. */ inline void* getData() const { return buf; } /** Returns the length of the data to be sent or the length of the data received. */ inline int getLength() const { return length; } /** Returns the offset of the data to be sent or the offset of the data received. */ inline int getOffset() const { return offset; } /** Returns the port number on the remote host to which this datagram is being sent or from which the datagram was received. */ inline int getPort() const { return port; } inline void setAddress(InetAddressPtr address1) { this->address = address1; } /** Set the data buffer for this packet. */ inline void setData(void* buf1) { this->buf = buf1; } /** Set the data buffer for this packet. */ inline void setData(void* buf1, int offset1, int length1) { this->buf = buf1; this->offset = offset1; this->length = length1; } /** Set the length for this packet. */ inline void setLength(int length1) { this->length = length1; } inline void setPort(int port1) { this->port = 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-0.12.1/src/main/include/log4cxx/helpers/class.h000644 001750 001750 00000003256 14120250670 024707 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_HELPERS_CLASS_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/outputstream.h000644 001750 001750 00000003450 14120250670 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. */ #ifndef _LOG4CXX_HELPERS_OUTPUTSTREAM_H #define _LOG4CXX_HELPERS_OUTPUTSTREAM_H #include #ifdef LOG4CXX_MULTI_PROCESS #include #endif 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; #ifdef LOG4CXX_MULTI_PROCESS virtual apr_file_t* getFilePtr(); virtual OutputStream& getFileOutPutStreamPtr(); #endif private: OutputStream(const OutputStream&); OutputStream& operator=(const OutputStream&); }; LOG4CXX_PTR_DEF(OutputStream); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_OUTPUTSTREAM_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/simpledateformat.h000644 001750 001750 00000004676 14120250671 027152 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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: /** * Time zone. */ TimeZonePtr timeZone; /** * List of tokens. */ PatternTokenList pattern; 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 #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_HELPERS_SIMPLE_DATE_FORMAT_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/exception.h000644 001750 001750 00000022135 14120250670 025575 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 : 4251 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-0.12.1/src/main/include/log4cxx/helpers/bytearrayinputstream.h000644 001750 001750 00000004711 14120250670 030075 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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: ByteList buf; size_t pos; 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. */ virtual void close(); /** * 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. */ virtual int read(ByteBuffer& buf); private: ByteArrayInputStream(const ByteArrayInputStream&); ByteArrayInputStream& operator=(const ByteArrayInputStream&); }; LOG4CXX_PTR_DEF(ByteArrayInputStream); } // namespace helpers } //namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_HELPERS_BYTEARRAYINPUTSTREAM_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/aprinitializer.h000644 001750 001750 00000004054 14121416577 026640 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 extern "C" { typedef struct apr_thread_mutex_t apr_thread_mutex_t; typedef struct apr_threadkey_t apr_threadkey_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 * APR termination. FileWatchdog must be * allocated on heap and not deleted elsewhere. */ static void registerCleanup(FileWatchdog* watchdog); static void unregisterCleanup(FileWatchdog* watchdog); private: APRInitializer(); APRInitializer(const APRInitializer&); APRInitializer& operator=(const APRInitializer&); apr_pool_t* p; std::mutex mutex; std::list watchdogs; apr_time_t startTime; apr_threadkey_t* tlsKey; static APRInitializer& getInstance(); public: ~APRInitializer(); }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_APRINITIALIZER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/onlyonceerrorhandler.h000644 001750 001750 00000005777 14120250670 030052 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #ifdef _MSC_VER #pragma warning ( push ) #pragma warning (disable : 4251) // ::std::exception needs to have dll-interface #endif 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: LogString WARN_PREFIX; LogString ERROR_PREFIX; mutable bool firstTime; public: DECLARE_LOG4CXX_OBJECT(OnlyOnceErrorHandler) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(spi::OptionHandler) LOG4CXX_CAST_ENTRY(spi::ErrorHandler) END_LOG4CXX_CAST_MAP() OnlyOnceErrorHandler(); /** Does not do anything. */ void setLogger(const LoggerPtr& logger); /** No options to activate. */ void activateOptions(log4cxx::helpers::Pool& p); void setOption(const LogString& option, const LogString& value); /** 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; /** 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; /** Print a the error message passed as parameter on System.err. */ void error(const LogString& message) const; /** Does not do anything. */ void setAppender(const AppenderPtr& appender); /** Does not do anything. */ void setBackupAppender(const AppenderPtr& appender); }; } // namespace helpers } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_HELPERS_ONLY_ONCE_ERROR_HANDLER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/threadspecificdata.h000644 001750 001750 00000003734 14120250671 027413 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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::NDC::Stack ndcStack; log4cxx::MDC::Map mdcMap; }; } // namespace helpers } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/object.h000644 001750 001750 00000012376 14120250670 025053 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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_ABSTRACT_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 const helpers::Class& getClass() const;\ static const helpers::Class& getStaticClass(); \ static const log4cxx::helpers::ClassRegistration& registerClass(); #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();\ }\ };\ virtual const helpers::Class& getClass() const;\ static const helpers::Class& getStaticClass(); \ static const log4cxx::helpers::ClassRegistration& registerClass(); #define DECLARE_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(object, class)\ public:\ virtual const helpers::Class& getClass() const;\ 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: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Object) virtual ~Object() {} virtual bool instanceof(const Class& clazz) const = 0; virtual const void* cast(const Class& clazz) const = 0; }; 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) { 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\ {\ 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\ { 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-0.12.1/src/main/include/log4cxx/helpers/bufferedwriter.h000644 001750 001750 00000003616 14120250670 026621 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif namespace log4cxx { namespace helpers { /** * Writes text to a character-output stream buffering * requests to increase efficiency. */ class LOG4CXX_EXPORT BufferedWriter : public Writer { private: WriterPtr out; size_t sz; LogString buf; 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(); virtual void close(Pool& p); virtual void flush(Pool& p); virtual void write(const LogString& str, Pool& p); private: BufferedWriter(const BufferedWriter&); BufferedWriter& operator=(const BufferedWriter&); }; } // namespace helpers } //namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_HELPERS_BUFFEREDWRITER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/serversocket.h000644 001750 001750 00000003165 14121416577 026333 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 LOG4CXX_EXPORT ServerSocket { public: /** Creates a server socket on a specified port. */ ServerSocket(int port); virtual ~ServerSocket(); /** Listens for a connection to be made to this socket and accepts it */ SocketPtr accept(); /** Closes this socket. */ void close(); /** Retrive setting for SO_TIMEOUT. */ int getSoTimeout() const; /** Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. */ void setSoTimeout(int timeout); private: Pool pool; std::mutex mutex; apr_socket_t* socket; int timeout; }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_SERVER_SOCKET_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/fileinputstream.h000644 001750 001750 00000005225 14120250670 027013 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 namespace log4cxx { namespace helpers { /** * InputStream implemented on top of APR file IO. * */ class LOG4CXX_EXPORT FileInputStream : public InputStream { private: Pool pool; apr_file_t* fileptr; 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. */ virtual void close(); /** * 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. */ virtual int read(ByteBuffer& buf); 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-0.12.1/src/main/include/log4cxx/helpers/bytebuffer.h000644 001750 001750 00000003515 14120250670 025735 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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: char* base; size_t pos; size_t lim; size_t cap; public: ByteBuffer(char* data, size_t capacity); ~ByteBuffer(); void clear(); void flip(); inline char* data() { return base; } inline const char* data() const { return base; } inline char* current() { return base + pos; } inline const char* current() const { return base + pos; } inline size_t limit() const { return lim; } void limit(size_t newLimit); inline size_t position() const { return pos; } inline size_t remaining() const { return lim - pos; } 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-0.12.1/src/main/include/log4cxx/helpers/charsetdecoder.h000644 001750 001750 00000005724 14120250670 026563 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/absolutetimedateformat.h000644 001750 001750 00000002507 14120250670 030344 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/transcoder.h000644 001750 001750 00000017146 14120250671 025752 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_HELPERS_TRANSCODER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/locale.h000644 001750 001750 00000003242 14120250670 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_LOCALE_H #define _LOG4CXX_HELPERS_LOCALE_H #include #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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); const LogString& getLanguage() const; const LogString& getCountry() const; const LogString& getVariant() const; protected: Locale(const Locale&); Locale& operator=(const Locale&); const LogString language; const LogString country; const LogString variant; }; // class Locale } // namespace helpers } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_HELPERS_LOCALE_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/relativetimedateformat.h000644 001750 001750 00000002731 14120250670 030340 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/loader.h000644 001750 001750 00000002462 14120250670 025046 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/socketoutputstream.h000644 001750 001750 00000004006 14120250671 027562 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(); virtual void close(Pool& p); virtual void flush(Pool& p); virtual void write(ByteBuffer& buf, Pool& p); private: ByteList array; SocketPtr socket; // // prevent copy and assignment statements SocketOutputStream(const SocketOutputStream&); SocketOutputStream& operator=(const SocketOutputStream&); }; LOG4CXX_PTR_DEF(SocketOutputStream); } // namespace helpers } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_HELPERS_SOCKET_OUTPUT_STREAM_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/inputstream.h000644 001750 001750 00000003705 14120250670 026154 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/inetaddress.h000644 001750 001750 00000005346 14120250670 026111 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include namespace log4cxx { namespace helpers { class LOG4CXX_EXPORT 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); /** 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: LogString ipAddrString; LogString hostNameString; }; // class InetAddress } // namespace helpers } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_HELPER_INETADDRESS_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/integer.h000644 001750 001750 00000002417 14120250670 025235 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/dateformat.h000644 001750 001750 00000004730 14120250670 025726 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/tchar.h000644 001750 001750 00000016260 14120250671 024703 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/iso8601dateformat.h000644 001750 001750 00000002773 14120250670 026765 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/cacheddateformat.h000644 001750 001750 00000014471 14120250670 027061 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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[]; /** * 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; 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); /** * 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 #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_HELPERS_SIMPLE_DATE_FORMAT_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/bufferedoutputstream.h000644 001750 001750 00000003443 14120250670 030057 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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_BUFFEREDOUTPUTSTREAM_H #define _LOG4CXX_HELPERS_BUFFEREDOUTPUTSTREAM_H #include namespace log4cxx { namespace helpers { /** * Abstract class for writing to character streams. */ class LOG4CXX_EXPORT BufferedOutputStream : public OutputStream { private: size_t count; LogString buf; public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(BufferedOutputStream) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(BufferedOutputStream) LOG4CXX_CAST_ENTRY_CHAIN(OutputStream) END_LOG4CXX_CAST_MAP() protected: BufferedOutputStream(OutputStreamPtr& out, size_t size = 4096); ~BufferedOutputStream(); public: void close(Pool& p); void flush(Pool& p); void write(ByteBuffer& buf, Pool& p); private: BufferedOutputStream(const BufferedOutputStream&); BufferedOutputStream& operator=(const BufferedOutputStream&); }; LOG4CXX_PTR_DEF(BufferedOutputStream); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_BUFFEREDOUTPUTSTREAM_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/systemoutwriter.h000644 001750 001750 00000003262 14120250671 027111 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Abstract class for writing to character streams. */ 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(); virtual void close(Pool& p); virtual void flush(Pool& p); virtual void write(const LogString& str, Pool& p); 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-0.12.1/src/main/include/log4cxx/helpers/charsetencoder.h000644 001750 001750 00000006501 14120250670 026567 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/socket.h000644 001750 001750 00000004706 14120250671 025074 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 extern "C" { struct apr_socket_t; } #include #include namespace log4cxx { namespace helpers { class ByteBuffer; /**

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 { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Socket) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Socket) END_LOG4CXX_CAST_MAP() /** Creates a stream socket and connects it to the specified port number at the specified IP address. */ Socket(InetAddressPtr& address, int port); Socket(apr_socket_t* socket, apr_pool_t* pool); ~Socket(); size_t write(ByteBuffer&); /** Closes this socket. */ void close(); /** Returns the value of this socket's address field. */ InetAddressPtr getInetAddress() const; /** Returns the value of this socket's port field. */ int getPort() const; private: Socket(const Socket&); Socket& operator=(const Socket&); Pool pool; apr_socket_t* socket; /** 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; }; LOG4CXX_PTR_DEF(Socket); } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_SOCKET_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/reader.h000644 001750 001750 00000003376 14120250670 025047 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/inputstreamreader.h000644 001750 001750 00000005130 14120250670 027331 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Class for reading from character streams. * Decorates a byte based InputStream and provides appropriate * conversion to characters. */ class LOG4CXX_EXPORT InputStreamReader : public Reader { private: InputStreamPtr in; CharsetDecoderPtr dec; 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. */ virtual void close(Pool& p); /** * @return The complete stream contents as a LogString. * @param p The memory pool associated with the reader. */ virtual LogString read(Pool& p); /** * @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-0.12.1/src/main/include/log4cxx/helpers/optionconverter.h000644 001750 001750 00000013003 14120250670 027031 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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

		String 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

		String 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. */ static void selectAndConfigure(const File& configFileName, const LogString& clazz, spi::LoggerRepositoryPtr hierarchy); }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPER_OPTION_CONVERTER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/transform.h000644 001750 001750 00000004150 14120250671 025610 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/stringhelper.h000644 001750 001750 00000004001 14120250671 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. */ #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 log4cxx_int64_t toInt64(const LogString& s); static void toString(int i, log4cxx::helpers::Pool& pool, LogString& dst); static void toString(log4cxx_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-0.12.1/src/main/include/log4cxx/helpers/date.h000644 001750 001750 00000003160 14120250670 024511 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 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(); }; LOG4CXX_PTR_DEF(Date); } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/syslogwriter.h000644 001750 001750 00000003176 14120250671 026361 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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); void write(const LogString& string); private: LogString syslogHost; int syslogHostPort; InetAddressPtr address; DatagramSocketPtr ds; }; } // namespace helpers } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/helpers/loglog.h000644 001750 001750 00000006247 14121416577 025103 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 logging by calling the #setInternalDebugging method.

All log4cxx internal debug calls go to standard output where as internal error messages are sent to standard error output. All internal messages are prepended with the string "log4cxx: ". */ class LOG4CXX_EXPORT LogLog { private: bool debugEnabled; /** In quietMode not even errors generate any output. */ bool quietMode; std::mutex mutex; LogLog(); LogLog(const LogLog&); LogLog& operator=(const LogLog&); static LogLog& getInstance(); public: /** Allows to enable/disable log4cxx internal logging. */ static void setInternalDebugging(bool enabled); /** This method is used to output log4cxx internal debug statements. Output goes to the standard output. */ static void debug(const LogString& msg); static void debug(const LogString& msg, const std::exception& e); /** This method is used to output log4cxx internal error statements. There is no way to disable error statements. Output goes to stderr. */ static void error(const LogString& msg); static void error(const LogString& msg, const std::exception& e); /** In quiet mode LogLog generates strictly no output, not even for errors. @param quietMode true for no output. */ static void setQuietMode(bool quietMode); /** This method is used to output log4cxx internal warning statements. There is no way to disable warning statements. Output goes to stderr. */ static void warn(const LogString& msg); static void warn(const LogString& msg, const std::exception& e); 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-0.12.1/src/main/include/log4cxx/helpers/pool.h000644 001750 001750 00000003034 14120250670 024545 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/helpers/threadlocal.h000644 001750 001750 00000004161 14120250671 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_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-0.12.1/src/main/include/log4cxx/helpers/appenderattachableimpl.h000644 001750 001750 00000006427 14121416577 030311 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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, public virtual helpers::Object { protected: /** Array of appenders. */ AppenderList appenderList; public: /** * Create new instance. * @param pool pool, must be longer-lived than instance. */ AppenderAttachableImpl(Pool& pool); 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. */ virtual void addAppender(const AppenderPtr newAppender); /** 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. */ virtual AppenderList getAllAppenders() const; /** * Get an appender by name. */ virtual AppenderPtr getAppender(const LogString& name) const; /** Returns true if the specified appender is in the list of attached appenders, false otherwise. */ virtual bool isAttached(const AppenderPtr appender) const; /** * Remove all previously added appenders. */ virtual void removeAllAppenders(); /** * Remove the appender passed as parameter from the list of appenders. */ virtual void removeAppender(const AppenderPtr appender); /** * Remove the appender with the name passed as parameter from the * list of appenders. */ virtual void removeAppender(const LogString& name); inline std::mutex& getMutex() const { return m_mutex; } private: mutable std::mutex m_mutex; AppenderAttachableImpl(const AppenderAttachableImpl&); AppenderAttachableImpl& operator=(const AppenderAttachableImpl&); }; LOG4CXX_PTR_DEF(AppenderAttachableImpl); } } #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_HELPERS_APPENDER_ATTACHABLE_IMPL_H apache-log4cxx-0.12.1/src/main/include/log4cxx/rollingfileappender.h000644 001750 001750 00000010353 14120250671 026162 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _LOG4CXX_ROLLING_FILE_APPENDER_H #define _LOG4CXX_ROLLING_FILE_APPENDER_H #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include namespace log4cxx { /** RollingFileAppender extends FileAppender to backup the log files when they reach a certain size. */ class LOG4CXX_EXPORT RollingFileAppender : public log4cxx::rolling::RollingFileAppenderSkeleton { private: /** The default maximum file size is 10MB. */ long maxFileSize; /** There is one backup file by default. */ int maxBackupIndex; public: // // Use custom class to use non-default name to avoid // conflict with log4cxx::rolling::RollingFileAppender DECLARE_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS( RollingFileAppender, ClassRollingFileAppender ) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY( RollingFileAppender ) LOG4CXX_CAST_ENTRY_CHAIN( FileAppender ) END_LOG4CXX_CAST_MAP() /** The default constructor simply calls its {@link FileAppender#FileAppender parents constructor}. */ RollingFileAppender(); /** Instantiate a RollingFileAppender and open the file designated by filename. The opened filename will become the ouput destination for this appender.

If the append parameter is true, the file will be appended to. Otherwise, the file desginated by filename will be truncated before being opened. */ RollingFileAppender( 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. */ RollingFileAppender( const LayoutPtr& layout, const LogString& fileName ); virtual ~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. */ long 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( int value ); virtual void setOption( const LogString& option, const LogString& value ); /** Prepares RollingFileAppender for use. */ void activateOptions( log4cxx::helpers::Pool& pool ); }; // class RollingFileAppender LOG4CXX_PTR_DEF(RollingFileAppender); } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_ROLLING_FILE_APPENDER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/appenderskeleton.h000644 001750 001750 00000013277 14120250670 025507 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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: /** 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 log4cxx::shared_mutex mutex; /** 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); /** Finalize this appender by calling the derived class' close method. */ void finalize(); /** Derived appenders should override this method if option structure requires it. */ virtual void activateOptions(log4cxx::helpers::Pool& /* pool */) {} virtual void setOption(const LogString& option, const LogString& value); /** Add a filter to end of the filter list. */ void addFilter(const spi::FilterPtr& newFilter) ; public: /** Clear the filters chain. */ void clearFilters(); /** Return the currently set spi::ErrorHandler for this Appender. */ const spi::ErrorHandlerPtr& getErrorHandler() const { return errorHandler; } /** Returns the head Filter. */ spi::FilterPtr getFilter() const { return headFilter; } /** Return the first filter in the filter chain for this Appender. The return value may be 0 if no is filter is set. */ const spi::FilterPtr& getFirstFilter() const { return headFilter; } /** Returns the layout of this appender. The value may be 0. */ LayoutPtr getLayout() const { return layout; } /** Returns the name of this Appender. */ LogString getName() const { return name; } /** Returns this appenders threshold level. See the #setThreshold method for the meaning of this option. */ const LevelPtr& getThreshold() const { return threshold; } /** 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. * */ virtual void doAppend(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool); /** 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. For example, the {@link net::SocketAppender SocketAppender} ignores the layout set here. */ void setLayout(const LayoutPtr& layout1) { this->layout = layout1; } /** Set the name of this Appender. */ void setName(const LogString& name1) { this->name.assign(name1); } /** 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 #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_APPENDER_SKELETON_H apache-log4cxx-0.12.1/src/main/include/log4cxx/logmanager.h000644 001750 001750 00000014023 14120250671 024247 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 repositorySelector; static spi::RepositorySelectorPtr getRepositorySelector(); public: /** Sets LoggerFactory but only if the correct 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 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 appropriate root logger. */ static LoggerPtr getRootLogger(); /** Retrieve the appropriate Logger instance. * @param name logger name in current encoding. * @return logger. */ static LoggerPtr getLogger(const std::string& name); /** Retrieve the appropriate Logger instance. * @param name logger name in current encoding. * @param factory logger factory. * @return logger. */ static LoggerPtr getLogger(const std::string& name, const spi::LoggerFactoryPtr& factory); /** * Determines if logger name exists in the hierarchy. * @param name logger name. * @return true if logger exists. */ static LoggerPtr exists(const std::string& name); #if LOG4CXX_WCHAR_T_API /** Retrieve the appropriate Logger instance. * @param name logger name. * @return logger. */ static LoggerPtr getLogger(const std::wstring& name); /** Retrieve the appropriate Logger instance. * @param name logger name. * @param factory logger factory. * @return logger. */ static LoggerPtr getLogger(const std::wstring& name, const spi::LoggerFactoryPtr& factory); /** * Determines if logger name exists in the hierarchy. * @param name logger name. * @return true if logger exists. */ static LoggerPtr exists(const std::wstring& name); #endif #if LOG4CXX_UNICHAR_API /** Retrieve the appropriate Logger instance. * @param name logger name. * @return logger. */ static LoggerPtr getLogger(const std::basic_string& name); /** Retrieve the appropriate Logger instance. * @param name logger name. * @param factory logger factory. * @return logger. */ static LoggerPtr getLogger(const std::basic_string& name, const spi::LoggerFactoryPtr& factory); /** * Determines if logger name exists in the hierarchy. * @param name logger name. * @return true if logger exists. */ static LoggerPtr exists(const std::basic_string& name); #endif #if LOG4CXX_CFSTRING_API /** Retrieve the appropriate Logger instance. * @param name logger name. * @return logger. */ static LoggerPtr getLogger(const CFStringRef& name); /** Retrieve the appropriate Logger instance. * @param name logger name. * @param factory logger factory. * @return logger. */ static LoggerPtr getLogger(const CFStringRef& name, const spi::LoggerFactoryPtr& factory); /** * Determines if logger name exists in the hierarchy. * @param name logger name. * @return true if logger exists. */ static LoggerPtr exists(const CFStringRef& name); #endif /** Retrieve the appropriate Logger instance. * @param name logger name. * @return logger. */ static LoggerPtr getLoggerLS(const LogString& name); /** Retrieve the appropriate Logger instance. * @param name logger name. * @param factory logger factory. * @return logger. */ static LoggerPtr getLoggerLS(const LogString& name, const spi::LoggerFactoryPtr& factory); /** * Determines if logger name exists in the hierarchy. * @param name logger name. * @return true if logger exists. */ static LoggerPtr existsLS(const LogString& name); static LoggerList getCurrentLoggers(); /** Safely close and remove all appenders in all loggers including the root logger. */ static void shutdown(); /** Reset all values contained in this current {@link spi::LoggerRepository LoggerRepository} to their default. */ static void resetConfiguration(); }; // class LogManager } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_LOG_MANAGER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/nt/000755 001750 001750 00000000000 14122472745 022415 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/nt/nteventlogappender.h000644 001750 001750 00000006467 14120250671 026475 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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(); virtual void activateOptions(log4cxx::helpers::Pool& p); virtual void close(); virtual void setOption(const LogString& option, const LogString& value); /** * The SocketAppender does not use a layout. Hence, this method * returns false. * */ bool requiresLayout() const { return true; } void setSource(const LogString& source) { this->source.assign(source); } const LogString& getSource() const { return source; } void setLog(const LogString& log) { this->log.assign(log); } const LogString& getLog() const { return log; } void setServer(const LogString& server) { this->server.assign(server); } const LogString& getServer() const { return server; } 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; virtual void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p); 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(); // Data LogString server; LogString log; LogString source; HANDLE hEventLog; SID* pCurrentUserSID; static LogString getErrorString(const LogString& function); private: NTEventLogAppender(const NTEventLogAppender&); NTEventLogAppender& operator=(const NTEventLogAppender&); }; // class NTEventLogAppender LOG4CXX_PTR_DEF(NTEventLogAppender); } // namespace nt } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_NT_EVENT_LOG_APPENDER_HEADER_ apache-log4cxx-0.12.1/src/main/include/log4cxx/nt/outputdebugstringappender.h000644 001750 001750 00000002776 14120250671 030105 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { return true; } virtual void close() {} virtual void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p); }; } } #endif //_LOG4CXX_NT_OUTPUTDEBUGSTRING_APPENDER_HEADER_ apache-log4cxx-0.12.1/src/main/include/log4cxx/nt/EventLogCategories.mc000644 001750 001750 00000002016 14120250671 026454 0ustar00robertrobert000000 000000 ; ; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, ; software distributed under the License is distributed on an ; "AS IS" BASIS, WITHOUT 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-0.12.1/src/main/include/log4cxx/spi/000755 001750 001750 00000000000 14122472745 022567 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/spi/loggingevent.h000644 001750 001750 00000016656 14120250671 025434 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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. */ inline const LevelPtr& getLevel() const { return level; } /** Return the name of the logger. */ inline const LogString& getLoggerName() const { return logger; } /** Return the message for this logging event. */ inline const LogString& getMessage() const { return message; } /** Return the message for this logging event. */ inline const LogString& getRenderedMessage() const { return message; } /**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. */ inline const LogString& getThreadName() const { return threadName; } /** The number of microseconds elapsed from 01.01.1970 until logging event was created. */ inline log4cxx_time_t getTimeStamp() const { return timeStamp; } /* Return the file where this log statement was written. */ inline const log4cxx::spi::LocationInfo& getLocationInformation() const { return locationInfo; } /** * 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; /** * Writes the content of the LoggingEvent * in a format compatible with log4j's serialized form. */ void write(helpers::ObjectOutputStream& os, helpers::Pool& p) 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: /** * 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; // // prevent copy and assignment // LoggingEvent(const LoggingEvent&); LoggingEvent& operator=(const LoggingEvent&); static const LogString getCurrentThreadName(); static void writeProlog(log4cxx::helpers::ObjectOutputStream& os, log4cxx::helpers::Pool& p); }; LOG4CXX_PTR_DEF(LoggingEvent); LOG4CXX_LIST_DEF(LoggingEventList, LoggingEventPtr); } } #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_SPI_LOGGING_EVENT_H apache-log4cxx-0.12.1/src/main/include/log4cxx/spi/configurator.h000644 001750 001750 00000003313 14120250671 025430 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** Implemented by classes capable of configuring log4j using a URL. */ class LOG4CXX_EXPORT Configurator : virtual public helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Configurator) 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 void doConfigure(const File& configFileName, spi::LoggerRepositoryPtr repository) = 0; private: Configurator(const Configurator&); Configurator& operator=(const Configurator&); bool initialized; }; LOG4CXX_PTR_DEF(Configurator); } } #endif // _LOG4CXX_SPI_CONFIGURATOR_H apache-log4cxx-0.12.1/src/main/include/log4cxx/spi/defaultrepositoryselector.h000644 001750 001750 00000003116 14120250671 030254 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 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); virtual LoggerRepositoryPtr getLoggerRepository(); private: LoggerRepositoryPtr repository; }; } // namespace spi } // namespace log4cxx #endif //_LOG4CXX_SPI_DEFAULT_REPOSITORY_SELECTOR_H apache-log4cxx-0.12.1/src/main/include/log4cxx/spi/repositoryselector.h000644 001750 001750 00000003471 14120250671 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_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-0.12.1/src/main/include/log4cxx/spi/hierarchyeventlistener.h000644 001750 001750 00000003360 14120250671 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_SPI_HIERARCHY_EVENT_LISTENER_H #define _LOG4CXX_SPI_HIERARCHY_EVENT_LISTENER_H #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_SPI_HIERARCHY_EVENT_LISTENER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/spi/optionhandler.h000644 001750 001750 00000004335 14120250671 025601 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 {@link FileAppender#setFile File} and {@link FileAppender#setAppend Append} options both of which are ambigous until the other is also set. */ virtual void activateOptions(log4cxx::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-0.12.1/src/main/include/log4cxx/spi/rootlogger.h000644 001750 001750 00000003621 14120250671 025113 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/spi/triggeringeventevaluator.h000644 001750 001750 00000003234 14120250671 030056 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/spi/appenderattachable.h000644 001750 001750 00000004713 14120250671 026542 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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_ #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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); } } #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_SPI_APPENDER_ATTACHABLE_H_ apache-log4cxx-0.12.1/src/main/include/log4cxx/spi/loggerrepository.h000644 001750 001750 00000007103 14120250671 026346 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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; /** 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 {@link #setThreshold(const LevelPtr&) setThreshold} for an explanation. */ virtual const 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) = 0; virtual void resetConfiguration() = 0; virtual bool isConfigured() = 0; virtual void setConfigured(bool configured) = 0; }; // class LoggerRepository } // namespace spi } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_SPI_LOG_REPOSITORY_H apache-log4cxx-0.12.1/src/main/include/log4cxx/spi/filter.h000644 001750 001750 00000007762 14120250671 024227 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 {@link xml::DOMConfigurator DOMConfigurator}. */ class LOG4CXX_EXPORT Filter : public virtual OptionHandler, public virtual helpers::Object { /** Points to the next filter in the filter chain. */ FilterPtr next; public: 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(log4cxx::helpers::Pool& p); void setOption(const LogString& option, const LogString& value); /**

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-0.12.1/src/main/include/log4cxx/spi/loggerfactory.h000644 001750 001750 00000002563 14120250671 025603 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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( log4cxx::helpers::Pool& pool, const LogString& name) const = 0; }; } // namespace spi } // namesapce log4cxx #endif //_LOG4CXX_SPI_LOGGERFACTORY_H apache-log4cxx-0.12.1/src/main/include/log4cxx/spi/errorhandler.h000644 001750 001750 00000007306 14120250671 025423 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_SPI_ERROR_HANDLER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/spi/location/000755 001750 001750 00000000000 14122472745 024377 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/spi/location/locationinfo.h000644 001750 001750 00000006340 14120250671 027225 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _LOG4CXX_SPI_LOCATION_LOCATIONINFO_H #define _LOG4CXX_SPI_LOCATION_LOCATIONINFO_H #include #include #include 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(); /** * Constructor. * @remarks Used by LOG4CXX_LOCATION to generate * location info for current code site */ LocationInfo( const char* const fileName, 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; /** * 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; void write(log4cxx::helpers::ObjectOutputStream& os, log4cxx::helpers::Pool& p) const; private: /** Caller's line number. */ int lineNumber; /** Caller's file name. */ const char* fileName; /** Caller's method name. */ const char* methodName; }; } } #if !defined(LOG4CXX_LOCATION) #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_FUNC__, \ __LINE__) #endif #endif //_LOG4CXX_SPI_LOCATION_LOCATIONINFO_H apache-log4cxx-0.12.1/src/main/include/log4cxx/layout.h000644 001750 001750 00000005215 14120250671 023453 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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); } #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_LAYOUT_H apache-log4cxx-0.12.1/src/main/include/log4cxx/propertyconfigurator.h000644 001750 001750 00000032023 14120250671 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_PROPERTY_CONFIGURATOR_H #define _LOG4CXX_PROPERTY_CONFIGURATOR_H #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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; } class PropertyWatchdog; /** Allows the configuration of log4cxx from an external file. See {@link #doConfigure(const File&, log4cxx::spi::LoggerRepositoryPtr&)} 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)} 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 */ std::shared_ptr 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. */ void doConfigure(const File& configFileName, spi::LoggerRepositoryPtr hierarchy); /** Read configuration options from file configFilename. */ static void 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 void 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 void configureAndWatch(const File& configFilename, long delay); /** Read configuration options from properties. See #doConfigure(const File&, log4cxx::spi::LoggerRepositoryPtr&) for the expected format. */ static void configure(helpers::Properties& properties); /** Read configuration options from properties. See #doConfigure(const File&, log4cxx::spi::LoggerRepositoryPtr&) for the expected format. */ void doConfigure(helpers::Properties& properties, spi::LoggerRepositoryPtr hierarchy); // -------------------------------------------------------------------------- // Internal stuff // -------------------------------------------------------------------------- protected: /** Check the provided Properties object for a #loggerFactory entry specified by LOGGER_FACTORY_KEY. 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 #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_PROPERTY_CONFIGURATOR_H apache-log4cxx-0.12.1/src/main/include/log4cxx/provisionnode.h000644 001750 001750 00000002166 14120250671 025036 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/dailyrollingfileappender.h000644 001750 001750 00000014466 14120250670 027215 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _LOG4CXX_DAILYROLLINGFILEAPPENDER_H #define _LOG4CXX_DAILYROLLINGFILEAPPENDER_H #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include namespace log4cxx { namespace helpers { class Pool; } namespace spi { class ErrorHandler; typedef std::shared_ptr ErrorHandlerPtr; } /** DailyRollingFileAppender extends {@link log4cxx::FileAppender FileAppender} so that the underlying file is rolled over at a user chosen frequency.

The rolling schedule is specified by the DatePattern option. This pattern should follow the {@link log4cxx::helpers::SimpleDateFormat SimpleDateFormat} conventions. In particular, you must escape literal text within a pair of single quotes. A formatted version of the date pattern is used as the suffix for the rolled file name.

For example, if the File option is set to /foo/bar.log and the DatePattern set to '.'yyyy-MM-dd, on 2001-02-16 at midnight, the logging file /foo/bar.log will be copied to /foo/bar.log.2001-02-16 and logging for 2001-02-17 will continue in /foo/bar.log until it rolls over the next day.

Is is possible to specify monthly, weekly, half-daily, daily, hourly, or minutely rollover schedules.

DatePattern Rollover schedule Example
'.'yyyy-MM Rollover at the beginning of each month At midnight of May 31st, 2002 /foo/bar.log will be copied to /foo/bar.log.2002-05. Logging for the month of June will be output to /foo/bar.log until it is also rolled over the next month.
'.'yyyy-ww Rollover at the first day of each week. The first day of the week depends on the locale. Assuming the first day of the week is Sunday, on Saturday midnight, June 9th 2002, the file /foo/bar.log will be copied to /foo/bar.log.2002-23. Logging for the 24th week of 2002 will be output to /foo/bar.log until it is rolled over the next week.
'.'yyyy-MM-dd Rollover at midnight each day. At midnight, on March 8th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-08. Logging for the 9th day of March will be output to /foo/bar.log until it is rolled over the next day.
'.'yyyy-MM-dd-a Rollover at midnight and midday of each day. At noon, on March 9th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-09-AM. Logging for the afternoon of the 9th will be output to /foo/bar.log until it is rolled over at midnight.
'.'yyyy-MM-dd-HH Rollover at the top of every hour. At approximately 11:00.000 o'clock on March 9th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-09-10. Logging for the 11th hour of the 9th of March will be output to /foo/bar.log until it is rolled over at the beginning of the next hour.
'.'yyyy-MM-dd-HH-mm Rollover at the beginning of every minute. At approximately 11:23,000, on March 9th, 2001, /foo/bar.log will be copied to /foo/bar.log.2001-03-09-10-22. Logging for the minute of 11:23 (9th of March) will be output to /foo/bar.log until it is rolled over the next minute.

Do not use the colon ":" character in anywhere in the DatePattern option. The text before the colon is interpeted as the protocol specificaion of a URL which is probably not what you want. */ class LOG4CXX_EXPORT DailyRollingFileAppender : public log4cxx::rolling::RollingFileAppenderSkeleton { DECLARE_LOG4CXX_OBJECT(DailyRollingFileAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(DailyRollingFileAppender) LOG4CXX_CAST_ENTRY_CHAIN(FileAppender) END_LOG4CXX_CAST_MAP() /** The date pattern used to initiate rollover. */ LogString datePattern; public: /** The default constructor simply calls its {@link FileAppender#FileAppender parents constructor}. */ DailyRollingFileAppender(); /** Instantiate a DailyRollingFileAppender and open the file designated by filename. The opened filename will become the ouput destination for this appender. */ DailyRollingFileAppender( const LayoutPtr& layout, const LogString& filename, const LogString& datePattern); /** 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); /** Returns the value of the DatePattern option. */ LogString getDatePattern() const; void setOption(const LogString& option, const LogString& value); /** * Prepares DailyRollingFileAppender for use. */ void activateOptions(log4cxx::helpers::Pool&); }; LOG4CXX_PTR_DEF(DailyRollingFileAppender); } #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/log4cxx.hw000644 001750 001750 00000006343 14120250671 023720 0ustar00robertrobert000000 000000 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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.hw instead * */ #define LOG4CXX_LOGCHAR_IS_UTF8 0 #if LOG4CXX_LOGCHAR_IS_UTF8 #define LOG4CXX_LOGCHAR_IS_WCHAR 0 #else #define LOG4CXX_LOGCHAR_IS_WCHAR 1 #endif #define LOG4CXX_LOGCHAR_IS_UNICHAR 0 #define LOG4CXX_CHAR_API 1 #define LOG4CXX_WCHAR_T_API 1 #define LOG4CXX_UNICHAR_API 0 #define LOG4CXX_CFSTRING_API 0 #if defined(_MSC_VER) typedef __int64 log4cxx_int64_t; #if _MSC_VER < 1300 #define LOG4CXX_USE_GLOBAL_SCOPE_TEMPLATE 1 #define LOG4CXX_LOGSTREAM_ADD_NOP 1 #endif #elif defined(__BORLANDC__) typedef __int64 log4cxx_int64_t; #else typedef long long log4cxx_int64_t; #endif typedef log4cxx_int64_t log4cxx_time_t; typedef int log4cxx_status_t; typedef unsigned int log4cxx_uint32_t; // definitions used when using static library #if defined(LOG4CXX_STATIC) #define LOG4CXX_EXPORT // definitions used when building DLL #elif defined(LOG4CXX) #define LOG4CXX_EXPORT __declspec(dllexport) #else // definitions used when using DLL #define LOG4CXX_EXPORT __declspec(dllimport) #endif // // pointer and list definition macros when building DLL using VC // #if defined(_MSC_VER) && !defined(LOG4CXX_STATIC) && defined(LOG4CXX) #define LOG4CXX_PTR_DEF(T) \ template class LOG4CXX_EXPORT log4cxx::helpers::ObjectPtrT; \ typedef log4cxx::helpers::ObjectPtrT T##Ptr #define LOG4CXX_LIST_DEF(N, T) \ template class LOG4CXX_EXPORT std::allocator; \ template class LOG4CXX_EXPORT std::vector; \ typedef std::vector N // // pointer and list definition macros when linking with DLL using VC // #elif defined(_MSC_VER) && !defined(LOG4CXX_STATIC) #define LOG4CXX_PTR_DEF(T) \ __pragma(warning(push)) \ __pragma(warning(disable: 4231)) \ extern template class LOG4CXX_EXPORT log4cxx::helpers::ObjectPtrT; \ typedef log4cxx::helpers::ObjectPtrT T##Ptr \ __pragma(warning(pop)) #define LOG4CXX_LIST_DEF(N, T) \ __pragma(warning(push)) \ __pragma(warning(disable: 4231)) \ extern template class LOG4CXX_EXPORT std::allocator; \ extern template class LOG4CXX_EXPORT std::vector; \ typedef std::vector N \ __pragma(warning(pop)) // // pointer and list definition macros for all other cases // #else #define LOG4CXX_PTR_DEF(T) typedef log4cxx::helpers::ObjectPtrT T##Ptr #define LOG4CXX_LIST_DEF(N, T) typedef std::vector N #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/net/000755 001750 001750 00000000000 14122472745 022562 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/net/smtpappender.h000644 001750 001750 00000017130 14120250671 025425 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif namespace log4cxx { namespace net { /** Send an e-mail when a specific logging event occurs, typically on errors or fatal errors.

The number of logging events delivered in this e-mail depend on the value of BufferSize option. 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. */ class LOG4CXX_EXPORT SMTPAppender : public AppenderSkeleton { private: private: 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(); 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; 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 */ virtual void setOption(const LogString& option, const LogString& value); /** Activate the specified options, such as the smtp host, the recipient, from, etc. */ virtual void activateOptions(log4cxx::helpers::Pool& 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. */ virtual void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p); virtual void close(); /** 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 {@link Layout layout}. */ virtual bool requiresLayout() const; /** 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. */ inline int getBufferSize() const { return bufferSize; } /** * 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 #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_NET_SMTP_H apache-log4cxx-0.12.1/src/main/include/log4cxx/net/socketappender.h000644 001750 001750 00000011564 14120250671 025737 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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_H #define _LOG4CXX_NET_SOCKET_APPENDER_H #include #include namespace log4cxx { namespace net { /** Sends {@link log4cxx::spi::LoggingEvent LoggingEvent} objects to a remote a log server, usually Apache Chainsaw.

The SocketAppender has the following properties: - If sent to Apache Chainsaw, remote logging is non-intrusive as far as the log event is concerned. In other words, the event will be logged with the same time stamp, {@link NDC NDC}, location info as if it were logged locally by the client. - SocketAppenders do not use a layout. They ship a serialized {@link log4cxx::spi::LoggingEvent LoggingEvent} object to the server side. - 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 a SocketAppender 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 SocketAppender explicitly. See also next item. @n @n Long lived applications which create/destroy many SocketAppender instances should be aware of this destruction problem. Most other applications can safely ignore it. - If the application hosting the SocketAppender exits before the SocketAppender 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 SocketAppender either explicitly or by calling the LogManager#shutdown method before exiting the application. */ class LOG4CXX_EXPORT SocketAppender : 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; DECLARE_LOG4CXX_OBJECT(SocketAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(SocketAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() SocketAppender(); ~SocketAppender(); /** Connects to remote server at address and port. */ SocketAppender(helpers::InetAddressPtr& address, int port); /** Connects to remote server at host and port. */ SocketAppender(const LogString& host, int port); protected: virtual void setSocket(log4cxx::helpers::SocketPtr& socket, log4cxx::helpers::Pool& p); virtual void cleanUp(log4cxx::helpers::Pool& p); virtual int getDefaultDelay() const; virtual int getDefaultPort() const; void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool); private: log4cxx::helpers::ObjectOutputStreamPtr oos; }; // class SocketAppender LOG4CXX_PTR_DEF(SocketAppender); } // namespace net } // namespace log4cxx #endif // _LOG4CXX_NET_SOCKET_APPENDER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/net/sockethubappender.h000644 001750 001750 00000014633 14120250671 026436 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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_HUB_APPENDER_H #define _LOG4CXX_NET_SOCKET_HUB_APPENDER_H #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include namespace log4cxx { namespace helpers { class ObjectOutputStream; typedef std::shared_ptr ObjectOutputStreamPtr; } namespace net { LOG4CXX_LIST_DEF(ObjectOutputStreamList, log4cxx::helpers::ObjectOutputStreamPtr); /** Sends {@link log4cxx::spi::LoggingEvent LoggingEvent} objects to a set of remote log servers, usually a SocketNode.

Acts just like SocketAppender except that instead of connecting to a given remote log server, SocketHubAppender accepts connections from the remote log servers as clients. It can accept more than one connection. When a log event is received, the event is sent to the set of currently connected remote log servers. Implemented this way it does not require any update to the configuration file to send data to another remote log server. The remote log server simply connects to the host and port the SocketHubAppender is running on.

The SocketHubAppender does not store events such that the remote side will events that arrived after the establishment of its connection. Once connected, events arrive in order as guaranteed by the TCP protocol.

This implementation borrows heavily from the SocketAppender.

The SocketHubAppender has the following characteristics: - If sent to a SocketNode, logging is non-intrusive as far as the log event is concerned. In other words, the event will be logged with the same time stamp, NDC, location info as if it were logged locally. - SocketHubAppender does not use a layout. It ships a serialized spi::LoggingEvent object to the remote side. - SocketHubAppender relies on the TCP protocol. Consequently, if the remote side is reachable, then log events will eventually arrive at remote client. - If no remote clients are attached, the logging requests are simply dropped. - Logging events are automatically buffered by the native TCP implementation. This means that if the link to remote client is slow but still faster than the rate of (log) event production, the application will not be affected by the slow network connection. However, if the network connection is slower then the rate of event production, then the local application can only progress at the network rate. In particular, if the network link to the the remote client is down, the application will be blocked. @n @n On the other hand, if the network link is up, but the remote client is down, the client will not be blocked when making log requests but the log events will be lost due to client unavailability. @n @n The single remote client case extends to multiple clients connections. The rate of logging will be determined by the slowest link. - If the application hosting the SocketHubAppender exits before the SocketHubAppender is closed either explicitly or subsequent to garbage collection, then there might be untransmitted data in the pipe which might be lost. This is a common problem on Windows based systems. @n @n To avoid lost data, it is usually sufficient to #close the SocketHubAppender either explicitly or by calling the LogManager#shutdown method before exiting the application. */ class LOG4CXX_EXPORT SocketHubAppender : public AppenderSkeleton { private: /** The default port number of the ServerSocket will be created on. */ static int DEFAULT_PORT; int port; ObjectOutputStreamList streams; bool locationInfo; public: DECLARE_LOG4CXX_OBJECT(SocketHubAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(SocketHubAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() SocketHubAppender(); ~SocketHubAppender(); /** Connects to remote server at address and port. */ SocketHubAppender(int port) ; /** Set up the socket server on the specified port. */ virtual void activateOptions(log4cxx::helpers::Pool& p); /** Set options */ virtual void setOption(const LogString& option, const LogString& value); virtual void close(); /** Append an event to all of current connections. */ virtual void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p); /** The SocketHubAppender does not use a layout. Hence, this method returns false. */ virtual bool requiresLayout() const { return false; } /** The Port option takes a positive integer representing the port where the server is waiting for connections. */ inline void setPort(int port1) { this->port = port1; } /** Returns value of the Port option. */ inline int getPort() const { return port; } /** 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. */ inline void setLocationInfo(bool locationInfo1) { this->locationInfo = locationInfo1; } /** Returns value of the LocationInfo option. */ inline bool getLocationInfo() const { return locationInfo; } /** Start the ServerMonitor thread. */ private: void startServer(); std::thread thread; void monitor(); }; // class SocketHubAppender LOG4CXX_PTR_DEF(SocketHubAppender); } // namespace net } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_NET_SOCKET_HUB_APPENDER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/net/telnetappender.h000644 001750 001750 00000010436 14120250671 025737 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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; int port; 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). */ virtual bool requiresLayout() const { 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(log4cxx::helpers::Pool& p); /** Set options */ virtual void setOption(const LogString& option, const LogString& value); /** Returns value of the Port option. */ int getPort() const { return port; } /** The Port option takes a positive integer representing the port where the server is waiting for connections. */ void setPort(int port1) { this->port = port1; } /** shuts down the appender. */ void close(); protected: /** Handles a log event. For this appender, that means writing the message to each connected client. */ virtual void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) ; //---------------------------------------------------------- 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); ConnectionList connections; LogString encoding; log4cxx::helpers::CharsetEncoderPtr encoder; helpers::ServerSocket* serverSocket; std::thread sh; size_t activeConnections; void acceptConnections(); }; // class TelnetAppender LOG4CXX_PTR_DEF(TelnetAppender); } // namespace net } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_NET_TELNET_APPENDER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/net/syslogappender.h000644 001750 001750 00000012275 14120250671 025767 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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(); /** 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, log4cxx::helpers::Pool& p); /** This method returns immediately as options are activated when they are set. */ void activateOptions(log4cxx::helpers::Pool& p); void setOption(const LogString& option, const LogString& value); /** The SyslogAppender requires a layout. Hence, this method returns true. */ virtual bool requiresLayout() const { 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. */ inline const LogString& getSyslogHost() const { return syslogHost; } /** 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. */ inline LogString getFacility() const { return getFacilityString(syslogFacility); } /** If the FacilityPrinting option is set to true, the printed message will include the facility name of the application. It is false by default. */ inline void setFacilityPrinting(bool facilityPrinting1) { this->facilityPrinting = facilityPrinting1; } /** Returns the value of the FacilityPrinting option. */ inline bool getFacilityPrinting() const { return facilityPrinting; } inline void setMaxMessageLength(int maxMessageLength1) { maxMessageLength = maxMessageLength1; } inline int getMaxMessageLength() const { return maxMessageLength; } protected: void initSyslogFacilityStr(); int syslogFacility; // Have LOG_USER as default LogString facilityStr; bool facilityPrinting; helpers::SyslogWriter* sw; LogString syslogHost; int syslogHostPort; int maxMessageLength; private: SyslogAppender(const SyslogAppender&); SyslogAppender& operator=(const SyslogAppender&); }; // class SyslogAppender LOG4CXX_PTR_DEF(SyslogAppender); } // namespace net } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_NET_SYSLOG_APPENDER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/net/socketappenderskeleton.h000644 001750 001750 00000012177 14120250671 027505 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #include #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif namespace log4cxx { namespace net { /** * Abstract base class for SocketAppender and XMLSocketAppender */ class LOG4CXX_EXPORT SocketAppenderSkeleton : public AppenderSkeleton { private: /** host name */ LogString remoteHost; /** IP address */ helpers::InetAddressPtr address; int port; int reconnectionDelay; bool locationInfo; 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(log4cxx::helpers::Pool& p); void close(); /** * This appender does not use a layout. Hence, this method * returns false. * */ bool requiresLayout() const { 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. * */ inline void setRemoteHost(const LogString& host) { address = helpers::InetAddress::getByName(host); remoteHost.assign(host); } /** Returns value of the RemoteHost option. */ inline const LogString& getRemoteHost() const { return remoteHost; } /** The Port option takes a positive integer representing the port where the server is waiting for connections. */ void setPort(int port1) { this->port = port1; } /** Returns value of the Port option. */ int getPort() const { return port; } /** 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) { this->locationInfo = locationInfo1; } /** Returns value of the LocationInfo option. */ bool getLocationInfo() const { return locationInfo; } /** 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) { this->reconnectionDelay = reconnectionDelay1; } /** Returns value of the ReconnectionDelay option. */ int getReconnectionDelay() const { return reconnectionDelay; } void fireConnector(); void setOption(const LogString& option, const LogString& value); protected: 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. */ std::thread thread; std::condition_variable interrupt; std::mutex interrupt_mutex; void monitor(); bool is_closed(); SocketAppenderSkeleton(const SocketAppenderSkeleton&); SocketAppenderSkeleton& operator=(const SocketAppenderSkeleton&); }; // class SocketAppenderSkeleton } // namespace net } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_NET_SOCKET_APPENDER_SKELETON_H apache-log4cxx-0.12.1/src/main/include/log4cxx/net/xmlsocketappender.h000644 001750 001750 00000012277 14120250671 026462 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 {@link log4cxx::spi::LoggingEvent LoggingEvent} objects in XML format to a remote a log server, usually a XMLSocketNode.

The XMLSocketAppender has the following properties: - If sent to a XMLSocketNode, remote logging is non-intrusive as far as the log event is concerned. In other words, the event will be logged with the same time stamp, {@link NDC NDC}, location info as if it were logged locally by the client. - XMLSocketAppenders use exclusively an XMLLayout. They ship an XML stream representing a {@link spi::LoggingEvent LoggingEvent} object to the server side. - 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; /** An event XML stream cannot exceed 1024 bytes. */ 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: virtual void setSocket(log4cxx::helpers::SocketPtr& socket, log4cxx::helpers::Pool& p); virtual void cleanUp(log4cxx::helpers::Pool& p); virtual int getDefaultDelay() const; virtual int getDefaultPort() const; void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool); private: log4cxx::helpers::WriterPtr writer; // prevent copy and assignment statements XMLSocketAppender(const XMLSocketAppender&); XMLSocketAppender& operator=(const XMLSocketAppender&); }; // class XMLSocketAppender LOG4CXX_PTR_DEF(XMLSocketAppender); } // namespace net } // namespace log4cxx #endif // _LOG4CXX_NET_XML_SOCKET_APPENDER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/filter/000755 001750 001750 00000000000 14122472745 023261 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/filter/levelrangefilter.h000644 001750 001750 00000010210 14120250670 026743 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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: /** 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; 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(); /** Set options */ virtual void setOption(const LogString& option, const LogString& value); /** Set the LevelMin option. */ void setLevelMin(const LevelPtr& levelMin1) { this->levelMin = levelMin1; } /** Get the value of the LevelMin option. */ const LevelPtr& getLevelMin() const { return levelMin; } /** Set the LevelMax option. */ void setLevelMax(const LevelPtr& levelMax1) { this->levelMax = levelMax1; } /** Get the value of the LevelMax option. */ const LevelPtr& getLevelMax() const { return levelMax; } /** Set the AcceptOnMatch option. */ inline void setAcceptOnMatch(bool acceptOnMatch1) { this->acceptOnMatch = acceptOnMatch1; } /** Get the value of the AcceptOnMatch option. */ inline bool getAcceptOnMatch() const { return acceptOnMatch; } /** 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; }; // class LevelRangeFilter LOG4CXX_PTR_DEF(LevelRangeFilter); } // namespace filter } // namespace log4cxx #endif // _LOG4CXX_FILTER_LEVEL_RANGE_FILTER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/filter/levelmatchfilter.h000644 001750 001750 00000006112 14120250670 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. */ #ifndef _LOG4CXX_FILTER_LEVEL_MATCH_FILTER_H #define _LOG4CXX_FILTER_LEVEL_MATCH_FILTER_H #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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: bool acceptOnMatch; LevelPtr levelToMatch; 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(); /** Set options */ virtual void setOption(const LogString& option, const LogString& value); void setLevelToMatch(const LogString& levelToMatch); LogString getLevelToMatch() const; inline void setAcceptOnMatch(bool acceptOnMatch1) { this->acceptOnMatch = acceptOnMatch1; } inline bool getAcceptOnMatch() const { return acceptOnMatch; } /** 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; }; // class LevelMatchFilter LOG4CXX_PTR_DEF(LevelMatchFilter); } // namespace filter } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_FILTER_LEVEL_MATCH_FILTER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/filter/locationinfofilter.h000644 001750 001750 00000005315 14120250670 027315 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 rule { class ExpressionRule; class Rule; typedef helpers::ObjectPtrT < Rule > RulePtr; typedef helpers::ObjectPtrT < ExpressionRule > ExpressionRulePtr; } namespace filter { /** * Location information is usually specified at the appender level - all events associated * with an appender either create and parse stack traces or they do not. This is * an expensive operation and in some cases not needed for all events associated with * an appender. * * This filter creates event-level location information only if the provided expression evaluates to true. * * For information on expression syntax, see org.apache.log4j.rule.ExpressionRule * * */ class LOG4CXX_EXPORT LocationInfoFilter: public log4cxx::spi::Filter { bool convertInFixToPostFix; LogString expression; log4cxx::rule::RulePtr expressionRule; //HACK: Category is the last of the internal layers - pass this in as the class name //in order for parsing to work correctly LogString className; public: DECLARE_LOG4CXX_OBJECT(LocationInfoFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(log4cxx::spi::Filter) END_LOG4CXX_CAST_MAP() LocationInfoFilter(); void activateOptions(log4cxx::helpers::Pool&); void setExpression(const LogString& expression); LogString getExpression() const; void setConvertInFixToPostFix(bool convertInFixToPostFix); bool getConvertInFixToPostFix() const; /** * 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; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/filter/loggermatchfilter.h000644 001750 001750 00000006344 14120250670 027130 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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: bool acceptOnMatch; LogString loggerToMatch; 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(); /** Set options */ virtual void setOption(const LogString& option, const LogString& value); void setLoggerToMatch(const LogString& levelToMatch); LogString getLoggerToMatch() const; inline void setAcceptOnMatch(bool acceptOnMatch1) { this->acceptOnMatch = acceptOnMatch1; } inline bool getAcceptOnMatch() const { return acceptOnMatch; } /** 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; }; // class LoggerMatchFilter LOG4CXX_PTR_DEF(LoggerMatchFilter); } // namespace filter } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_FILTER_LOGGER_MATCH_FILTER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/filter/denyallfilter.h000644 001750 001750 00000004210 14120250670 026252 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 { return spi::Filter::DENY; } }; // class DenyAllFilter LOG4CXX_PTR_DEF(DenyAllFilter); } // namespace filter } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_FILTER_DENY_ALL_FILTER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/filter/andfilter.h000644 001750 001750 00000006667 14120250670 025406 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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: log4cxx::spi::FilterPtr headFilter; log4cxx::spi::FilterPtr tailFilter; bool acceptOnMatch; 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(); void addFilter(const log4cxx::spi::FilterPtr& filter); void setAcceptOnMatch(bool acceptOnMatch); FilterDecision decide(const spi::LoggingEventPtr& event) const; }; LOG4CXX_PTR_DEF(AndFilter); } } #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/filter/stringmatchfilter.h000644 001750 001750 00000006166 14120250670 027161 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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: bool acceptOnMatch; LogString stringToMatch; 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(); /** Set options */ virtual void setOption(const LogString& option, const LogString& value); inline void setStringToMatch(const LogString& stringToMatch1) { this->stringToMatch.assign(stringToMatch1); } inline const LogString& getStringToMatch() const { return stringToMatch; } inline void setAcceptOnMatch(bool acceptOnMatch1) { this->acceptOnMatch = acceptOnMatch1; } inline bool getAcceptOnMatch() const { return acceptOnMatch; } /** Returns {@link log4cxx::spi::Filter#NEUTRAL NEUTRAL} is there is no string match. */ FilterDecision decide(const spi::LoggingEventPtr& event) const; }; // class StringMatchFilter LOG4CXX_PTR_DEF(StringMatchFilter); } // namespace filter } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_FILTER_STRING_MATCH_FILTER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/filter/propertyfilter.h000644 001750 001750 00000004370 14120250670 026515 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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; }; } } #if defined(_MSC_VER) #pragma warning (pop) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/filter/mapfilter.h000644 001750 001750 00000005737 14120250670 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_FILTER_MAPFILTER_H #define _LOG4CXX_FILTER_MAPFILTER_H #include #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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: bool acceptOnMatch; bool mustMatchAll; // true = AND; false = OR KeyVals keyVals; 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(); /** Set options */ virtual void setOption(const LogString& option, const LogString& value); inline void setKeyValue(const LogString& strKey, const LogString& strValue) { this->keyVals[strKey] = strValue; } inline const LogString& getValue(const LogString& strKey) const { static const LogString empty; const KeyVals::const_iterator it(this->keyVals.find(strKey)); return (it != keyVals.end() ? it->second : empty); } inline void setAcceptOnMatch(bool acceptOnMatch1) { this->acceptOnMatch = acceptOnMatch1; } inline bool getAcceptOnMatch() const { return acceptOnMatch; } inline bool getMustMatchAll() const { return mustMatchAll; } inline void setMustMatchAll(bool mustMatchAll1) { this->mustMatchAll = mustMatchAll1; } /** Returns {@link log4cxx::spi::Filter#NEUTRAL NEUTRAL} is there is no string match. */ FilterDecision decide(const spi::LoggingEventPtr& event) const; }; // class MapFilter LOG4CXX_PTR_DEF(MapFilter); } // namespace filter } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_FILTER_MAPFILTER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/filter/expressionfilter.h000644 001750 001750 00000007700 14120250670 027030 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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; LogString expression; log4cxx::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(log4cxx::helpers::Pool& p); 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; }; } } #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/db/000755 001750 001750 00000000000 14122472745 022361 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/db/odbcappender.h000644 001750 001750 00000020322 14120250670 025144 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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); }; /**

WARNING: This version of ODBCAppender is very likely to be completely replaced in the future. Moreoever, it does not log exceptions.

The ODBCAppender provides for sending log events to a database.

Each append call adds to an ArrayList buffer. When the buffer is filled each log event is placed in a sql statement (configurable) and executed. BufferSize, db URL, User, & Password are configurable options in the standard log4j ways.

The setSql(String sql) sets the SQL statement to be used for logging -- this statement is sent to a PatternLayout (either created automaticly by the appender or added by the user). Therefore by default all the conversion patterns in PatternLayout can be used inside of the statement. (see the test cases for examples)

Overriding the {@link #getLogStatement} method allows more explicit control of the statement used for logging.

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.
  • Override getLogStatement to produce specialized or dynamic statements. The default uses the sql option value.
*/ class LOG4CXX_EXPORT ODBCAppender : public AppenderSkeleton { protected: /** * 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; typedef void* SQLHDBC; typedef void* SQLHENV; typedef void* SQLHANDLE; typedef short SQLSMALLINT; /** * 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 * statement, eg: insert into LogTable (Thread, File, Message) values * ("%t", "%F", "%m") * * Be careful of quotes in your messages! * * Also see PatternLayout. */ 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::list buffer; public: DECLARE_LOG4CXX_OBJECT(ODBCAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ODBCAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() ODBCAppender(); virtual ~ODBCAppender(); /** Set options */ virtual void setOption(const LogString& option, const LogString& value); /** Activate the specified options. */ virtual void activateOptions(log4cxx::helpers::Pool& p); /** * Adds the event to the buffer. When full the buffer is flushed. */ void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool&); /** * By default getLogStatement sends the event to the required Layout object. * The layout will format the given pattern into a workable SQL string. * * Overriding this provides direct access to the LoggingEvent * when constructing the logging statement. * */ protected: LogString getLogStatement(const spi::LoggingEventPtr& event, helpers::Pool& p) const; /** * * Override this to provide an alertnate method of getting * connections (such as caching). One method to fix this is to open * connections at the start of flushBuffer() and close them at the * end. I use a connection pool outside of ODBCAppender which is * accessed in an override of this method. * */ 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: virtual void close(); /** * 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); /** * ODBCAppender requires a layout. * */ virtual bool requiresLayout() const { return true; } /** * 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") */ inline const LogString& getSql() const { return sqlStatement; } inline void setUser(const LogString& user) { databaseUser = user; } inline void setURL(const LogString& url) { databaseURL = url; } inline void setPassword(const LogString& password) { databasePassword = password; } inline void setBufferSize(size_t newBufferSize) { bufferSize = newBufferSize; } inline const LogString& getUser() const { return databaseUser; } inline const LogString& getURL() const { return databaseURL; } inline const LogString& getPassword() const { return databasePassword; } inline size_t getBufferSize() const { return bufferSize; } 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); }; // class ODBCAppender LOG4CXX_PTR_DEF(ODBCAppender); } // namespace db } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_DB_ODBC_APPENDER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/config/000755 001750 001750 00000000000 14122472745 023241 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/config/propertysetter.h000644 001750 001750 00000006412 14120250670 026515 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; typedef std::shared_ptr ObjectPtr; 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-0.12.1/src/main/include/log4cxx/private/000755 001750 001750 00000000000 14122472745 023446 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/private/log4cxx_private.hw000644 001750 001750 00000004150 14120250671 027116 0ustar00robertrobert000000 000000 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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.h * * You must modify log4cxx.hw instead. * * * This is the Win32 specific version of log4cxx.h. */ #include #if !defined(LOG4CXX) && !defined(LOG4CXX_TEST) #error "log4cxx/private/log4cxx.h should only be used within log4cxx and tests implementation" #endif #if !defined(__BORLANDC__) #define LOG4CXX_RETURN_AFTER_THROW 1 #else #define LOG4CXX_RETURN_AFTER_THROW 0 #endif #if defined(_WIN32_WCE) #define LOG4CXX_HAS_STD_LOCALE 0 #else #define LOG4CXX_HAS_STD_LOCALE 1 #endif #define LOG4CXX_FORCE_WIDE_CONSOLE 1 #define LOG4CXX_FORCE_BYTE_CONSOLE 0 #if defined(_MSC_VER) #define LOG4CXX_MEMSET_IOS_BASE 1 #endif #if !defined(_WIN32_WCE) #define LOG4CXX_HAVE_ODBC 1 #if defined(__BORLANDC__) #define LOG4CXX_HAS_MBSRTOWCS 0 #else #define LOG4CXX_HAS_MBSRTOWCS 1 #endif #else #define LOG4CXX_HAVE_ODBC 0 #define LOG4CXX_HAS_MBSRTOWCS 0 #endif #define LOG4CXX_HAS_FWIDE 1 #define LOG4CXX_HAS_WCSTOMBS 1 #define LOG4CXX_CHARSET_UTF8 0 #define LOG4CXX_CHARSET_ISO88591 0 #define LOG4CXX_CHARSET_USASCII 0 #define LOG4CXX_CHARSET_EBCDIC 0 #define LOG4CXX_HAVE_LIBESMTP 0 #define LOG4CXX_HAVE_SYSLOG 0 #define LOG4CXX_WIN32_THREAD_FMTSPEC "0x%.8x" #define LOG4CXX_APR_THREAD_FMTSPEC "0x%pt" #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/private/log4cxx_private.h.in000644 001750 001750 00000004402 14122472113 027333 0ustar00robertrobert000000 000000 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #define LOG4CXX_MEMSET_IOS_BASE 0 #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" #ifdef __BORLANDC__ /* * embarcadero/RAD Studio compilers don't support thread_local: * http://docwiki.embarcadero.com/RADStudio/Sydney/en/Modern_C%2B%2B_Language_Features_Compliance_Status */ #define LOG4CXX_THREAD_LOCAL #else #define LOG4CXX_THREAD_LOCAL thread_local #endif #if defined(_MSC_VER) #define LOG4CXX_MEMSET_IOS_BASE 1 #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/xml/000755 001750 001750 00000000000 14122472745 022574 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/xml/domconfigurator.h000644 001750 001750 00000021664 14120250671 026146 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 { 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 void configure(const std::string& filename); #if LOG4CXX_WCHAR_T_API static void configure(const std::wstring& filename); #endif #if LOG4CXX_UNICHAR_API static void configure(const std::basic_string& filename); #endif #if LOG4CXX_CFSTRING_API static void 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 void configureAndWatch(const std::string& configFilename); #if LOG4CXX_WCHAR_T_API static void configureAndWatch(const std::wstring& configFilename); #endif #if LOG4CXX_UNICHAR_API static void configureAndWatch(const std::basic_string& configFilename); #endif #if LOG4CXX_CFSTRING_API static void 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 void configureAndWatch(const std::string& configFilename, long delay); #if LOG4CXX_WCHAR_T_API static void configureAndWatch(const std::wstring& configFilename, long delay); #endif #if LOG4CXX_UNICHAR_API static void configureAndWatch(const std::basic_string& configFilename, long delay); #endif #if LOG4CXX_CFSTRING_API static void 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. */ void doConfigure(const File& filename, spi::LoggerRepositoryPtr repository); protected: static LogString getAttribute( log4cxx::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem*, const std::string& attrName); LogString subst(const LogString& value); protected: helpers::Properties props; spi::LoggerRepositoryPtr repository; spi::LoggerFactoryPtr loggerFactory; private: // prevent assignment or copy statements DOMConfigurator(const DOMConfigurator&); DOMConfigurator& operator=(const DOMConfigurator&); static XMLWatchdog* xdog; }; LOG4CXX_PTR_DEF(DOMConfigurator); } // namespace xml } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_XML_DOM_CONFIGURATOR_H apache-log4cxx-0.12.1/src/main/include/log4cxx/xml/xmllayout.h000644 001750 001750 00000007262 14120250671 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. */ #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: // Print no location info by default bool locationInfo; //= false bool properties; // = false public: DECLARE_LOG4CXX_OBJECT(XMLLayout) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(XMLLayout) LOG4CXX_CAST_ENTRY_CHAIN(Layout) END_LOG4CXX_CAST_MAP() 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. */ inline void setLocationInfo(bool locationInfo1) { this->locationInfo = locationInfo1; } /** Returns the current value of the LocationInfo option. */ inline bool getLocationInfo() const { return locationInfo; } /** * Sets whether MDC key-value pairs should be output, default false. * @param flag new value. * */ inline void setProperties(bool flag) { properties = flag; } /** * Gets whether MDC key-value pairs should be output. * @return true if MDC key-value pairs are output. * */ inline bool getProperties() { return properties; } /** No options to activate. */ void activateOptions(log4cxx::helpers::Pool& /* p */) { } /** Set options */ virtual void setOption(const LogString& option, const LogString& value); /** * Formats a {@link spi::LoggingEvent LoggingEvent} * in conformance with the log4cxx.dtd. **/ virtual void format(LogString& output, const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) const; /** The XMLLayout prints and does not ignore exceptions. Hence the return value false. */ virtual bool ignoresThrowable() const { return false; } }; // class XMLLayout LOG4CXX_PTR_DEF(XMLLayout); } // namespace xml } // namespace log4cxx #endif // _LOG4CXX_XML_LAYOUT_H apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/000755 001750 001750 00000000000 14122472745 023442 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/filerenameaction.h000644 001750 001750 00000003116 14120250671 027107 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { const File source; const File destination; bool renameEmptyFile; 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. */ virtual bool execute(log4cxx::helpers::Pool& pool) const; }; LOG4CXX_PTR_DEF(FileRenameAction); } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/zipcompressaction.h000644 001750 001750 00000003547 14120250671 027366 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include namespace log4cxx { namespace rolling { class ZipCompressAction : public Action { const File source; const File destination; bool deleteSource; 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. */ virtual bool execute(log4cxx::helpers::Pool& pool) const; private: ZipCompressAction(const ZipCompressAction&); ZipCompressAction& operator=(const ZipCompressAction&); }; LOG4CXX_PTR_DEF(ZipCompressAction); } #if defined(_MSC_VER) #pragma warning ( pop ) #endif } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/timebasedrollingpolicy.h000755 001750 001750 00000022522 14120250671 030353 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #include #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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 RollingPolicyBase, public 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: /** * Time for next determination if time for rollover. */ log4cxx_time_t nextCheck; /** * File name at last rollover. */ LogString lastFileName; /** * 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; /** * Length of any file type suffix (.gz, .zip). */ int suffixLength; public: TimeBasedRollingPolicy(); void activateOptions(log4cxx::helpers::Pool& ); #ifdef LOG4CXX_MULTI_PROCESS virtual ~TimeBasedRollingPolicy(); /** * 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); #endif /** * {@inheritDoc} */ RolloverDescriptionPtr initialize( const LogString& currentActiveFile, const bool append, log4cxx::helpers::Pool& pool); /** * {@inheritDoc} */ RolloverDescriptionPtr rollover( const LogString& currentActiveFile, const bool append, log4cxx::helpers::Pool& pool); /** * 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 log4cxx::spi::LoggingEventPtr& event, const LogString& filename, size_t fileLength); protected: log4cxx::pattern::PatternMap getFormatSpecifiers() const; }; LOG4CXX_PTR_DEF(TimeBasedRollingPolicy); } } #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/rollingfileappenderskeleton.h000644 001750 001750 00000011475 14120250671 031403 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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_SKELETON_H) #define _LOG4CXX_ROLLING_ROLLING_FILE_APPENDER_SKELETON_H #include #include #include #include #include #include namespace log4cxx { namespace rolling { /** * Base class for log4cxx::rolling::RollingFileAppender and log4cxx::RollingFileAppender * (analogues of org.apache.log4j.rolling.RFA from extras companion and * org.apache.log4j.RFA from log4j 1.2, respectively). * * */ class LOG4CXX_EXPORT RollingFileAppenderSkeleton : public FileAppender { DECLARE_LOG4CXX_OBJECT(RollingFileAppenderSkeleton) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(RollingFileAppenderSkeleton) LOG4CXX_CAST_ENTRY_CHAIN(FileAppender) END_LOG4CXX_CAST_MAP() /** * Triggering policy. */ TriggeringPolicyPtr triggeringPolicy; /** * Rolling policy. */ RollingPolicyPtr rollingPolicy; /** * Length of current active log file. */ size_t fileLength; /** * save the loggingevent */ spi::LoggingEventPtr* _event; public: /** * The default constructor simply calls its {@link * FileAppender#FileAppender parents constructor}. * */ RollingFileAppenderSkeleton(); void activateOptions(log4cxx::helpers::Pool&); /** 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. */ virtual void subAppend(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p); bool rolloverInternal(log4cxx::helpers::Pool& p); protected: 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(); 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. */ log4cxx::helpers::WriterPtr createWriter(log4cxx::helpers::OutputStreamPtr& os); public: /** * Get byte length of current active log file. * @return byte length of current active log file. */ size_t getFileLength() const; #ifdef LOG4CXX_MULTI_PROCESS /** * 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); #endif /** * 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(RollingFileAppenderSkeleton); } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/manualtriggeringpolicy.h000644 001750 001750 00000004272 14120250671 030365 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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. */ virtual bool isTriggeringEvent( Appender* appender, const log4cxx::spi::LoggingEventPtr& event, const LogString& filename, size_t fileLength); void activateOptions(log4cxx::helpers::Pool&); void setOption(const LogString& option, const LogString& value); }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/rollingfileappender.h000644 001750 001750 00000006763 14120250671 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. */ #if !defined(_LOG4CXX_ROLLING_ROLLING_FILE_APPENDER_H) #define _LOG4CXX_ROLLING_ROLLING_FILE_APPENDER_H #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 RollingFileAppenderSkeleton { DECLARE_LOG4CXX_OBJECT(RollingFileAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(RollingFileAppender) LOG4CXX_CAST_ENTRY_CHAIN(RollingFileAppenderSkeleton) END_LOG4CXX_CAST_MAP() public: RollingFileAppender(); using RollingFileAppenderSkeleton::getRollingPolicy; using RollingFileAppenderSkeleton::getTriggeringPolicy; /** * 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 */ using RollingFileAppenderSkeleton::setRollingPolicy; using RollingFileAppenderSkeleton::setTriggeringPolicy; }; LOG4CXX_PTR_DEF(RollingFileAppender); } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/action.h000644 001750 001750 00000003642 14121416577 025075 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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() /** * Is action complete. */ bool complete; /** * Is action interrupted. */ bool interrupted; log4cxx::helpers::Pool pool; std::mutex mutex; protected: /** * Constructor. */ Action(); 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-0.12.1/src/main/include/log4cxx/rolling/gzcompressaction.h000644 001750 001750 00000003533 14120250671 027177 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include namespace log4cxx { namespace rolling { class GZCompressAction : public Action { const File source; const File destination; bool deleteSource; 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); /** * Perform action. * * @return true if successful. */ virtual bool execute(log4cxx::helpers::Pool& pool) const; private: GZCompressAction(const GZCompressAction&); GZCompressAction& operator=(const GZCompressAction&); }; LOG4CXX_PTR_DEF(GZCompressAction); } } #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/rollingpolicy.h000644 001750 001750 00000005676 14120250671 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. */ #if !defined(_LOG4CXX_ROLLING_ROLLING_POLICY_H) #define _LOG4CXX_ROLLING_ROLLING_POLICY_H #include #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-0.12.1/src/main/include/log4cxx/rolling/rollingpolicybase.h000644 001750 001750 00000006520 14120250671 027325 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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() private: /** * File name pattern converters. */ PatternConverterList patternConverters; /** * File name field specifiers. */ FormattingInfoList patternFields; /** * File name pattern. */ LogString fileNamePatternStr; public: RollingPolicyBase(); virtual ~RollingPolicyBase(); virtual void activateOptions(log4cxx::helpers::Pool& p) = 0; virtual log4cxx::pattern::PatternMap getFormatSpecifiers() const = 0; virtual void setOption(const LogString& option, const LogString& value); /** * 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; #ifdef LOG4CXX_MULTI_PROCESS PatternConverterList getPatternConverterList() { return patternConverters; } #endif protected: /** * 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(log4cxx::helpers::ObjectPtr& obj, LogString& buf, log4cxx::helpers::Pool& p) const; log4cxx::pattern::PatternConverterPtr getIntegerPatternConverter() const; log4cxx::pattern::PatternConverterPtr getDatePatternConverter() const; }; } } #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/fixedwindowrollingpolicy.h000644 001750 001750 00000007737 14120250671 030755 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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() int minIndex; int maxIndex; bool explicitActiveFile; /** * 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(); void activateOptions(log4cxx::helpers::Pool& p); void setOption(const LogString& option, const LogString& value); 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, log4cxx::helpers::Pool& pool); /** * {@inheritDoc} */ RolloverDescriptionPtr rollover( const LogString& currentActiveFile, const bool append, log4cxx::helpers::Pool& pool); protected: log4cxx::pattern::PatternMap getFormatSpecifiers() const; }; LOG4CXX_PTR_DEF(FixedWindowRollingPolicy); } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/filterbasedtriggeringpolicy.h000644 001750 001750 00000006142 14120250671 031372 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { /** * 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() /** * 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; 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. */ virtual bool isTriggeringEvent( Appender* appender, const log4cxx::spi::LoggingEventPtr& event, const LogString& filename, size_t fileLength); /** * Add a filter to end of the filter list. * @param newFilter filter to add to end of list. */ void addFilter(const log4cxx::spi::FilterPtr& newFilter); /** * Clear the filters chain. * */ void clearFilters(); /** * Returns the head Filter. * */ log4cxx::spi::FilterPtr& getFilter(); /** * Prepares the instance for use. */ void activateOptions(log4cxx::helpers::Pool&); void setOption(const LogString& option, const LogString& value); }; LOG4CXX_PTR_DEF(FilterBasedTriggeringPolicy); } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/triggeringpolicy.h000644 001750 001750 00000004430 14120250671 027163 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 log4cxx::spi::LoggingEventPtr& event, const LogString& filename, size_t fileLength) = 0; }; LOG4CXX_PTR_DEF(TriggeringPolicy); } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/rolling/rolloverdescription.h000644 001750 001750 00000005633 14120250671 027720 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #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() /** * 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; 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); /** * 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-0.12.1/src/main/include/log4cxx/rolling/sizebasedtriggeringpolicy.h000644 001750 001750 00000004521 14120250671 031056 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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. */ virtual bool isTriggeringEvent( Appender* appender, const log4cxx::spi::LoggingEventPtr& event, const LogString& filename, size_t fileLength); size_t getMaxFileSize(); void setMaxFileSize(size_t l); void activateOptions(log4cxx::helpers::Pool&); void setOption(const LogString& option, const LogString& value); }; LOG4CXX_PTR_DEF(SizeBasedTriggeringPolicy); } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/htmllayout.h000644 001750 001750 00000007224 14120250671 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_HTML_LAYOUT_H #define _LOG4CXX_HTML_LAYOUT_H #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include namespace log4cxx { /** This layout outputs events in a HTML table. */ class LOG4CXX_EXPORT HTMLLayout : public Layout { private: // Print no location info by default bool locationInfo; //= false LogString title; helpers::ISO8601DateFormat dateFormat; public: DECLARE_LOG4CXX_OBJECT(HTMLLayout) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(HTMLLayout) LOG4CXX_CAST_ENTRY_CHAIN(Layout) END_LOG4CXX_CAST_MAP() 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. */ inline void setLocationInfo(bool locationInfoFlag) { this->locationInfo = locationInfoFlag; } /** Returns the current value of the LocationInfo option. */ inline bool getLocationInfo() const { return locationInfo; } /** The Title option takes a String value. This option sets the document title of the generated HTML document.

Defaults to 'Log4cxx Log Messages'. */ inline void setTitle(const LogString& title1) { this->title.assign(title1); } /** Returns the current value of the Title option. */ inline const LogString& getTitle() const { return title; } /** Returns the content type output by this layout, i.e "text/html". */ virtual LogString getContentType() const { return LOG4CXX_STR("text/html"); } /** No options to activate. */ virtual void activateOptions(log4cxx::helpers::Pool& /* p */) {} /** Set options */ virtual void setOption(const LogString& option, const LogString& value); virtual void format(LogString& output, const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool) const; /** Append appropriate HTML headers. */ virtual void appendHeader(LogString& output, log4cxx::helpers::Pool& pool); /** Append the appropriate HTML footers. */ virtual void appendFooter(LogString& output, log4cxx::helpers::Pool& pool); /** The HTML layout handles the throwable contained in logging events. Hence, this method return false. */ virtual bool ignoresThrowable() const { return false; } }; // class HtmlLayout LOG4CXX_PTR_DEF(HTMLLayout); } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif // _LOG4CXX_HTML_LAYOUT_H apache-log4cxx-0.12.1/src/main/include/log4cxx/consoleappender.h000644 001750 001750 00000004607 14120250670 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. */ #ifndef _LOG4CXX_CONSOLE_APPENDER_H #define _LOG4CXX_CONSOLE_APPENDER_H #include #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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: LogString target; public: DECLARE_LOG4CXX_OBJECT(ConsoleAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ConsoleAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() ConsoleAppender(); ConsoleAppender(const LayoutPtr& layout); ConsoleAppender(const LayoutPtr& layout, const LogString& target); ~ConsoleAppender(); /** * Sets the value of the target property. Recognized values * are "System.out" and "System.err". Any other value will be * ignored. * */ void setTarget(const LogString& value); /** * Returns the current value of the target property. The * default value of the option is "System.out". * * See also #setTarget. * */ LogString getTarget() const; void activateOptions(log4cxx::helpers::Pool& p); void setOption(const LogString& option, const LogString& value); static const LogString& getSystemOut(); static const LogString& getSystemErr(); private: void targetWarn(const LogString& val); }; LOG4CXX_PTR_DEF(ConsoleAppender); } //namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_CONSOLE_APPENDER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/fileappender.h000644 001750 001750 00000015722 14120250670 024577 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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: /** 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; 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. */ inline bool getAppend() const { return fileAppend; } /** Returns the value of the File option. */ inline LogString getFile() const { return fileName; } /**

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(log4cxx::helpers::Pool& p); void setOption(const LogString& option, const LogString& value); /** Get the value of the BufferedIO option.

BufferedIO will significatnly increase performance on heavily loaded systems. */ inline bool getBufferedIO() const { return bufferedIO; } /** Get the size of the IO buffer. */ inline int getBufferSize() const { return bufferSize; } /** 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) { this->bufferSize = 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&); }; // class FileAppender LOG4CXX_PTR_DEF(FileAppender); } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/mdc.h000644 001750 001750 00000016730 14120250671 022705 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif 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&); LogString key; }; // class MDC; } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_MDC_H apache-log4cxx-0.12.1/src/main/include/log4cxx/jsonlayout.h000644 001750 001750 00000007536 14120250671 024355 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif namespace log4cxx { /** This layout outputs events in a JSON dictionary. */ class LOG4CXX_EXPORT JSONLayout : public Layout { private: // Print no location info by default bool locationInfo; //= false bool prettyPrint; //= false helpers::ISO8601DateFormat dateFormat; protected: LogString ppIndentL1; LogString ppIndentL2; 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: DECLARE_LOG4CXX_OBJECT(JSONLayout) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(JSONLayout) LOG4CXX_CAST_ENTRY_CHAIN(Layout) END_LOG4CXX_CAST_MAP() 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. */ inline void setLocationInfo(bool locationInfoFlag) { this->locationInfo = locationInfoFlag; } /** Returns the current value of the LocationInfo option. */ inline bool getLocationInfo() const { return locationInfo; } /** 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. */ inline void setPrettyPrint(bool prettyPrintFlag) { this->prettyPrint = prettyPrintFlag; } /** Returns the current value of the PrettyPrint option. */ inline bool getPrettyPrint() const { return prettyPrint; } /** Returns the content type output by this layout, i.e "application/json". */ virtual LogString getContentType() const { return LOG4CXX_STR("application/json"); } /** No options to activate. */ virtual void activateOptions(log4cxx::helpers::Pool& /* p */) {} /** Set options */ virtual void setOption(const LogString& option, const LogString& value); virtual void format(LogString& output, const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool) const; /** The JSON layout handles the throwable contained in logging events. Hence, this method return false. */ virtual bool ignoresThrowable() const { return false; } }; // class JSONLayout LOG4CXX_PTR_DEF(JSONLayout); } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_JSON_LAYOUT_H apache-log4cxx-0.12.1/src/main/include/log4cxx/varia/000755 001750 001750 00000000000 14122472745 023076 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/varia/fallbackerrorhandler.h000644 001750 001750 00000006025 14120250671 027407 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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: AppenderWeakPtr backup; AppenderWeakPtr primary; std::vector loggers; public: DECLARE_LOG4CXX_OBJECT(FallbackErrorHandler) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FallbackErrorHandler) LOG4CXX_CAST_ENTRY_CHAIN(spi::ErrorHandler) END_LOG4CXX_CAST_MAP() 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); /** No options to activate. */ void activateOptions(log4cxx::helpers::Pool& p); void setOption(const LogString& option, const LogString& value); /** 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; /** 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; /** Print a the error message passed as parameter on System.err. */ void error(const LogString& /* message */) const {} /** The appender to which this error handler is attached. */ void setAppender(const AppenderPtr& primary); /** Set the backup appender. */ void setBackupAppender(const AppenderPtr& backup); }; LOG4CXX_PTR_DEF(FallbackErrorHandler); } // namespace varia } // namespace log4cxx #endif //_LOG4CXX_VARIA_FALLBACK_ERROR_HANDLER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/defaultloggerfactory.h000644 001750 001750 00000002730 14120250670 026350 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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() virtual LoggerPtr makeNewLoggerInstance( log4cxx::helpers::Pool& pool, const LogString& name) const; }; } // namespace log4cxx #endif //_LOG4CXX_DEFAULT_LOGGER_FACTORY_H apache-log4cxx-0.12.1/src/main/include/log4cxx/logger.h000644 001750 001750 00000211643 14120250671 023421 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) && (_MSC_VER < 1900) #pragma warning ( push ) #pragma warning ( disable: 4127 ) #endif #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include #include #include namespace log4cxx { namespace helpers { class synchronized; } 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 virtual helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Logger) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Logger) LOG4CXX_CAST_ENTRY(spi::AppenderAttachable) END_LOG4CXX_CAST_MAP() private: /** * Reference to memory pool. */ helpers::Pool* pool; protected: /** 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::LoggerRepositoryWeakPtr repository; helpers::AppenderAttachableImplPtr 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; protected: friend class DefaultLoggerFactory; /** This constructor created a new logger instance and sets its name.

It is intended to be used by sub-classes only. You should not create categories directly. @param pool lifetime of pool must be longer than logger. @param name The name of the logger. */ Logger(log4cxx::helpers::Pool& pool, const LogString& name); public: ~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. */ virtual void addAppender(const AppenderPtr newAppender); /** 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(); /** Log a message string with the DEBUG level.

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; /** Log a message string with the DEBUG level.

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. */ void debug(const std::string& msg) const; #if LOG4CXX_WCHAR_T_API /** Log a message string with the DEBUG level.

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::wstring& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the DEBUG level.

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. */ void debug(const std::wstring& msg) const; #endif #if LOG4CXX_UNICHAR_API /** Log a message string with the DEBUG level.

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::basic_string& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the DEBUG level.

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. */ void debug(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Log a message string with the DEBUG level.

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 CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the DEBUG level.

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. */ void debug(const CFStringRef& msg) const; #endif /** Log a message string with the ERROR level.

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. */ void error(const std::string& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the ERROR level.

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. */ void error(const std::string& msg) const; #if LOG4CXX_WCHAR_T_API /** Log a message string with the ERROR level.

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. */ void error(const std::wstring& msg) const; /** Log a message string with the ERROR level.

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. */ void error(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const; #endif #if LOG4CXX_UNICHAR_API /** Log a message string with the ERROR level.

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. */ void error(const std::basic_string& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the ERROR level.

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. */ void error(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Log a message string with the ERROR level.

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. */ void error(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the ERROR level.

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. */ void error(const CFStringRef& msg) const; #endif /** Log a message string with the FATAL level.

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. */ void fatal(const std::string& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the ERROR level.

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. */ void fatal(const std::string& msg) const; #if LOG4CXX_WCHAR_T_API /** Log a message string with the ERROR level.

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. */ void fatal(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the ERROR level.

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. */ void fatal(const std::wstring& msg) const; #endif #if LOG4CXX_UNICHAR_API /** Log a message string with the ERROR level.

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. */ void fatal(const std::basic_string& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the ERROR level.

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. */ void fatal(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Log a message string with the ERROR level.

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. */ void fatal(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the ERROR level.

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. */ void fatal(const CFStringRef& msg) const; #endif /** This method creates a new logging event and logs the event 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; /** This method creates a new logging event and logs the event 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 /** This method creates a new logging event and logs the event 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; /** This method creates a new logging event and logs the event 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 /** This method creates a new logging event and logs the event 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; /** This method creates a new logging event and logs the event 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 /** This method creates a new logging event and logs the event 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; /** This method creates a new logging event and logs the event without further checks. @param level the level to log. @param message message. */ void forcedLog(const LevelPtr& level, const CFStringRef& message) const; #endif /** This method creates a new logging event and logs the event 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 instance. */ 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; /** 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; /** 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::LoggerRepositoryWeakPtr getLoggerRepository() const; /** * Get the logger name. * @return logger name as LogString. */ const LogString& getName() const { return name; } /** * Get logger name in current encoding. * @param name buffer to which name is appended. */ void getName(std::string& name) const; #if LOG4CXX_WCHAR_T_API /** * Get logger name. * @param name buffer to which name is appended. */ void getName(std::wstring& name) const; #endif #if LOG4CXX_UNICHAR_API /** * Get logger name. * @param name buffer to which name is appended. */ void getName(std::basic_string& name) const; #endif #if LOG4CXX_CFSTRING_API /** * Get logger name. * @param name buffer to which name is appended. */ void getName(CFStringRef& name) const; #endif /** Returns 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; /** Returns the assigned Level, if any, for this Logger. @return Level - the assigned Level, can be null. */ 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 coresponding 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: /** Log a message string with the INFO level.

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::string& msg, const log4cxx::spi::LocationInfo& location) const; void info(const std::string& msg) const; #if LOG4CXX_WCHAR_T_API /** Log a message string with the INFO level.

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::wstring& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the INFO level.

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. */ void info(const std::wstring& msg) const; #endif #if LOG4CXX_UNICHAR_API /** Log a message string with the INFO level.

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; /** Log a message string with the INFO level.

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. */ void info(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Log a message string with the INFO level.

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 CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the INFO level.

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. */ void info(const CFStringRef& msg) const; #endif /** Is the appender passed as parameter attached to this logger? */ bool isAttached(const AppenderPtr appender) const; /** * Check whether this logger is enabled for the DEBUG * Level. * *

This function is intended to lessen the computational cost of * disabled log debug statements. * *

For some logger Logger object, when you write, *

		 *      logger->debug("debug message");
		 *  
* *

You incur the cost constructing the message, concatenation in * this case, regardless of whether the message is logged or not. * *

If you are worried about speed, then you should write *

		 *    if(logger->isDebugEnabled()) {
		 *      logger->debug("debug message");
		 *    }
		 *  
* *

This way you will not incur the cost of parameter * construction if debugging is disabled for logger. On * the other hand, if the logger is debug enabled, you * will incur the cost of evaluating whether the logger is debug * enabled twice. Once in isDebugEnabled and once in * the debug. This is an insignificant overhead * since evaluating a logger takes about 1%% of the time it * takes to actually log. * * @return bool - true if this logger is debug * enabled, false otherwise. * */ bool isDebugEnabled() const; /** Check whether this logger is enabled for a given Level passed as parameter. See also #isDebugEnabled. @return bool True if this logger is enabled for level. */ bool isEnabledFor(const LevelPtr& level) const; /** Check whether this logger is enabled for the info Level. See also #isDebugEnabled. @return bool - true if this logger is enabled for level info, false otherwise. */ bool isInfoEnabled() const; /** Check whether this logger is enabled for the warn Level. See also #isDebugEnabled. @return bool - true if this logger is enabled for level warn, false otherwise. */ bool isWarnEnabled() const; /** Check whether this logger is enabled for the error Level. See also #isDebugEnabled. @return bool - true if this logger is enabled for level error, false otherwise. */ bool isErrorEnabled() const; /** Check whether this logger is enabled for the fatal Level. See also #isDebugEnabled. @return bool - true if this logger is enabled for level fatal, false otherwise. */ bool isFatalEnabled() const; /** Check whether this logger is enabled for the trace level. See also #isDebugEnabled. @return bool - true if this logger is enabled for level trace, false otherwise. */ bool isTraceEnabled() const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const LogString& key, const log4cxx::spi::LocationInfo& locationInfo, const std::vector& values) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const std::string& key, const log4cxx::spi::LocationInfo& locationInfo) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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. @see #setResourceBundle */ void l7dlog(const LevelPtr& level, const std::string& key, const log4cxx::spi::LocationInfo& locationInfo, const std::string& val1) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const std::string& key, const log4cxx::spi::LocationInfo& locationInfo, const std::string& val1, const std::string& val2) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ 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 /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const std::wstring& key, const log4cxx::spi::LocationInfo& locationInfo) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const std::wstring& key, const log4cxx::spi::LocationInfo& locationInfo, const std::wstring& val1) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const std::wstring& key, const log4cxx::spi::LocationInfo& locationInfo, const std::wstring& val1, const std::wstring& val2) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ 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 /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const std::basic_string& key, const log4cxx::spi::LocationInfo& locationInfo) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const std::basic_string& key, const log4cxx::spi::LocationInfo& locationInfo, const std::basic_string& val1) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ 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; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ 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 /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const CFStringRef& key, const log4cxx::spi::LocationInfo& locationInfo) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const CFStringRef& key, const log4cxx::spi::LocationInfo& locationInfo, const CFStringRef& val1) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const CFStringRef& key, const log4cxx::spi::LocationInfo& locationInfo, const CFStringRef& val1, const CFStringRef& val2) const; /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the user supplied string array params. @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 */ void l7dlog(const LevelPtr& level, const CFStringRef& key, const log4cxx::spi::LocationInfo& locationInfo, const CFStringRef& val1, const CFStringRef& val2, const CFStringRef& val3) const; #endif /** 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; /** 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 /** 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; /** 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 /** 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; /** 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 /** 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; /** 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 /** 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(); /** Remove the appender passed as parameter form the list of appenders. */ void removeAppender(const AppenderPtr appender); /** Remove the appender with the name passed as parameter form the list of appenders. */ void removeAppender(const LogString& name); /** Set the additivity flag for this Logger instance. */ void setAdditivity(bool additive); protected: friend class Hierarchy; /** Only the Hierarchy class can set the hierarchy of a logger.*/ void setHierarchy(spi::LoggerRepositoryWeakPtr repository); 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. */ inline void setResourceBundle(const helpers::ResourceBundlePtr& bundle) { resourceBundle = bundle; } #if LOG4CXX_WCHAR_T_API /** Log a message string with the WARN level.

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. */ void warn(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the WARN level.

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. */ void warn(const std::wstring& msg) const; #endif #if LOG4CXX_UNICHAR_API /** Log a message string with the WARN level.

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. */ void warn(const std::basic_string& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the WARN level.

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. */ void warn(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Log a message string with the WARN level.

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. */ void warn(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the WARN level.

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. */ void warn(const CFStringRef& msg) const; #endif /** Log a message string with the WARN level.

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. */ void warn(const std::string& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the WARN level.

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. */ void warn(const std::string& msg) const; #if LOG4CXX_WCHAR_T_API /** Log a message string with the TRACE level.

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. */ void trace(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the TRACE level.

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. */ void trace(const std::wstring& msg) const; #endif #if LOG4CXX_UNICHAR_API /** Log a message string with the TRACE level.

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. */ void trace(const std::basic_string& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the TRACE level.

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. */ void trace(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Log a message string with the TRACE level.

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. */ void trace(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the TRACE level.

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. */ void trace(const CFStringRef& msg) const; #endif /** Log a message string with the TRACE level.

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. */ void trace(const std::string& msg, const log4cxx::spi::LocationInfo& location) const; /** Log a message string with the TRACE level.

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. */ 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&); mutable shared_mutex mutex; friend class log4cxx::helpers::synchronized; }; 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 /** Logs a message to a specified logger with a specified level. @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) /** Logs a message to a specified logger with a specified level, formatting utilizing libfmt @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) /** Logs a message to a specified logger with a specified level. @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 /** Logs a message to a specified logger with the DEBUG level. @param logger the logger to be used. @param message the message string to log. */ #define LOG4CXX_DEBUG(logger, message) do { \ if (LOG4CXX_UNLIKELY(logger->isDebugEnabled())) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getDebug(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Logs a message to a specified logger with the DEBUG level, formatting with libfmt @param logger the logger to be used. @param ... The format string and message to log */ #define LOG4CXX_DEBUG_FMT(logger, ...) do { \ if (LOG4CXX_UNLIKELY(logger->isDebugEnabled())) {\ 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 /** Logs a message to a specified logger with the TRACE level. @param logger the logger to be used. @param message the message string to log. */ #define LOG4CXX_TRACE(logger, message) do { \ if (LOG4CXX_UNLIKELY(logger->isTraceEnabled())) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getTrace(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Logs a message to a specified logger with the TRACE level, formatting with libfmt. @param logger the logger to be used. @param ... The format string and message to log */ #define LOG4CXX_TRACE_FMT(logger, ...) do { \ if (LOG4CXX_UNLIKELY(logger->isTraceEnabled())) {\ 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 /** Logs a message to a specified logger with the INFO level. @param logger the logger to be used. @param message the message string to log. */ #define LOG4CXX_INFO(logger, message) do { \ if (logger->isInfoEnabled()) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getInfo(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Logs a message to a specified logger with the INFO level, formatting with libfmt. @param logger the logger to be used. @param message the message string to log. @param ... The format string and message to log */ #define LOG4CXX_INFO_FMT(logger, ...) do { \ if (logger->isInfoEnabled()) {\ 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 /** Logs a message to a specified logger with the WARN level. @param logger the logger to be used. @param message the message string to log. */ #define LOG4CXX_WARN(logger, message) do { \ if (logger->isWarnEnabled()) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getWarn(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Logs a message to a specified logger with the WARN level, formatting with libfmt @param logger the logger to be used. @param ... The format string and message to log */ #define LOG4CXX_WARN_FMT(logger, ...) do { \ if (logger->isWarnEnabled()) {\ 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 /** Logs a message to a specified logger with the ERROR level. @param logger the logger to be used. @param message the message string to log. */ #define LOG4CXX_ERROR(logger, message) do { \ if (logger->isErrorEnabled()) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getError(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Logs a message to a specified logger with the ERROR level, formatting with libfmt @param logger the logger to be used. @param ... The format string and message to log */ #define LOG4CXX_ERROR_FMT(logger, ...) do { \ if (logger->isErrorEnabled()) {\ logger->forcedLog(::log4cxx::Level::getError(), fmt::format( __VA_ARGS__ ), LOG4CXX_LOCATION); }} while (0) /** Logs a error if the condition is not true. @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) && logger->isErrorEnabled()) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getError(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Logs a error if the condition is not true, formatting with libfmt @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) && logger->isErrorEnabled()) {\ 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 /** Logs a message to a specified logger with the FATAL level. @param logger the logger to be used. @param message the message string to log. */ #define LOG4CXX_FATAL(logger, message) do { \ if (logger->isFatalEnabled()) {\ ::log4cxx::helpers::MessageBuffer oss_; \ logger->forcedLog(::log4cxx::Level::getFatal(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Logs a message to a specified logger with the FATAL level, formatting with libfmt @param logger the logger to be used. @param ... The format string and message to log */ #define LOG4CXX_FATAL_FMT(logger, ...) do { \ if (logger->isFatalEnabled()) {\ 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 /** Logs a localized message with no 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. */ #define LOG4CXX_L7DLOG(logger, level, key) do { \ if (logger->isEnabledFor(level)) {\ logger->l7dlog(level, key, LOG4CXX_LOCATION); }} while (0) /** Logs a localized message 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) /** Logs a localized message 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) /** Logs a localized message 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) /**@}*/ #if defined(_MSC_VER) #pragma warning ( pop ) #endif #include #endif //_LOG4CXX_LOGGER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/log4cxx.h.in000644 001750 001750 00000004035 14120250671 024132 0ustar00robertrobert000000 000000 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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_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@ typedef long long log4cxx_int64_t; #define LOG4CXX_USE_GLOBAL_SCOPE_TEMPLATE 0 #define LOG4CXX_LOGSTREAM_ADD_NOP 0 typedef log4cxx_int64_t log4cxx_time_t; typedef int log4cxx_status_t; typedef unsigned int log4cxx_uint32_t; #include "boost-std-configuration.h" #include #define LOG4CXX_PTR_DEF(T) typedef std::shared_ptr T##Ptr;\ typedef std::weak_ptr T##WeakPtr #define LOG4CXX_LIST_DEF(N, T) typedef std::vector N #if _WIN32 // definitions used when using static library #if defined(LOG4CXX_STATIC) #define LOG4CXX_EXPORT // definitions used when building DLL #elif defined(LOG4CXX) #define LOG4CXX_EXPORT __declspec(dllexport) #else // definitions used when using DLL #define LOG4CXX_EXPORT __declspec(dllimport) #endif #else #define LOG4CXX_EXPORT #endif /* WIN32 */ #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/logstring.h000644 001750 001750 00000004412 14120250671 024144 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_STRING_H apache-log4cxx-0.12.1/src/main/include/log4cxx/patternlayout.h000644 001750 001750 00000036423 14120250671 025056 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 *

 *      LoggerPtr root = Logger::getRoot();
 *      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 logger of the logging event. The logger 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 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. *
* 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. *
tUsed to output the name of the thread that generated the logging event.
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. The X conversion character must be * followed by the key for the map placed between braces, as in %X{clientNumber} * where clientNumber is the key. The value in the MDC corresponding to * the key will be output. *

See MDC class for more details.

*
%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. *

*/ class LOG4CXX_EXPORT PatternLayout : public Layout { /** * Conversion pattern. */ LogString conversionPattern; /** * Pattern converters. */ LoggingEventPatternConverterList patternConverters; /** * Field widths and alignment corresponding to pattern converters. */ FormattingInfoList patternFields; 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); /** * 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. */ inline LogString getConversionPattern() const { return conversionPattern; } /** * Call createPatternParser */ virtual void activateOptions(log4cxx::helpers::Pool& p); virtual void setOption(const LogString& option, const LogString& value); /** * The PatternLayout does not handle the throwable contained within * {@link spi::LoggingEvent LoggingEvents}. Thus, it returns * true. */ virtual bool ignoresThrowable() const { return true; } /** * Produces a formatted string as specified by the conversion pattern. */ virtual void format( LogString& output, const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool) const; protected: virtual log4cxx::pattern::PatternMap getFormatSpecifiers(); }; LOG4CXX_PTR_DEF(PatternLayout); } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_PATTERN_LAYOUT_H apache-log4cxx-0.12.1/src/main/include/log4cxx/appender.h000644 001750 001750 00000007664 14120250670 023745 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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() {} void asdf(); /** 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); } #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_APPENDER_H apache-log4cxx-0.12.1/src/main/include/log4cxx/basicconfigurator.h000644 001750 001750 00000004002 14120250670 025632 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 that uses PatternLayout using the PatternLayout#TTCC_CONVERSION_PATTERN and prints to stdout to the root logger.*/ static void configure(); /** 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-0.12.1/src/main/include/log4cxx/level.h000644 001750 001750 00000021306 14121416577 023256 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif 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 void initializeLevels(); 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: static volatile bool initialized; static std::mutex initMutex; static LevelPtr allLevel; static LevelPtr fatalLevel; static LevelPtr errorLevel; static LevelPtr warnLevel; static LevelPtr infoLevel; static LevelPtr debugLevel; static LevelPtr traceLevel; static LevelPtr offLevel; int level; LogString name; 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) #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_LEVEL_H apache-log4cxx-0.12.1/src/main/include/log4cxx/stream.h000644 001750 001750 00000035502 14120250671 023433 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/config_msvc.h.in000644 001750 001750 00000003647 14120250670 025046 0ustar00robertrobert000000 000000 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 of package */ #define PACKAGE "log4cxx" /* Version number of package */ #define VERSION "@VERSION@" /* Define to 1 if you have the `ftime' function. */ #define LOG4CXX_HAVE_FTIME 1 /* ODBC support through Microsoft ODBC. */ #define LOG4CXX_HAVE_MS_ODBC 1 /* thread support through Microsoft threads. */ #define LOG4CXX_HAVE_MS_THREAD 1 /* ODBC support */ #define LOG4CXX_HAVE_ODBC 1 /* thread support */ #define LOG4CXX_HAVE_THREAD 1 typedef __int64 int64_t; #if defined(WIN32) || defined(_WIN32) #pragma warning(disable : 4250 4251 4786 4290) #endif #ifdef LOG4CXX_STATIC #define LOG4CXX_EXPORT // cf. file msvc/static/static.cpp #pragma comment(linker, "/include:?ForceSymbolReferences@@YAXXZ") #else // DLL #ifdef LOG4CXX #define LOG4CXX_EXPORT __declspec(dllexport) #else #define LOG4CXX_EXPORT __declspec(dllimport) #endif #endif #if !defined(LOG4CXX_HAVE_OLD_WIN32_INTERLOCKS) #if defined(_MSC_VER) #if _MSC_VER <= 1200 #define LOG4CXX_HAVE_OLD_WIN32_INTERLOCKS 1 #else #define LOG4CXX_HAVE_OLD_WIN32_INTERLOCKS 0 #endif #else #define LOG4CXX_HAVE_OLD_WIN32_INTERLOCKS 0 #endif #endif #define _WIN32_WINNT 0x0400 #include apache-log4cxx-0.12.1/src/main/include/log4cxx/simplelayout.h000644 001750 001750 00000004500 14120250671 024661 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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. */ virtual void format(LogString& output, const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool) const; /** The SimpleLayout does not handle the throwable contained within {@link spi::LoggingEvent LoggingEvents}. Thus, it returns true. */ bool ignoresThrowable() const { return true; } virtual void activateOptions(log4cxx::helpers::Pool& /* p */) {} virtual void setOption(const LogString& /* option */, const LogString& /* value */) {} }; LOG4CXX_PTR_DEF(SimpleLayout); } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //_LOG4CXX_SIMPLE_LAYOUT_H apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/000755 001750 001750 00000000000 14122472745 023451 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/threadpatternconverter.h000644 001750 001750 00000003511 14120250671 030405 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. */ ThreadPatternConverter(); public: DECLARE_LOG4CXX_PATTERN(ThreadPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ThreadPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() /** * 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/linelocationpatternconverter.h000644 001750 001750 00000003542 14120250671 031622 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. */ LineLocationPatternConverter(); public: DECLARE_LOG4CXX_PATTERN(LineLocationPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LineLocationPatternConverter) 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/propertiespatternconverter.h000644 001750 001750 00000004602 14120250671 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. */ #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 { /** * Name of property to output. */ const LogString option; /** * Private constructor. * @param options options, may be null. * @param logger logger for diagnostic messages, may be null. */ PropertiesPatternConverter(const LogString& name, const LogString& option); public: DECLARE_LOG4CXX_PATTERN(PropertiesPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(PropertiesPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() /** * 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/throwableinformationpatternconverter.h000644 001750 001750 00000004532 14120250671 033377 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * If "short", only first line of throwable report will be formatted. */ const bool shortReport; /** * Private constructor. */ ThrowableInformationPatternConverter(bool shortReport); public: DECLARE_LOG4CXX_PATTERN(ThrowableInformationPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ThrowableInformationPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() /** * 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; /** * This converter obviously handles throwables. * @return true. */ bool handlesThrowable() const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/ndcpatternconverter.h000644 001750 001750 00000003451 14120250671 027705 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. */ NDCPatternConverter(); public: DECLARE_LOG4CXX_PATTERN(NDCPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(NDCPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() /** * 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/datepatternconverter.h000644 001750 001750 00000004705 14120250671 030061 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Date format. */ log4cxx::helpers::DateFormatPtr df; /** * Private constructor. * @param options options, may be null. * @param logger logger for diagnostic messages, may be null. */ DatePatternConverter(const OptionsList& options); /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static log4cxx::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() static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const log4cxx::spi::LoggingEventPtr& event, LogString& output, log4cxx::helpers::Pool& p) const; void format(const log4cxx::helpers::ObjectPtr& obj, LogString& output, log4cxx::helpers::Pool& p) const; void format(const log4cxx::helpers::DatePtr& date, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; LOG4CXX_PTR_DEF(DatePatternConverter); } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/lineseparatorpatternconverter.h000644 001750 001750 00000003715 14120250671 032014 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. */ LineSeparatorPatternConverter(); public: DECLARE_LOG4CXX_PATTERN(LineSeparatorPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LineSeparatorPatternConverter) 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; void format(const log4cxx::helpers::ObjectPtr& obj, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/namepatternconverter.h000644 001750 001750 00000004242 14120250671 030060 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Abbreviator. */ const NameAbbreviatorPtr abbreviator; 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(int nameStart, LogString& buf) const; private: NameAbbreviatorPtr getAbbreviator(const std::vector& options); }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/classnamepatternconverter.h000644 001750 001750 00000003727 14120250671 031115 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. * @param options options, may be null. * @param logger logger for diagnostic messages, may be null. */ ClassNamePatternConverter( const std::vector& options); public: 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/filelocationpatternconverter.h000644 001750 001750 00000003564 14120250671 031616 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. */ FileLocationPatternConverter(); public: DECLARE_LOG4CXX_PATTERN(FileLocationPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FileLocationPatternConverter) 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/relativetimepatternconverter.h000644 001750 001750 00000003606 14120250671 031635 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/methodlocationpatternconverter.h000644 001750 001750 00000003632 14120250671 032153 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. */ MethodLocationPatternConverter(); public: DECLARE_LOG4CXX_PATTERN(MethodLocationPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(MethodLocationPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() /** * 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/messagepatternconverter.h000644 001750 001750 00000003474 14120250671 030572 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. */ MessagePatternConverter(); public: DECLARE_LOG4CXX_PATTERN(MessagePatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(MessagePatternConverter) 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/literalpatternconverter.h000644 001750 001750 00000004025 14120250671 030573 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4251 ) #endif namespace log4cxx { namespace pattern { /** * Formats a string literal. * * * * */ class LOG4CXX_EXPORT LiteralPatternConverter : public LoggingEventPatternConverter { /** * String literal. */ const LogString literal; /** * Create a new instance. * @param literal string literal. */ LiteralPatternConverter(const LogString& literal); public: DECLARE_LOG4CXX_PATTERN(LiteralPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LiteralPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() static PatternConverterPtr newInstance(const LogString& literal); using LoggingEventPatternConverter::format; void format(const log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; void format(const log4cxx::helpers::ObjectPtr& obj, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #if defined(_MSC_VER) #pragma warning (pop) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/integerpatternconverter.h000644 001750 001750 00000003375 14120250671 030603 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. */ IntegerPatternConverter(); public: DECLARE_LOG4CXX_PATTERN(IntegerPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(IntegerPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(PatternConverter) 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); void format(const log4cxx::helpers::ObjectPtr& obj, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; LOG4CXX_PTR_DEF(IntegerPatternConverter); } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/patternconverter.h000644 001750 001750 00000006677 14120250671 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_PATTERN_PATTERN_CONVERTER_H #define _LOG4CXX_PATTERN_PATTERN_CONVERTER_H #include #include #include #ifdef _MSC_VER // disable identifier too wide for debugging warning #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 log4cxx::helpers::Object { /** * Converter name. */ const LogString name; /** * Converter style name. */ const LogString style; protected: /** * Create a new pattern converter. * @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 log4cxx::helpers::ObjectPtr& obj, LogString& toAppendTo, log4cxx::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 log4cxx::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-0.12.1/src/main/include/log4cxx/pattern/loggingeventpatternconverter.h000644 001750 001750 00000005206 14120250671 031631 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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); 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const = 0; void format(const log4cxx::helpers::ObjectPtr& obj, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; /** * 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-0.12.1/src/main/include/log4cxx/pattern/fulllocationpatternconverter.h000644 001750 001750 00000003543 14120250671 031636 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. */ FullLocationPatternConverter(); public: DECLARE_LOG4CXX_PATTERN(FullLocationPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FullLocationPatternConverter) 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/loggerpatternconverter.h000644 001750 001750 00000003635 14120250671 030424 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. * @param options options, may be null. * @param logger logger for diagnostic messages, may be null. */ LoggerPatternConverter(const std::vector& options); public: DECLARE_LOG4CXX_PATTERN(LoggerPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LoggerPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(NamePatternConverter) 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 NamePatternConverter::format; void format(const log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/formattinginfo.h000644 001750 001750 00000005160 14120250671 026640 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Minimum length. */ const int minLength; /** * Maximum length. */ const int maxLength; /** * Alignment. */ const bool leftAlign; 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); /** * Gets default instance. * @return default instance. */ static FormattingInfoPtr getDefault(); /** * Determine if left aligned. * @return true if left aligned. */ inline bool isLeftAligned() const { return leftAlign; } /** * Get minimum length. * @return minimum length. */ inline int getMinLength() const { return minLength; } /** * Get maximum length. * @return maximum length. */ inline int getMaxLength() const { return maxLength; } /** * Adjust the content of the buffer based on the specified lengths and alignment. * * @param fieldStart start of field in buffer. * @param buffer buffer to be modified. */ void format(const int fieldStart, LogString& buffer) const; }; LOG4CXX_PTR_DEF(FormattingInfo); } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/nameabbreviator.h000644 001750 001750 00000004536 14120250671 026761 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/pattern/patternparser.h000644 001750 001750 00000012443 14120250671 026506 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include #include namespace log4cxx { namespace pattern { typedef PatternConverterPtr (*PatternConstructor)(const std::vector& options); 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); }; } } #if defined(_MSC_VER) #pragma warning (pop) #endif #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/pattern/filedatepatternconverter.h000644 001750 001750 00000003034 14120250671 030713 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/include/log4cxx/pattern/levelpatternconverter.h000644 001750 001750 00000003573 14120250671 030255 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 { /** * Private constructor. */ LevelPatternConverter(); public: DECLARE_LOG4CXX_PATTERN(LevelPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LevelPatternConverter) 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 log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& p) const; LogString getStyleClass(const log4cxx::helpers::ObjectPtr& e) const; }; } } #endif apache-log4cxx-0.12.1/src/main/include/log4cxx/hierarchy.h000644 001750 001750 00000021054 14120250671 024113 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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 virtual spi::LoggerRepository, public virtual helpers::Object, public std::enable_shared_from_this { private: log4cxx::helpers::Pool pool; mutable std::mutex mutex; bool configured; spi::LoggerFactoryPtr defaultFactory; spi::HierarchyEventListenerList listeners; typedef std::map LoggerMap; std::unique_ptr loggers; typedef std::map ProvisionNodeMap; std::unique_ptr provisionNodes; LoggerPtr root; int thresholdInt; LevelPtr threshold; bool emittedNoAppenderWarning; bool emittedNoResourceBundleWarning; 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); /** 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); /** 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); /** The string form of {@link #setThreshold(const LevelPtr&) setThreshold}. */ void setThreshold(const LogString& levelStr); /** Enable logging for logging requests with level l or higher. By default all levels are enabled. @param l The minimum level for which logging requests are sent to their appenders. */ void setThreshold(const LevelPtr& l); void fireAddAppenderEvent(const Logger* logger, const Appender* appender); void fireRemoveAppenderEvent(const Logger* logger, const Appender* appender); /** Returns a Level representation of the enable state. */ const LevelPtr& getThreshold() const; /** Return a new logger instance named as the first parameter using the default factory.

If a logger of that name already exists, then it will be returned. Otherwise, a new logger will be instantiated and then linked with its existing ancestors as well as children. @param name The name of the logger to retrieve. */ LoggerPtr getLogger(const LogString& name); /** Return a new logger instance named as the first parameter using factory.

If a logger of that name already exists, then it will be returned. Otherwise, a new logger will be instantiated by the factory parameter and linked with its existing ancestors as well as children. @param 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); /** 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; /** Get the root of this hierarchy. */ LoggerPtr getRootLogger() const; /** 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; /** 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(); /** 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::SocketAppender SocketAppender} and AsyncAppender need to be closed before the application exists. Otherwise, pending logging events might be lost.

The shutdown method is careful to close nested appenders before closing regular appenders. This is allows configurations where a regular appender is attached to a logger and again to a nested appender. */ void shutdown(); virtual bool isConfigured(); virtual void setConfigured(bool configured); 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 'cat'. There 3 possible cases: 1) No entry for the potential parent of 'cat' exists We create a ProvisionNode for this potential parent and insert 'cat' in that provision node. 2) There entry is of type Logger for the potential parent. The entry is 'cat's nearest existing parent. We update cat'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 'cat' to the list of children for this potential parent. */ void updateParents(LoggerPtr logger); /** We update the links for all the children that placed themselves in the provision node 'pn'. The second argument 'cat' is a reference for the newly created Logger, 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 cat's parent field to c's parent and set c's parent field to cat. */ Hierarchy(const Hierarchy&); Hierarchy& operator=(const Hierarchy&); void updateChildren(ProvisionNode& pn, LoggerPtr logger); void configureRoot(); }; } //namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif //_LOG4CXX_HIERARCHY_H apache-log4cxx-0.12.1/src/main/include/log4cxx-qt/000755 001750 001750 00000000000 14122472745 022416 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/include/log4cxx-qt/messagehandler.h000644 001750 001750 00000002600 14120250670 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_QT_MESSAGEHANDLER_H #define LOG4CXX_QT_MESSAGEHANDLER_H #include 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(). */ void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message); } /* namespace qt */ } /* namespace log4cxx */ #endif /* LOG4CXX_QT_MESSAGEHANDLER_H */ apache-log4cxx-0.12.1/src/main/cpp/000755 001750 001750 00000000000 14122472745 017543 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/cpp/syslogappender.cpp000644 001750 001750 00000027314 14120250670 023302 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 #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 #define LOG_UNDEF -1 using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; IMPLEMENT_LOG4CXX_OBJECT(SyslogAppender) SyslogAppender::SyslogAppender() : syslogFacility(LOG_USER), facilityPrinting(false), sw(0), maxMessageLength(1024) { this->initSyslogFacilityStr(); } SyslogAppender::SyslogAppender(const LayoutPtr& layout1, int syslogFacility1) : syslogFacility(syslogFacility1), facilityPrinting(false), sw(0), maxMessageLength(1024) { this->layout = layout1; this->initSyslogFacilityStr(); } SyslogAppender::SyslogAppender(const LayoutPtr& layout1, const LogString& syslogHost1, int syslogFacility1) : syslogFacility(syslogFacility1), facilityPrinting(false), sw(0), maxMessageLength(1024) { this->layout = layout1; this->initSyslogFacilityStr(); setSyslogHost(syslogHost1); } SyslogAppender::~SyslogAppender() { finalize(); } /** Release any resources held by this SyslogAppender.*/ void SyslogAppender::close() { closed = true; if (sw != 0) { delete sw; sw = 0; } } void SyslogAppender::initSyslogFacilityStr() { facilityStr = getFacilityString(this->syslogFacility); if (facilityStr.empty()) { Pool p; LogString msg(LOG4CXX_STR("\"")); StringHelper::toString(syslogFacility, p, msg); msg.append(LOG4CXX_STR("\" is an unknown syslog facility. Defaulting to \"USER\".")); LogLog::error(msg); this->syslogFacility = LOG_USER; facilityStr = LOG4CXX_STR("user:"); } else { 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; 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() > maxMessageLength ) { LogString::iterator start = msg.begin(); while ( start != msg.end() ) { LogString::iterator end = start + 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, 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 (sw == 0) { for ( std::vector::iterator it = packets.begin(); it != packets.end(); it++ ) { // use of "%s" to avoid a security hole ::syslog(syslogFacility | event->getLevel()->getSyslogEquivalent(), "%s", it->c_str()); } return; } #endif // We must not attempt to append if sw is null. if (sw == 0) { errorHandler->error(LOG4CXX_STR("No syslog host is set for SyslogAppedender named \"") + this->name + LOG4CXX_STR("\".")); return; } for ( std::vector::iterator it = packets.begin(); it != packets.end(); it++ ) { LogString sbuf(1, 0x3C /* '<' */); StringHelper::toString((syslogFacility | event->getLevel()->getSyslogEquivalent()), p, sbuf); sbuf.append(1, (logchar) 0x3E /* '>' */); if (facilityPrinting) { sbuf.append(facilityStr); } sbuf.append(*it); 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 (this->sw != 0) { delete this->sw; this->sw = 0; } 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) { this->sw = new SyslogWriter(slHost, slHostPort); } else { this->sw = new SyslogWriter(slHost); } this->syslogHost = slHost; this->syslogHostPort = slHostPort; } void SyslogAppender::setFacility(const LogString& facilityName) { if (facilityName.empty()) { return; } syslogFacility = getFacility(facilityName); if (syslogFacility == LOG_UNDEF) { LogLog::error(LOG4CXX_STR("[") + facilityName + LOG4CXX_STR("] is an unknown syslog facility. Defaulting to [USER].")); syslogFacility = LOG_USER; } this->initSyslogFacilityStr(); } apache-log4cxx-0.12.1/src/main/cpp/consoleappender.cpp000644 001750 001750 00000006453 14120250670 023425 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(ConsoleAppender) ConsoleAppender::ConsoleAppender() : target(getSystemOut()) { } ConsoleAppender::ConsoleAppender(const LayoutPtr& layout1) : target(getSystemOut()) { setLayout(layout1); Pool p; WriterPtr writer1(new SystemOutWriter()); setWriter(writer1); WriterAppender::activateOptions(p); } ConsoleAppender::ConsoleAppender(const LayoutPtr& layout1, const LogString& target1) : target(target1) { setLayout(layout1); 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"))) { target = getSystemOut(); } else if (StringHelper::equalsIgnoreCase(v, LOG4CXX_STR("SYSTEM.ERR"), LOG4CXX_STR("system.err"))) { target = getSystemErr(); } else { targetWarn(value); } } LogString ConsoleAppender::getTarget() const { return 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(target, LOG4CXX_STR("SYSTEM.OUT"), LOG4CXX_STR("system.out"))) { WriterPtr writer1(new SystemOutWriter()); setWriter(writer1); } else if (StringHelper::equalsIgnoreCase(target, LOG4CXX_STR("SYSTEM.ERR"), LOG4CXX_STR("system.err"))) { WriterPtr writer1(new SystemErrWriter()); 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-0.12.1/src/main/cpp/socketoutputstream.cpp000644 001750 001750 00000003311 14120250670 024217 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(SocketOutputStream) SocketOutputStream::SocketOutputStream(const SocketPtr& socket1) : socket(socket1) { } SocketOutputStream::~SocketOutputStream() { } void SocketOutputStream::close(Pool& p) { flush(p); socket->close(); } void SocketOutputStream::flush(Pool& /* p */) { if (array.size() > 0) { ByteBuffer buf((char*) &array[0], array.size()); socket->write(buf); array.resize(0); } } void SocketOutputStream::write(ByteBuffer& buf, Pool& /* p */ ) { if (buf.remaining() > 0) { size_t sz = array.size(); array.resize(sz + buf.remaining()); memcpy(&array[sz], buf.current(), buf.remaining()); buf.position(buf.limit()); } } apache-log4cxx-0.12.1/src/main/cpp/rollingfileappender.cpp000644 001750 001750 00000037354 14120250670 024275 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #ifdef LOG4CXX_MULTI_PROCESS #include #include #include #include #include #ifndef MAX_FILE_LEN #define MAX_FILE_LEN 2048 #endif #include #include #endif #include #include #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(RollingFileAppenderSkeleton) IMPLEMENT_LOG4CXX_OBJECT(RollingFileAppender) /** * Construct a new instance. */ RollingFileAppenderSkeleton::RollingFileAppenderSkeleton() : _event(NULL) { } RollingFileAppender::RollingFileAppender() { } /** * Prepare instance of use. */ void RollingFileAppenderSkeleton::activateOptions(Pool& p) { if (rollingPolicy == NULL) { FixedWindowRollingPolicyPtr fwrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); fwrp->setFileNamePattern(getFile() + LOG4CXX_STR(".%i")); rollingPolicy = fwrp; } // // if no explicit triggering policy and rolling policy is both. // if (triggeringPolicy == NULL) { TriggeringPolicyPtr trig = log4cxx::cast(rollingPolicy); if (trig != NULL) { triggeringPolicy = trig; } } if (triggeringPolicy == NULL) { triggeringPolicy = TriggeringPolicyPtr(new ManualTriggeringPolicy()); } { std::unique_lock lock(mutex); triggeringPolicy->activateOptions(p); rollingPolicy->activateOptions(p); try { RolloverDescriptionPtr rollover1 = rollingPolicy->initialize(getFile(), getAppend(), p); if (rollover1 != NULL) { ActionPtr syncAction(rollover1->getSynchronous()); if (syncAction != NULL) { syncAction->execute(p); } fileName = rollover1->getActiveFileName(); 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()) { fileLength = activeFile.length(p); } else { fileLength = 0; } FileAppender::activateOptionsInternal(p); } catch (std::exception&) { LogLog::warn( LogString(LOG4CXX_STR("Exception will initializing RollingFileAppender named ")) + getName()); } } } #ifdef LOG4CXX_MULTI_PROCESS void RollingFileAppenderSkeleton::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; } } #endif /** 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 RollingFileAppenderSkeleton::rollover(Pool& p) { std::unique_lock lock(mutex); return rolloverInternal(p); } bool RollingFileAppenderSkeleton::rolloverInternal(Pool& p) { // // can't roll without a policy // if (rollingPolicy != NULL) { { #ifdef LOG4CXX_MULTI_PROCESS std::string fileName(getFile()); RollingPolicyBase* basePolicy = dynamic_cast(&(*rollingPolicy)); apr_time_t n = apr_time_now(); ObjectPtr obj(new Date(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, pool.getAPRPool()); if (stat == APR_SUCCESS) { snprintf(szUid, MAX_FILE_LEN, "%u", uid); } const std::string lockname = std::string(::dirname(szDirName)) + "/." + ::basename(szBaseName) + 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) { std::string err = "lockfile return error: open lockfile failed. "; err += (strerror(errno)); LogLog::warn(LOG4CXX_STR(err.c_str())); bAlreadyRolled = false; lock_file = NULL; } else { stat = apr_file_lock(lock_file, APR_FLOCK_EXCLUSIVE); if (stat != APR_SUCCESS) { std::string err = "apr_file_lock: lock failed. "; err += (strerror(errno)); LogLog::warn(LOG4CXX_STR(err.c_str())); bAlreadyRolled = false; } else { if (_event) { triggeringPolicy->isTriggeringEvent(this, *_event, getFile(), getFileLength()); } } } if (bAlreadyRolled) { apr_finfo_t finfo1, finfo2; apr_status_t st1, st2; apr_file_t* _fd = getWriter()->getOutPutStreamPtr()->getFileOutPutStreamPtr().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) { LogLog::warn(LOG4CXX_STR("apr_stat failed.")); } bAlreadyRolled = ((st1 == APR_SUCCESS) && (st2 == APR_SUCCESS) && ((finfo1.device != finfo2.device) || (finfo1.inode != finfo2.inode))); } if (!bAlreadyRolled) { #endif try { RolloverDescriptionPtr rollover1(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); errorHandler->error(exmsg, ex, 0); } } if (success) { if (rollover1->getAppend()) { fileLength = File().setPath(rollover1->getActiveFileName()).length(p); } else { fileLength = 0; } // // async action not yet implemented // ActionPtr asyncAction(rollover1->getAsynchronous()); if (asyncAction != NULL) { asyncAction->execute(p); } setFileInternal( rollover1->getActiveFileName(), rollover1->getAppend(), bufferedIO, bufferSize, p); } else { setFileInternal( rollover1->getActiveFileName(), true, bufferedIO, 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); errorHandler->error(exmsg, ex, 0); } } if (success) { if (rollover1->getAppend()) { fileLength = File().setPath(rollover1->getActiveFileName()).length(p); } else { fileLength = 0; } // // async action not yet implemented // ActionPtr asyncAction(rollover1->getAsynchronous()); if (asyncAction != NULL) { asyncAction->execute(p); } } writeHeader(p); } #ifdef LOG4CXX_MULTI_PROCESS releaseFileLock(lock_file); #endif return true; } } catch (std::exception& ex) { LogLog::warn(LOG4CXX_STR("Exception during rollover")); LogString exmsg; log4cxx::helpers::Transcoder::decode(ex.what(), exmsg); errorHandler->error(exmsg, ex, 0); } #ifdef LOG4CXX_MULTI_PROCESS } else { reopenLatestFile(p); } releaseFileLock(lock_file); #endif } } return false; } #ifdef LOG4CXX_MULTI_PROCESS /** * re-open current file when its own handler has been renamed */ void RollingFileAppenderSkeleton::reopenLatestFile(Pool& p) { closeWriter(); OutputStreamPtr os(new FileOutputStream(getFile(), true)); WriterPtr newWriter(createWriter(os)); setFile(getFile()); setWriter(newWriter); fileLength = File().setPath(getFile()).length(p); writeHeader(p); } #endif /** * {@inheritDoc} */ void RollingFileAppenderSkeleton::subAppend(const LoggingEventPtr& event, Pool& p) { // The rollover check must precede actual writing. This is the // only correct behavior for time driven triggers. if ( triggeringPolicy->isTriggeringEvent( this, event, getFile(), getFileLength())) { // // wrap rollover request in try block since // rollover may fail in case read access to directory // is not provided. However appender should still be in good // condition and the append should still happen. try { _event = &(const_cast(event)); rolloverInternal(p); } catch (std::exception& ex) { LogLog::warn(LOG4CXX_STR("Exception during rollover attempt.")); LogString exmsg; log4cxx::helpers::Transcoder::decode(ex.what(), exmsg); errorHandler->error(exmsg); } } #ifdef LOG4CXX_MULTI_PROCESS //do re-check before every write // apr_finfo_t finfo1, finfo2; apr_status_t st1, st2; apr_file_t* _fd = getWriter()->getOutPutStreamPtr()->getFileOutPutStreamPtr().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) { std::string err = "apr_stat failed. file:" + std::string(getFile()); LogLog::warn(LOG4CXX_STR(err.c_str())); } bool bAlreadyRolled = ((st1 == APR_SUCCESS) && (st2 == APR_SUCCESS) && ((finfo1.device != finfo2.device) || (finfo1.inode != finfo2.inode))); if (bAlreadyRolled) { reopenLatestFile(p); } #endif FileAppender::subAppend(event, p); } /** * Get rolling policy. * @return rolling policy. */ RollingPolicyPtr RollingFileAppenderSkeleton::getRollingPolicy() const { return rollingPolicy; } /** * Get triggering policy. * @return triggering policy. */ TriggeringPolicyPtr RollingFileAppenderSkeleton::getTriggeringPolicy() const { return triggeringPolicy; } /** * Sets the rolling policy. * @param policy rolling policy. */ void RollingFileAppenderSkeleton::setRollingPolicy(const RollingPolicyPtr& policy) { rollingPolicy = policy; } /** * Set triggering policy. * @param policy triggering policy. */ void RollingFileAppenderSkeleton::setTriggeringPolicy(const TriggeringPolicyPtr& policy) { triggeringPolicy = policy; } /** * Close appender. Waits for any asynchronous file compression actions to be completed. */ void RollingFileAppenderSkeleton::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. */ RollingFileAppenderSkeleton* rfa; public: /** * Constructor. * @param os output stream to wrap. * @param rfa rolling file appender to inform. */ CountingOutputStream( OutputStreamPtr& os1, RollingFileAppenderSkeleton* 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) { #ifndef LOG4CXX_MULTI_PROCESS rfa->incrementFileLength(buf.limit()); #else rfa->setFileLength(File().setPath(rfa->getFile()).length(p)); #endif } } #ifdef LOG4CXX_MULTI_PROCESS OutputStream& getFileOutPutStreamPtr() { return *os; } #endif }; } } /** 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 RollingFileAppenderSkeleton::createWriter(OutputStreamPtr& os) { OutputStreamPtr cos(new CountingOutputStream(os, this)); return FileAppender::createWriter(cos); } /** * Get byte length of current active log file. * @return byte length of current active log file. */ size_t RollingFileAppenderSkeleton::getFileLength() const { return fileLength; } #ifdef LOG4CXX_MULTI_PROCESS void RollingFileAppenderSkeleton::setFileLength(size_t length) { fileLength = length; } #endif /** * Increments estimated byte length of current active log file. * @param increment additional bytes written to log file. */ void RollingFileAppenderSkeleton::incrementFileLength(size_t increment) { fileLength += increment; } apache-log4cxx-0.12.1/src/main/cpp/bytearrayoutputstream.cpp000644 001750 001750 00000003121 14120250670 024730 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(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 = array.size(); array.resize(sz + buf.remaining()); memcpy(&array[sz], buf.current(), buf.remaining()); buf.position(buf.limit()); } std::vector ByteArrayOutputStream::toByteArray() const { return array; } apache-log4cxx-0.12.1/src/main/cpp/locationinfo.cpp000644 001750 001750 00000012353 14120250670 022724 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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::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 methodName1, int lineNumber1 ) : lineNumber( lineNumber1 ), fileName( fileName1 ), methodName( methodName1 ) { } /** * Default constructor. */ LocationInfo::LocationInfo() : lineNumber( -1 ), fileName(LocationInfo::NA), methodName(LocationInfo::NA_METHOD) { } /** * Copy constructor. * @param src source location */ LocationInfo::LocationInfo( const LocationInfo& src ) : lineNumber( src.lineNumber ), fileName( src.fileName ), 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; } /** * 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; } void LocationInfo::write(ObjectOutputStream& os, Pool& p) const { if (lineNumber == -1 && fileName == NA && methodName == NA_METHOD) { os.writeNull(p); } else { unsigned char prolog[] = { 0x72, 0x00, 0x21, 0x6F, 0x72, 0x67, 0x2E, 0x61, 0x70, 0x61, 0x63, 0x68, 0x65, 0x2E, 0x6C, 0x6F, 0x67, 0x34, 0x6A, 0x2E, 0x73, 0x70, 0x69, 0x2E, 0x4C, 0x6F, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x49, 0x6E, 0x66, 0x6F, 0xED, 0x99, 0xBB, 0xE1, 0x4A, 0x91, 0xA5, 0x7C, 0x02, 0x00, 0x01, 0x4C, 0x00, 0x08, 0x66, 0x75, 0x6C, 0x6C, 0x49, 0x6E, 0x66, 0x6F, 0x74, 0x00, 0x12, 0x4C, 0x6A, 0x61, 0x76, 0x61, 0x2F, 0x6C, 0x61, 0x6E, 0x67, 0x2F, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x3B, 0x78, 0x70 }; os.writeProlog("org.apache.log4j.spi.LocationInfo", 2, (char*) prolog, sizeof(prolog), p); char* line = p.itoa(lineNumber); // // construct Java-like fullInfo (replace "::" with ".") // std::string fullInfo(methodName); size_t openParen = fullInfo.find('('); if (openParen != std::string::npos) { size_t space = fullInfo.find(' '); if (space != std::string::npos && space < openParen) { fullInfo.erase(0, space + 1); } } openParen = fullInfo.find('('); if (openParen != std::string::npos) { size_t classSep = fullInfo.rfind("::", openParen); if (classSep != std::string::npos) { fullInfo.replace(classSep, 2, "."); } else { fullInfo.insert(0, "."); } } fullInfo.append(1, '('); fullInfo.append(fileName); fullInfo.append(1, ':'); fullInfo.append(line); fullInfo.append(1, ')'); os.writeUTFString(fullInfo, p); } } apache-log4cxx-0.12.1/src/main/cpp/datepatternconverter.cpp000644 001750 001750 00000010436 14120250670 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. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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; IMPLEMENT_LOG4CXX_OBJECT(DatePatternConverter) DatePatternConverter::DatePatternConverter( const std::vector& options) : LoggingEventPatternConverter(LOG4CXX_STR("Class Name"), LOG4CXX_STR("class name")), df(getDateFormat(options)) { } DateFormatPtr DatePatternConverter::getDateFormat(const OptionsList& options) { DateFormatPtr df; int maximumCacheValidity = 1000000; if (options.size() == 0) { df = DateFormatPtr(new ISO8601DateFormat()); } else { LogString dateFormatStr(options[0]); if (dateFormatStr.empty() || StringHelper::equalsIgnoreCase(dateFormatStr, LOG4CXX_STR("ISO8601"), LOG4CXX_STR("iso8601"))) { df = DateFormatPtr(new ISO8601DateFormat()); } else if (StringHelper::equalsIgnoreCase(dateFormatStr, LOG4CXX_STR("ABSOLUTE"), LOG4CXX_STR("absolute"))) { df = DateFormatPtr(new AbsoluteTimeDateFormat()); } else if (StringHelper::equalsIgnoreCase(dateFormatStr, LOG4CXX_STR("DATE"), LOG4CXX_STR("date"))) { df = DateFormatPtr(new DateTimeDateFormat()); } else { if (dateFormatStr.find(0x25 /*'%'*/) == std::string::npos) { try { df = DateFormatPtr(new SimpleDateFormat(dateFormatStr)); maximumCacheValidity = CachedDateFormat::getMaximumCacheValidity(dateFormatStr); } catch (IllegalArgumentException& e) { df = DateFormatPtr(new ISO8601DateFormat()); LogLog::warn(((LogString) LOG4CXX_STR("Could not instantiate SimpleDateFormat with pattern ")) + dateFormatStr, e); } } else { df = DateFormatPtr(new StrftimeDateFormat(dateFormatStr)); } } if (options.size() >= 2) { TimeZonePtr tz(TimeZone::getTimeZone(options[1])); if (tz != NULL) { df->setTimeZone(tz); } } } if (maximumCacheValidity > 0) { df = DateFormatPtr(new CachedDateFormat(df, maximumCacheValidity)); } return df; } PatternConverterPtr DatePatternConverter::newInstance( const std::vector& options) { return PatternConverterPtr(new DatePatternConverter(options)); } void DatePatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { 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 { df->format(toAppendTo, date->getTime(), p); } apache-log4cxx-0.12.1/src/main/cpp/literalpatternconverter.cpp000644 001750 001750 00000003777 14120250670 025234 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(LiteralPatternConverter) LiteralPatternConverter::LiteralPatternConverter(const LogString& literal1) : LoggingEventPatternConverter(LOG4CXX_STR("Literal"), LOG4CXX_STR("literal")), literal(literal1) { } PatternConverterPtr LiteralPatternConverter::newInstance( const LogString& literal) { if (literal.length() == 1 && literal[0] == 0x20 /* ' ' */) { static PatternConverterPtr blank(new LiteralPatternConverter(literal)); return blank; } PatternConverterPtr pattern(new LiteralPatternConverter(literal)); return pattern; } void LiteralPatternConverter::format( const LoggingEventPtr& /* event */, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(literal); } void LiteralPatternConverter::format( const ObjectPtr& /* event */, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(literal); } apache-log4cxx-0.12.1/src/main/cpp/xmlsocketappender.cpp000644 001750 001750 00000006572 14120250670 023776 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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::net; using namespace log4cxx::xml; IMPLEMENT_LOG4CXX_OBJECT(XMLSocketAppender) // 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(DEFAULT_PORT, DEFAULT_RECONNECTION_DELAY) { layout = XMLLayoutPtr(new XMLLayout()); } XMLSocketAppender::XMLSocketAppender(InetAddressPtr address1, int port1) : SocketAppenderSkeleton(address1, port1, DEFAULT_RECONNECTION_DELAY) { layout = XMLLayoutPtr(new XMLLayout()); Pool p; activateOptions(p); } XMLSocketAppender::XMLSocketAppender(const LogString& host, int port1) : SocketAppenderSkeleton(host, port1, DEFAULT_RECONNECTION_DELAY) { layout = XMLLayoutPtr(new XMLLayout()); 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(new SocketOutputStream(socket)); CharsetEncoderPtr charset(CharsetEncoder::getUTF8Encoder()); std::unique_lock lock(mutex); writer = OutputStreamWriterPtr(new OutputStreamWriter(os, charset)); } void XMLSocketAppender::cleanUp(Pool& p) { if (writer != 0) { try { writer->close(p); writer = 0; } catch (std::exception&) { } } } void XMLSocketAppender::append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) { if (writer != 0) { LogString output; layout->format(output, event, p); try { writer->write(output, p); writer->flush(p); } catch (std::exception& e) { writer = 0; LogLog::warn(LOG4CXX_STR("Detected problem with connection: "), e); if (getReconnectionDelay() > 0) { fireConnector(); } } } } apache-log4cxx-0.12.1/src/main/cpp/propertyconfigurator.cpp000644 001750 001750 00000032067 14122472113 024553 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 #define LOG4CXX 1 #include using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; using namespace log4cxx::config; #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; } void 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&) { LogLog::error(((LogString) LOG4CXX_STR("Could not read configuration file [")) + configFileName.getPath() + LOG4CXX_STR("].")); return; } try { doConfigure(props, hierarchy); } catch (const std::exception& ex) { LogLog::error(((LogString) LOG4CXX_STR("Could not parse configuration file [")) + configFileName.getPath() + LOG4CXX_STR("]."), ex); } } void PropertyConfigurator::configure(const File& configFilename) { PropertyConfigurator().doConfigure(configFilename, LogManager::getLoggerRepository()); } void PropertyConfigurator::configure(helpers::Properties& properties) { PropertyConfigurator().doConfigure(properties, LogManager::getLoggerRepository()); } #if APR_HAS_THREADS void PropertyConfigurator::configureAndWatch(const File& configFilename) { configureAndWatch(configFilename, FileWatchdog::DEFAULT_DELAY); } void PropertyConfigurator::configureAndWatch( const File& configFilename, long delay) { if (pdog) { APRInitializer::unregisterCleanup(pdog); delete pdog; } pdog = new PropertyWatchdog(configFilename); APRInitializer::registerCleanup(pdog); pdog->setDelay(delay); pdog->start(); } #endif void 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("].")); } static const LogString STRINGSTREAM_KEY(LOG4CXX_STR("log4j.stringstream")); LogString strstrValue(properties.getProperty(STRINGSTREAM_KEY)); if (strstrValue == LOG4CXX_STR("static")) { MessageBufferUseStaticStream(); } 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(); } 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 ); if (appender == 0) { 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("\".")); //configureOptionHandler(layout, layoutPrefix + ".", props); PropertySetter::setProperties(layout, props, layoutPrefix + LOG4CXX_STR("."), p); LogLog::debug((LogString) LOG4CXX_STR("End of parsing for \"") + appenderName + LOG4CXX_STR("\".")); } } //configureOptionHandler((OptionHandler) appender, prefix + _T("."), props); 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-0.12.1/src/main/cpp/filterbasedtriggeringpolicy.cpp000644 001750 001750 00000005050 14120250670 026022 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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) FilterBasedTriggeringPolicy::FilterBasedTriggeringPolicy() { } FilterBasedTriggeringPolicy::~FilterBasedTriggeringPolicy() { } bool FilterBasedTriggeringPolicy::isTriggeringEvent( Appender* /* appender */, const log4cxx::spi::LoggingEventPtr& event, const LogString& /* filename */, size_t /* fileLength */ ) { if (headFilter == NULL) { return false; } for (log4cxx::spi::FilterPtr f = 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 (headFilter == NULL) { headFilter = newFilter; tailFilter = newFilter; } else { tailFilter->setNext(newFilter); tailFilter = newFilter; } } void FilterBasedTriggeringPolicy::clearFilters() { log4cxx::spi::FilterPtr empty; headFilter = empty; tailFilter = empty; } log4cxx::spi::FilterPtr& FilterBasedTriggeringPolicy::getFilter() { return headFilter; } /** * Prepares the instance for use. */ void FilterBasedTriggeringPolicy::activateOptions(log4cxx::helpers::Pool& p) { for (log4cxx::spi::FilterPtr f = headFilter; f != NULL; f = f->getNext()) { f->activateOptions(p); } } void FilterBasedTriggeringPolicy::setOption(const LogString& /* option */, const LogString& /* value */ ) { } apache-log4cxx-0.12.1/src/main/cpp/loggingevent.cpp000644 001750 001750 00000021530 14120250670 022725 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(LoggingEvent) // // Accessor for start time. // log4cxx_time_t LoggingEvent::getStartTime() { return log4cxx::helpers::APRInitializer::initialize(); } LoggingEvent::LoggingEvent() : ndc(0), mdcCopy(0), properties(0), ndcLookupRequired(true), mdcCopyLookupRequired(true), timeStamp(0), locationInfo() { } LoggingEvent::LoggingEvent( 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(apr_time_now()), locationInfo(locationInfo1), threadName(getCurrentThreadName()) { } LoggingEvent::~LoggingEvent() { delete ndc; delete mdcCopy; delete properties; } bool LoggingEvent::getNDC(LogString& dest) const { if (ndcLookupRequired) { ndcLookupRequired = false; LogString val; if (NDC::get(val)) { ndc = new LogString(val); } } if (ndc) { dest.append(*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 (mdcCopy != 0 && !mdcCopy->empty()) { MDC::Map::const_iterator it = mdcCopy->find(key); if (it != 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 (mdcCopy != 0 && !mdcCopy->empty()) { MDC::Map::const_iterator it; for (it = mdcCopy->begin(); it != 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 (mdcCopyLookupRequired) { mdcCopyLookupRequired = false; // the clone call is required for asynchronous logging. ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { mdcCopy = new MDC::Map(data->getMap()); } else { mdcCopy = new MDC::Map(); } } } bool LoggingEvent::getProperty(const LogString& key, LogString& dest) const { if (properties == 0) { return false; } std::map::const_iterator it = properties->find(key); if (it != properties->end()) { dest.append(it->second); return true; } return false; } LoggingEvent::KeySet LoggingEvent::getPropertyKeySet() const { LoggingEvent::KeySet set; if (properties != 0) { std::map::const_iterator it; for (it = properties->begin(); it != properties->end(); it++) { set.push_back(it->first); } } return set; } const LogString LoggingEvent::getCurrentThreadName() { #if APR_HAS_THREADS LOG4CXX_THREAD_LOCAL LogString thread_name; if( thread_name.size() ){ return thread_name; } #if defined(_WIN32) char result[20]; DWORD threadId = GetCurrentThreadId(); 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_os_thread_t threadId = apr_os_thread_current(); apr_snprintf(result, sizeof(result), LOG4CXX_APR_THREAD_FMTSPEC, (void*) &threadId); #endif /* _WIN32 */ log4cxx::helpers::Transcoder::decode(reinterpret_cast(result), thread_name); return thread_name; #else return LOG4CXX_STR("0x00000000"); #endif /* APR_HAS_THREADS */ } void LoggingEvent::setProperty(const LogString& key, const LogString& value) { if (properties == 0) { properties = new std::map; } (*properties)[key] = value; } void LoggingEvent::writeProlog(ObjectOutputStream& os, Pool& p) { unsigned char classDesc[] = { 0x72, 0x00, 0x21, 0x6F, 0x72, 0x67, 0x2E, 0x61, 0x70, 0x61, 0x63, 0x68, 0x65, 0x2E, 0x6C, 0x6F, 0x67, 0x34, 0x6A, 0x2E, 0x73, 0x70, 0x69, 0x2E, 0x4C, 0x6F, 0x67, 0x67, 0x69, 0x6E, 0x67, 0x45, 0x76, 0x65, 0x6E, 0x74, 0xF3, 0xF2, 0xB9, 0x23, 0x74, 0x0B, 0xB5, 0x3F, 0x03, 0x00, 0x0A, 0x5A, 0x00, 0x15, 0x6D, 0x64, 0x63, 0x43, 0x6F, 0x70, 0x79, 0x4C, 0x6F, 0x6F, 0x6B, 0x75, 0x70, 0x52, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x5A, 0x00, 0x11, 0x6E, 0x64, 0x63, 0x4C, 0x6F, 0x6F, 0x6B, 0x75, 0x70, 0x52, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x4A, 0x00, 0x09, 0x74, 0x69, 0x6D, 0x65, 0x53, 0x74, 0x61, 0x6D, 0x70, 0x4C, 0x00, 0x0C, 0x63, 0x61, 0x74, 0x65, 0x67, 0x6F, 0x72, 0x79, 0x4E, 0x61, 0x6D, 0x65, 0x74, 0x00, 0x12, 0x4C, 0x6A, 0x61, 0x76, 0x61, 0x2F, 0x6C, 0x61, 0x6E, 0x67, 0x2F, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x3B, 0x4C, 0x00, 0x0C, 0x6C, 0x6F, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x49, 0x6E, 0x66, 0x6F, 0x74, 0x00, 0x23, 0x4C, 0x6F, 0x72, 0x67, 0x2F, 0x61, 0x70, 0x61, 0x63, 0x68, 0x65, 0x2F, 0x6C, 0x6F, 0x67, 0x34, 0x6A, 0x2F, 0x73, 0x70, 0x69, 0x2F, 0x4C, 0x6F, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x49, 0x6E, 0x66, 0x6F, 0x3B, 0x4C, 0x00, 0x07, 0x6D, 0x64, 0x63, 0x43, 0x6F, 0x70, 0x79, 0x74, 0x00, 0x15, 0x4C, 0x6A, 0x61, 0x76, 0x61, 0x2F, 0x75, 0x74, 0x69, 0x6C, 0x2F, 0x48, 0x61, 0x73, 0x68, 0x74, 0x61, 0x62, 0x6C, 0x65, 0x3B, 0x4C, 0x00, 0x03, 0x6E, 0x64, 0x63, 0x74, 0x00, 0x12, 0x4C, 0x6A, 0x61, 0x76, 0x61, 0x2F, 0x6C, 0x61, 0x6E, 0x67, 0x2F, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x3B, 0x4C, 0x00, 0x0F, 0x72, 0x65, 0x6E, 0x64, 0x65, 0x72, 0x65, 0x64, 0x4D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x74, 0x00, 0x12, 0x4C, 0x6A, 0x61, 0x76, 0x61, 0x2F, 0x6C, 0x61, 0x6E, 0x67, 0x2F, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x3B, 0x4C, 0x00, 0x0A, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x4E, 0x61, 0x6D, 0x65, 0x74, 0x00, 0x12, 0x4C, 0x6A, 0x61, 0x76, 0x61, 0x2F, 0x6C, 0x61, 0x6E, 0x67, 0x2F, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x3B, 0x4C, 0x00, 0x0D, 0x74, 0x68, 0x72, 0x6F, 0x77, 0x61, 0x62, 0x6C, 0x65, 0x49, 0x6E, 0x66, 0x6F, 0x74, 0x00, 0x2B, 0x4C, 0x6F, 0x72, 0x67, 0x2F, 0x61, 0x70, 0x61, 0x63, 0x68, 0x65, 0x2F, 0x6C, 0x6F, 0x67, 0x34, 0x6A, 0x2F, 0x73, 0x70, 0x69, 0x2F, 0x54, 0x68, 0x72, 0x6F, 0x77, 0x61, 0x62, 0x6C, 0x65, 0x49, 0x6E, 0x66, 0x6F, 0x72, 0x6D, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x3B, 0x78, 0x70 }; os.writeProlog("org.apache.log4j.spi.LoggingEvent", 8, (char*) classDesc, sizeof(classDesc), p); } void LoggingEvent::write(helpers::ObjectOutputStream& os, Pool& p) const { writeProlog(os, p); // mdc and ndc lookup required should always be false char lookupsRequired[] = { 0, 0 }; os.writeBytes(lookupsRequired, sizeof(lookupsRequired), p); os.writeLong(timeStamp / 1000, p); os.writeObject(logger, p); locationInfo.write(os, p); if (mdcCopy == 0 || mdcCopy->size() == 0) { os.writeNull(p); } else { os.writeObject(*mdcCopy, p); } if (ndc == 0) { os.writeNull(p); } else { os.writeObject(*ndc, p); } os.writeObject(message, p); os.writeObject(threadName, p); // throwable os.writeNull(p); os.writeByte(ObjectOutputStream::TC_BLOCKDATA, p); os.writeByte(0x04, p); os.writeInt(level->toInt(), p); os.writeNull(p); os.writeByte(ObjectOutputStream::TC_ENDBLOCKDATA, p); } apache-log4cxx-0.12.1/src/main/cpp/fileoutputstream.cpp000644 001750 001750 00000005320 14120250670 023650 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; IMPLEMENT_LOG4CXX_OBJECT(FileOutputStream) FileOutputStream::FileOutputStream(const LogString& filename, bool append) : pool(), fileptr(open(filename, append, pool)) { } FileOutputStream::FileOutputStream(const logchar* filename, bool append) : pool(), fileptr(open(filename, append, 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 (fileptr != NULL && !APRInitializer::isDestructed) { apr_file_close(fileptr); } } void FileOutputStream::close(Pool& /* p */) { if (fileptr != NULL) { apr_status_t stat = apr_file_close(fileptr); if (stat != APR_SUCCESS) { throw IOException(stat); } fileptr = NULL; } } void FileOutputStream::flush(Pool& /* p */) { } void FileOutputStream::write(ByteBuffer& buf, Pool& /* p */ ) { if (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( fileptr, data + pos, &nbytes); if (stat != APR_SUCCESS) { throw IOException(stat); } pos += nbytes; buf.position(pos); nbytes = buf.remaining(); } } apache-log4cxx-0.12.1/src/main/cpp/filewatchdog.cpp000644 001750 001750 00000004537 14122472113 022705 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 using namespace log4cxx; using namespace log4cxx::helpers; long FileWatchdog::DEFAULT_DELAY = 60000; FileWatchdog::FileWatchdog(const File& file1) : file(file1), delay(DEFAULT_DELAY), lastModif(0), warnedAlready(false), interrupted(0), thread() { } FileWatchdog::~FileWatchdog() { interrupted = 0xFFFF; { std::unique_lock lock(interrupt_mutex); interrupt.notify_all(); } thread.join(); } void FileWatchdog::checkAndConfigure() { Pool pool1; if (!file.exists(pool1)) { if (!warnedAlready) { LogLog::debug(((LogString) LOG4CXX_STR("[")) + file.getPath() + LOG4CXX_STR("] does not exist.")); warnedAlready = true; } } else { apr_time_t thisMod = file.lastModified(pool1); if (thisMod > lastModif) { lastModif = thisMod; doOnChange(); warnedAlready = false; } } } void FileWatchdog::run() { while (interrupted != 0xFFFF) { std::unique_lock lock( interrupt_mutex ); interrupt.wait_for( lock, std::chrono::milliseconds( delay ), std::bind(&FileWatchdog::is_interrupted, this) ); checkAndConfigure(); } } void FileWatchdog::start() { checkAndConfigure(); thread = std::thread( &FileWatchdog::run, this ); } bool FileWatchdog::is_interrupted() { return interrupted == 0xFFFF; } apache-log4cxx-0.12.1/src/main/cpp/resourcebundle.cpp000644 001750 001750 00000006247 14120250670 023266 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 = PropertyResourceBundlePtr(new PropertyResourceBundle(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-0.12.1/src/main/cpp/exception.cpp000644 001750 001750 00000024577 14120250670 022251 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; 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 strcpy(msg, src.msg); #endif } Exception& Exception::operator=(const Exception& src) { #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) strcpy_s(msg, sizeof msg, src.msg); #else strcpy(msg, src.msg); #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) { LogString s(LOG4CXX_STR("IO Exception : status code = ")); Pool p; StringHelper::toString(stat, p, s); 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-0.12.1/src/main/cpp/bytearrayinputstream.cpp000644 001750 001750 00000003242 14120250670 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. */ #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace std; IMPLEMENT_LOG4CXX_OBJECT(ByteArrayInputStream) ByteArrayInputStream::ByteArrayInputStream(const std::vector& bytes) : buf(bytes), pos(0) { } ByteArrayInputStream::~ByteArrayInputStream() { } void ByteArrayInputStream::close() { } int ByteArrayInputStream::read(ByteBuffer& dst) { if (pos >= buf.size()) { return -1; } else { size_t bytesCopied = min(dst.remaining(), buf.size() - pos); std::memcpy(dst.current(), &buf[pos], bytesCopied); pos += bytesCopied; dst.position(dst.position() + bytesCopied); return (int)bytesCopied; } } apache-log4cxx-0.12.1/src/main/cpp/loader.cpp000644 001750 001750 00000004613 14120250670 021506 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 InputStreamPtr( new FileInputStream(name) ); } catch (const IOException&) { } return 0; } apache-log4cxx-0.12.1/src/main/cpp/loggingeventpatternconverter.cpp000644 001750 001750 00000003161 14120250670 026253 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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) { } 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-0.12.1/src/main/cpp/rolloverdescription.cpp000644 001750 001750 00000003471 14120250670 024351 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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) RolloverDescription::RolloverDescription() { } RolloverDescription::RolloverDescription( const LogString& activeFileName1, const bool append1, const ActionPtr& synchronous1, const ActionPtr& asynchronous1) : activeFileName(activeFileName1), append(append1), synchronous(synchronous1), asynchronous(asynchronous1) { } LogString RolloverDescription::getActiveFileName() const { return activeFileName; } bool RolloverDescription::getAppend() const { return append; } ActionPtr RolloverDescription::getSynchronous() const { return synchronous; } /** * Action to be completed after close of current active log file * and before next rollover attempt, may be executed asynchronously. * * @return action, may be null. */ ActionPtr RolloverDescription::getAsynchronous() const { return asynchronous; } apache-log4cxx-0.12.1/src/main/cpp/socket.cpp000644 001750 001750 00000007051 14120250670 021527 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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_signal.h" using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(Socket) /** Creates a stream socket and connects it to the specified port number at the specified IP address. */ Socket::Socket(InetAddressPtr& addr, int prt) : pool(), socket(0), address(addr), port(prt) { apr_status_t status = apr_socket_create(&socket, APR_INET, SOCK_STREAM, APR_PROTO_TCP, pool.getAPRPool()); if (status != APR_SUCCESS) { throw SocketException(status); } LOG4CXX_ENCODE_CHAR(host, addr->getHostAddress()); // create socket address (including port) apr_sockaddr_t* client_addr; status = apr_sockaddr_info_get(&client_addr, host.c_str(), APR_INET, prt, 0, pool.getAPRPool()); if (status != APR_SUCCESS) { throw ConnectException(status); } // connect the socket status = apr_socket_connect(socket, client_addr); if (status != APR_SUCCESS) { throw ConnectException(status); } } Socket::Socket(apr_socket_t* s, apr_pool_t* p) : pool(p, true), socket(s) { apr_sockaddr_t* sa; apr_status_t status = apr_socket_addr_get(&sa, APR_REMOTE, s); if (status == APR_SUCCESS) { 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); } address = InetAddressPtr(new InetAddress(remotename, remoteip)); } } Socket::~Socket() { } size_t Socket::write(ByteBuffer& buf) { if (socket == 0) { throw ClosedChannelException(); } int 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(socket, buf.current(), &written); apr_signal(SIGPIPE, old); #else apr_status_t status = apr_socket_send(socket, buf.current(), &written); #endif buf.position(buf.position() + written); totalWritten += written; if (status != APR_SUCCESS) { throw SocketException(status); } } return totalWritten; } void Socket::close() { if (socket != 0) { apr_status_t status = apr_socket_close(socket); if (status != APR_SUCCESS) { throw SocketException(status); } socket = 0; } } InetAddressPtr Socket::getInetAddress() const { return address; } int Socket::getPort() const { return port; } apache-log4cxx-0.12.1/src/main/cpp/rollingpolicybase.cpp000644 001750 001750 00000010616 14120250670 023761 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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() { } RollingPolicyBase::~RollingPolicyBase() { } void RollingPolicyBase::activateOptions(log4cxx::helpers::Pool& /* pool */) { if (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"))) { fileNamePatternStr = value; } } void RollingPolicyBase::setFileNamePattern(const LogString& fnp) { fileNamePatternStr = fnp; } LogString RollingPolicyBase::getFileNamePattern() const { return fileNamePatternStr; } /** * Parse file name pattern. */ void RollingPolicyBase::parseFileNamePattern() { patternConverters.erase(patternConverters.begin(), patternConverters.end()); patternFields.erase(patternFields.begin(), patternFields.end()); PatternParser::parse(fileNamePatternStr, patternConverters, 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( ObjectPtr& obj, LogString& toAppendTo, Pool& pool) const { std::vector::const_iterator formatterIter = patternFields.begin(); for (std::vector::const_iterator converterIter = patternConverters.begin(); converterIter != patternConverters.end(); converterIter++, formatterIter++) { int startField = toAppendTo.length(); (*converterIter)->format(obj, toAppendTo, pool); (*formatterIter)->format(startField, toAppendTo); } } PatternConverterPtr RollingPolicyBase::getIntegerPatternConverter() const { for (std::vector::const_iterator converterIter = patternConverters.begin(); converterIter != 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 = patternConverters.begin(); converterIter != patternConverters.end(); converterIter++) { DatePatternConverterPtr datePattern; PatternConverterPtr patternptr = (*converterIter); datePattern = log4cxx::cast(patternptr); if (datePattern != NULL) { return *converterIter; } } PatternConverterPtr noMatch; return noMatch; } apache-log4cxx-0.12.1/src/main/cpp/dailyrollingfileappender.cpp000644 001750 001750 00000005670 14120250670 025314 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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::rolling; IMPLEMENT_LOG4CXX_OBJECT(DailyRollingFileAppender) DailyRollingFileAppender::DailyRollingFileAppender() { } DailyRollingFileAppender::DailyRollingFileAppender( const LayoutPtr& l, const LogString& filename, const LogString& datePattern1) : datePattern(datePattern1) { setLayout(l); setFile(filename); Pool p; activateOptions(p); } void DailyRollingFileAppender::setDatePattern(const LogString& newPattern) { datePattern = newPattern; } LogString DailyRollingFileAppender::getDatePattern() const { return datePattern; } void DailyRollingFileAppender::activateOptions(log4cxx::helpers::Pool& p) { TimeBasedRollingPolicyPtr policy = TimeBasedRollingPolicyPtr( new TimeBasedRollingPolicy() ); LogString pattern(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) { pattern.append(1, (logchar) 0x7D /* '}' */); inPattern = false; } } else { if (!inLiteral && !inPattern) { const logchar dbrace[] = { 0x25, 0x64, 0x7B, 0 }; // "%d{" pattern.append(dbrace); inPattern = true; } pattern.append(1, datePattern[i]); } } if (inPattern) { pattern.append(1, (logchar) 0x7D /* '}' */); } policy->setFileNamePattern(pattern); policy->activateOptions(p); setTriggeringPolicy(policy); setRollingPolicy(policy); RollingFileAppenderSkeleton::activateOptions(p); } void DailyRollingFileAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("DATEPATTERN"), LOG4CXX_STR("datepattern"))) { setDatePattern(value); } else { RollingFileAppenderSkeleton::setOption(option, value); } } apache-log4cxx-0.12.1/src/main/cpp/sockethubappender.cpp000644 001750 001750 00000013322 14122472113 023743 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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::spi; IMPLEMENT_LOG4CXX_OBJECT(SocketHubAppender) int SocketHubAppender::DEFAULT_PORT = 4560; SocketHubAppender::~SocketHubAppender() { finalize(); } SocketHubAppender::SocketHubAppender() : port(DEFAULT_PORT), streams(), locationInfo(false), thread() { } SocketHubAppender::SocketHubAppender(int port1) : port(port1), streams(), locationInfo(false), thread() { startServer(); } void SocketHubAppender::activateOptions(Pool& /* p */ ) { startServer(); } void SocketHubAppender::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("LOCATIONINFO"), LOG4CXX_STR("locationinfo"))) { setLocationInfo(OptionConverter::toBoolean(value, true)); } else { AppenderSkeleton::setOption(option, value); } } void SocketHubAppender::close() { { std::unique_lock lock(mutex); if (closed) { return; } closed = true; } LogLog::debug(LOG4CXX_STR("closing SocketHubAppender ") + getName()); // // wait until the server thread completes // if ( thread.joinable() ) { thread.join(); } std::unique_lock lock(mutex); // close all of the connections LogLog::debug(LOG4CXX_STR("closing client connections")); for (std::vector::iterator iter = streams.begin(); iter != streams.end(); iter++) { if ( (*iter) != NULL) { try { (*iter)->close(pool); } catch (SocketException& e) { LogLog::error(LOG4CXX_STR("could not close socket: "), e); } } } streams.erase(streams.begin(), streams.end()); LogLog::debug(LOG4CXX_STR("SocketHubAppender ") + getName() + LOG4CXX_STR(" closed")); } void SocketHubAppender::append(const spi::LoggingEventPtr& event, Pool& p) { // if no open connections, exit now if (streams.empty()) { return; } LogString ndcVal; event->getNDC(ndcVal); event->getThreadName(); // Get a copy of this thread's MDC. event->getMDCCopy(); // loop through the current set of open connections, appending the event to each std::vector::iterator it = streams.begin(); std::vector::iterator itEnd = streams.end(); while (it != itEnd) { // list size changed unexpectedly? Just exit the append. if (*it == 0) { break; } try { event->write(**it, p); (*it)->flush(p); it++; } catch (std::exception& e) { // there was an io exception so just drop the connection it = streams.erase(it); itEnd = streams.end(); LogLog::debug(LOG4CXX_STR("dropped connection"), e); } } } void SocketHubAppender::startServer() { thread = std::thread( &SocketHubAppender::monitor, this ); } void SocketHubAppender::monitor() { ServerSocket* serverSocket = 0; try { serverSocket = new ServerSocket(port); serverSocket->setSoTimeout(1000); } catch (SocketException& e) { LogLog::error(LOG4CXX_STR("exception setting timeout, shutting down server socket."), e); delete serverSocket; return; } bool stopRunning = closed; while (!stopRunning) { SocketPtr socket; try { socket = serverSocket->accept(); } catch (InterruptedIOException&) { // timeout occurred, so just loop } catch (SocketException& e) { LogLog::error(LOG4CXX_STR("exception accepting socket, shutting down server socket."), e); stopRunning = true; } catch (IOException& e) { LogLog::error(LOG4CXX_STR("exception accepting socket."), e); } // if there was a socket accepted if (socket != 0) { try { InetAddressPtr remoteAddress = socket->getInetAddress(); LogLog::debug(LOG4CXX_STR("accepting connection from ") + remoteAddress->getHostName() + LOG4CXX_STR(" (") + remoteAddress->getHostAddress() + LOG4CXX_STR(")")); // add it to the oosList. std::unique_lock lock(mutex); OutputStreamPtr os(new SocketOutputStream(socket)); Pool p; ObjectOutputStreamPtr oos(new ObjectOutputStream(os, p)); streams.push_back(oos); } catch (IOException& e) { LogLog::error(LOG4CXX_STR("exception creating output stream on socket."), e); } } stopRunning = (stopRunning || closed); } delete serverSocket; } apache-log4cxx-0.12.1/src/main/cpp/outputstreamwriter.cpp000644 001750 001750 00000005014 14120250670 024245 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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) OutputStreamWriter::OutputStreamWriter(OutputStreamPtr& out1) : out(out1), enc(CharsetEncoder::getDefaultEncoder()) { if (out1 == 0) { throw NullPointerException(LOG4CXX_STR("out parameter may not be null.")); } } OutputStreamWriter::OutputStreamWriter(OutputStreamPtr& out1, CharsetEncoderPtr& enc1) : out(out1), enc(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) { out->close(p); } void OutputStreamWriter::flush(Pool& p) { out->flush(p); } void OutputStreamWriter::write(const LogString& str, Pool& p) { if (str.length() > 0) { #ifdef LOG4CXX_MULTI_PROCESS 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 enc->reset(); LogString::const_iterator iter = str.begin(); while (iter != str.end()) { CharsetEncoder::encode(enc, str, iter, buf); buf.flip(); out->write(buf, p); buf.clear(); } CharsetEncoder::encode(enc, str, iter, buf); enc->flush(buf); buf.flip(); out->write(buf, p); #ifdef LOG4CXX_MULTI_PROCESS delete []rawbuf; #endif } } apache-log4cxx-0.12.1/src/main/cpp/outputstream.cpp000644 001750 001750 00000002607 14120250670 023015 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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() { } #ifdef LOG4CXX_MULTI_PROCESS apr_file_t* OutputStream::getFilePtr() { throw std::logic_error("getFilePtr must be implemented in the derived class that you are using"); } OutputStream& OutputStream::getFileOutPutStreamPtr() { throw std::logic_error("getFileOutPutStreamPtr must be implemented in the derived class that you are using"); } #endif apache-log4cxx-0.12.1/src/main/cpp/obsoleterollingfileappender.cpp000644 001750 001750 00000011114 14120250670 026014 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; using namespace log4cxx::spi; namespace log4cxx { class ClassRollingFileAppender : public Class { public: ClassRollingFileAppender() : helpers::Class() {} virtual LogString getName() const { return LOG4CXX_STR("org.apache.log4j.RollingFileAppender"); } virtual Object* newInstance() const { return new RollingFileAppender(); } }; } const log4cxx::helpers::Class& RollingFileAppender::getClass() const { return getStaticClass(); } const log4cxx::helpers::Class& RollingFileAppender::getStaticClass() { static ClassRollingFileAppender theClass; return theClass; } const log4cxx::helpers::ClassRegistration& RollingFileAppender::registerClass() { static log4cxx::helpers::ClassRegistration classReg(RollingFileAppender::getStaticClass); return classReg; } namespace log4cxx { namespace classes { const log4cxx::helpers::ClassRegistration& ObsoleteRollingFileAppenderRegistration = RollingFileAppender::registerClass(); } } RollingFileAppender::RollingFileAppender() : maxFileSize(10 * 1024 * 1024), maxBackupIndex(1) { } RollingFileAppender::RollingFileAppender( const LayoutPtr& newLayout, const LogString& filename, bool append) : maxFileSize(10 * 1024 * 1024), maxBackupIndex(1) { setLayout(newLayout); setFile(filename); setAppend(append); Pool p; activateOptions(p); } RollingFileAppender::RollingFileAppender(const LayoutPtr& newLayout, const LogString& filename) : maxFileSize(10 * 1024 * 1024), maxBackupIndex(1) { setLayout(newLayout); setFile(filename); Pool p; activateOptions(p); } RollingFileAppender::~RollingFileAppender() { } 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"))) { maxBackupIndex = StringHelper::toInt(value); } else { using namespace log4cxx::rolling; RollingFileAppenderSkeleton::setOption(option, value); } } int RollingFileAppender::getMaxBackupIndex() const { return maxBackupIndex; } long RollingFileAppender::getMaximumFileSize() const { return maxFileSize; } void RollingFileAppender::setMaxBackupIndex(int maxBackups) { maxBackupIndex = maxBackups; } void RollingFileAppender::setMaximumFileSize(int maxFileSize1) { maxFileSize = maxFileSize1; } void RollingFileAppender::setMaxFileSize(const LogString& value) { maxFileSize = OptionConverter::toFileSize(value, maxFileSize + 1); } void RollingFileAppender::activateOptions(Pool& p) { log4cxx::rolling::SizeBasedTriggeringPolicyPtr trigger( new log4cxx::rolling::SizeBasedTriggeringPolicy()); trigger->setMaxFileSize(maxFileSize); trigger->activateOptions(p); setTriggeringPolicy(trigger); log4cxx::rolling::FixedWindowRollingPolicyPtr rolling( new log4cxx::rolling::FixedWindowRollingPolicy()); rolling->setMinIndex(1); rolling->setMaxIndex(maxBackupIndex); rolling->setFileNamePattern(getFile() + LOG4CXX_STR(".%i")); rolling->activateOptions(p); setRollingPolicy(rolling); using namespace log4cxx::rolling; RollingFileAppenderSkeleton::activateOptions(p); } apache-log4cxx-0.12.1/src/main/cpp/triggeringpolicy.cpp000644 001750 001750 00000002007 14120250670 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 using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(TriggeringPolicy) TriggeringPolicy::~TriggeringPolicy() { } apache-log4cxx-0.12.1/src/main/cpp/timezone.cpp000644 001750 001750 00000014411 14120250670 022067 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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( new GMTTimeZone() ); 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; } private: 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( new LocalTimeZone() ); 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; } private: LocalTimeZone() : TimeZone( getTimeZoneName() ) { } 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 TimeZonePtr(new log4cxx::helpers::TimeZoneImpl::FixedTimeZone( s, offset )); } const TimeZonePtr& ltz = getDefault(); if ( ltz->getID() == id ) { return ltz; } return getGMT(); } apache-log4cxx-0.12.1/src/main/cpp/zipcompressaction.cpp000644 001750 001750 00000005355 14120250670 024020 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(ZipCompressAction) ZipCompressAction::ZipCompressAction(const File& src, const File& dest, bool del) : source(src), destination(dest), deleteSource(del) { } bool ZipCompressAction::execute(log4cxx::helpers::Pool& p) const { if (!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(destination.getPath(), p); args[i++] = Transcoder::encode(source.getPath(), p); args[i++] = NULL; if (destination.exists(p)) { destination.deleteFile(p); } apr_proc_t pid; stat = apr_proc_create(&pid, "zip", args, NULL, attr, aprpool); if (stat != APR_SUCCESS) { throw IOException(stat); } int exitCode; apr_proc_wait(&pid, &exitCode, NULL, APR_WAIT); if (exitCode != APR_SUCCESS) { throw IOException(exitCode); } if (deleteSource) { source.deleteFile(p); } return true; } apache-log4cxx-0.12.1/src/main/cpp/outputdebugstringappender.cpp000644 001750 001750 00000002663 14120250670 025560 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 "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; 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-0.12.1/src/main/cpp/defaultloggerfactory.cpp000644 001750 001750 00000002166 14120250670 024455 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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 LoggerPtr(new Logger(pool, name)); } apache-log4cxx-0.12.1/src/main/cpp/socketappenderskeleton.cpp000644 001750 001750 00000013051 14122472113 025010 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #define __STDC_CONSTANT_MACROS #include #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; SocketAppenderSkeleton::SocketAppenderSkeleton(int defaultPort, int reconnectionDelay1) : remoteHost(), address(), port(defaultPort), reconnectionDelay(reconnectionDelay1), locationInfo(false), thread() { } SocketAppenderSkeleton::SocketAppenderSkeleton(InetAddressPtr address1, int port1, int delay) : remoteHost(), address(address1), port(port1), reconnectionDelay(delay), locationInfo(false), thread() { remoteHost = this->address->getHostName(); } SocketAppenderSkeleton::SocketAppenderSkeleton(const LogString& host, int port1, int delay) : remoteHost(host), address(InetAddress::getByName(host)), port(port1), reconnectionDelay(delay), locationInfo(false), thread() { } SocketAppenderSkeleton::~SocketAppenderSkeleton() { finalize(); } void SocketAppenderSkeleton::activateOptions(Pool& p) { AppenderSkeleton::activateOptions(p); connect(p); } void SocketAppenderSkeleton::close() { std::unique_lock lock(mutex); if (closed) { return; } closed = true; cleanUp(pool); { std::unique_lock lock2(interrupt_mutex); interrupt.notify_all(); } if ( thread.joinable() ) { thread.join(); } } void SocketAppenderSkeleton::connect(Pool& p) { if (address == 0) { LogLog::error(LogString(LOG4CXX_STR("No remote host is set for Appender named \"")) + name + LOG4CXX_STR("\".")); } else { cleanUp(p); try { SocketPtr socket(new Socket(address, port)); setSocket(socket, p); } catch (SocketException& e) { LogString msg = LOG4CXX_STR("Could not connect to remote log4cxx server at [") + address->getHostName() + LOG4CXX_STR("]."); if (reconnectionDelay > 0) { msg += LOG4CXX_STR(" We will try again later. "); } 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::unique_lock lock(mutex); if ( !thread.joinable() ) { LogLog::debug(LOG4CXX_STR("Connector thread not alive: starting monitor.")); thread = std::thread( &SocketAppenderSkeleton::monitor, this ); } } void SocketAppenderSkeleton::monitor() { SocketPtr socket; bool isClosed = closed; while (!isClosed) { try { std::this_thread::sleep_for( std::chrono::milliseconds( reconnectionDelay ) ); std::unique_lock lock( interrupt_mutex ); interrupt.wait_for( lock, std::chrono::milliseconds( reconnectionDelay ), std::bind(&SocketAppenderSkeleton::is_closed, this) ); if (!closed) { LogLog::debug(LogString(LOG4CXX_STR("Attempting connection to ")) + address->getHostName()); socket = SocketPtr(new Socket(address, port)); Pool p; setSocket(socket, p); LogLog::debug(LOG4CXX_STR("Connection established. Exiting connector thread.")); } return; } catch (InterruptedException&) { LogLog::debug(LOG4CXX_STR("Connector interrupted. Leaving loop.")); return; } catch (ConnectException&) { LogLog::debug(LOG4CXX_STR("Remote host ") + 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 ")) + address->getHostName() + LOG4CXX_STR(". Exception is ") + exmsg); } isClosed = closed; } LogLog::debug(LOG4CXX_STR("Exiting Connector.run() method.")); } bool SocketAppenderSkeleton::is_closed() { return closed; } apache-log4cxx-0.12.1/src/main/cpp/serversocket.cpp000644 001750 001750 00000007044 14120250670 022760 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include "apr_network_io.h" #include "apr_pools.h" #include "apr_poll.h" using namespace log4cxx::helpers; /** Creates a server socket on a specified port. */ ServerSocket::ServerSocket(int port) : pool(), socket(0), timeout(0) { apr_status_t status = apr_socket_create(&socket, APR_INET, SOCK_STREAM, APR_PROTO_TCP, pool.getAPRPool()); if (status != APR_SUCCESS) { throw SocketException(status); } status = apr_socket_opt_set(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, pool.getAPRPool()); if (status != APR_SUCCESS) { throw ConnectException(status); } // bind the socket to the address status = apr_socket_bind(socket, server_addr); if (status != APR_SUCCESS) { throw BindException(status); } status = apr_socket_listen(socket, 50); if (status != APR_SUCCESS) { throw SocketException(status); } } ServerSocket::~ServerSocket() { } void ServerSocket::close() { std::unique_lock lock(mutex); if (socket != 0) { apr_status_t status = apr_socket_close(socket); if (status != APR_SUCCESS) { throw SocketException(status); } socket = 0; } } /** Listens for a connection to be made to this socket and accepts it */ SocketPtr ServerSocket::accept() { std::unique_lock lock(mutex); if (socket == 0) { throw IOException(); } apr_pollfd_t poll; poll.p = pool.getAPRPool(); poll.desc_type = APR_POLL_SOCKET; poll.reqevents = APR_POLLIN; poll.rtnevents = 0; poll.desc.s = socket; poll.client_data = NULL; apr_int32_t signaled; apr_interval_time_t to = 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, 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 SocketPtr(new Socket(newSocket, newPool)); } /** Retrive setting for SO_TIMEOUT. */ int ServerSocket::getSoTimeout() const { return timeout; } /** Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. */ void ServerSocket::setSoTimeout(int newVal) { timeout = newVal; } apache-log4cxx-0.12.1/src/main/cpp/defaultconfigurator.cpp000644 001750 001750 00000006630 14120250670 024310 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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::spi; using namespace log4cxx::helpers; void DefaultConfigurator::configure(LoggerRepositoryPtr repository) { repository->setConfigured(true); const LogString configuratorClassName(getConfiguratorClass()); LogString configurationOptionStr(getConfigurationFileName()); Pool pool; File configuration; if (configurationOptionStr.empty()) { const char* names[] = { "log4cxx.xml", "log4cxx.properties", "log4j.xml", "log4j.properties", 0 }; for (int i = 0; names[i] != 0; i++) { File candidate(names[i]); if (candidate.exists(pool)) { configuration = candidate; break; } } } else { configuration.setPath(configurationOptionStr); } 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); } else { if (configurationOptionStr.empty()) { LogLog::debug(LOG4CXX_STR("Could not find default configuration file.")); } else { LogString msg(LOG4CXX_STR("Could not find configuration file: [")); msg += configurationOptionStr; 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 log4jConfigurationOptionStr( OptionConverter::getSystemProperty(LOG4J_DEFAULT_CONFIGURATION_KEY, LOG4CXX_STR(""))); const LogString configurationOptionStr( OptionConverter::getSystemProperty(LOG4CXX_DEFAULT_CONFIGURATION_KEY, log4jConfigurationOptionStr)); return configurationOptionStr; } apache-log4cxx-0.12.1/src/main/cpp/jsonlayout.cpp000644 001750 001750 00000021432 14120250670 022445 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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) JSONLayout::JSONLayout() : locationInfo(false), prettyPrint(false), dateFormat(), ppIndentL1(LOG4CXX_STR(" ")), ppIndentL2(LOG4CXX_STR(" ")) { } 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(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { output.append(ppIndentL1); } appendQuotedEscapedString(output, LOG4CXX_STR("timestamp")); output.append(LOG4CXX_STR(": ")); LogString timestamp; dateFormat.format(timestamp, event->getTimeStamp(), p); appendQuotedEscapedString(output, timestamp); output.append(LOG4CXX_STR(",")); output.append(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { output.append(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(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { output.append(ppIndentL1); } appendQuotedEscapedString(output, LOG4CXX_STR("logger")); output.append(LOG4CXX_STR(": ")); appendQuotedEscapedString(output, event->getLoggerName()); output.append(LOG4CXX_STR(",")); output.append(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { output.append(ppIndentL1); } appendQuotedEscapedString(output, LOG4CXX_STR("message")); output.append(LOG4CXX_STR(": ")); appendQuotedEscapedString(output, event->getMessage()); appendSerializedMDC(output, event); appendSerializedNDC(output, event); if (locationInfo) { output.append(LOG4CXX_STR(",")); output.append(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); appendSerializedLocationInfo(output, event, p); } output.append(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); output.append(LOG4CXX_STR("}")); output.append(LOG4CXX_EOL); } void JSONLayout::appendQuotedEscapedString(LogString& buf, const LogString& input) const { /* 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(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { buf.append(ppIndentL1); } appendQuotedEscapedString(buf, LOG4CXX_STR("context_map")); buf.append(LOG4CXX_STR(": {")); buf.append(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); for (LoggingEvent::KeySet::iterator it = keys.begin(); it != keys.end(); ++it) { if (prettyPrint) { buf.append(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(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); } else { buf.append(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); } } if (prettyPrint) { buf.append(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(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { buf.append(ppIndentL1); } appendQuotedEscapedString(buf, LOG4CXX_STR("context_stack")); buf.append(LOG4CXX_STR(": [")); buf.append(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { buf.append(ppIndentL2); } appendQuotedEscapedString(buf, ndcVal); buf.append(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { buf.append(ppIndentL1); } buf.append(LOG4CXX_STR("]")); } void JSONLayout::appendSerializedLocationInfo(LogString& buf, const LoggingEventPtr& event, Pool& p) const { if (prettyPrint) { buf.append(ppIndentL1); } appendQuotedEscapedString(buf, LOG4CXX_STR("location_info")); buf.append(LOG4CXX_STR(": {")); buf.append(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); const LocationInfo& locInfo = event->getLocationInformation(); if (prettyPrint) { buf.append(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(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { buf.append(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(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { buf.append(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(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { buf.append(ppIndentL2); } appendQuotedEscapedString(buf, LOG4CXX_STR("method")); buf.append(LOG4CXX_STR(": ")); LOG4CXX_DECODE_CHAR(methodName, locInfo.getMethodName()); appendQuotedEscapedString(buf, methodName); buf.append(prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (prettyPrint) { buf.append(ppIndentL1); } buf.append(LOG4CXX_STR("}")); } apache-log4cxx-0.12.1/src/main/cpp/loglog.cpp000644 001750 001750 00000006103 14120250670 021517 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 using namespace log4cxx; using namespace log4cxx::helpers; LogLog::LogLog() { debugEnabled = false; quietMode = false; } LogLog& LogLog::getInstance() { static LogLog internalLogger; return internalLogger; } void LogLog::setInternalDebugging(bool debugEnabled1) { std::unique_lock lock(getInstance().mutex); getInstance().debugEnabled = debugEnabled1; } void LogLog::debug(const LogString& msg) { if (!getInstance().debugEnabled) { return; } std::unique_lock lock(getInstance().mutex); emit(msg); } void LogLog::debug(const LogString& msg, const std::exception& e) { if (!getInstance().debugEnabled) { return; } std::unique_lock lock(getInstance().mutex); emit(msg); emit(e); } void LogLog::error(const LogString& msg) { std::unique_lock lock(getInstance().mutex); emit(msg); } void LogLog::error(const LogString& msg, const std::exception& e) { std::unique_lock lock(getInstance().mutex); emit(msg); emit(e); } void LogLog::setQuietMode(bool quietMode1) { std::unique_lock lock(getInstance().mutex); getInstance().quietMode = quietMode1; } void LogLog::warn(const LogString& msg) { std::unique_lock lock(getInstance().mutex); emit(msg); } void LogLog::warn(const LogString& msg, const std::exception& e) { std::unique_lock lock(getInstance().mutex); emit(msg); emit(e); } void LogLog::emit(const LogString& msg) { if (getInstance().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().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-0.12.1/src/main/cpp/cyclicbuffer.cpp000644 001750 001750 00000006542 14120250670 022703 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** 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) : ea(maxSize1), first(0), last(0), numElems(0), maxSize(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) { ea[last] = event; if (++last == maxSize) { last = 0; } if (numElems < maxSize) { numElems++; } else if (++first == maxSize) { 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 >= numElems) { return 0; } return ea[(first + i) % maxSize]; } /** Get the oldest (first) element in the buffer. The oldest element is removed from the buffer. */ spi::LoggingEventPtr CyclicBuffer::get() { LoggingEventPtr r; if (numElems > 0) { numElems--; r = ea[first]; ea[first] = 0; if (++first == maxSize) { 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 == numElems) { return; // nothing to do } LoggingEventList temp(newSize); int loopLen = newSize < numElems ? newSize : numElems; int i; for (i = 0; i < loopLen; i++) { temp[i] = ea[first]; ea[first] = 0; if (++first == numElems) { first = 0; } } ea = temp; first = 0; numElems = loopLen; maxSize = newSize; if (loopLen == newSize) { last = 0; } else { last = loopLen; } } apache-log4cxx-0.12.1/src/main/cpp/systemerrwriter.cpp000644 001750 001750 00000003550 14120250670 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 #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-0.12.1/src/main/cpp/asyncappender.cpp000644 001750 001750 00000021533 14122472113 023074 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(AsyncAppender) AsyncAppender::AsyncAppender() : AppenderSkeleton(), buffer(), discardMap(new DiscardMap()), bufferSize(DEFAULT_BUFFER_SIZE), appenders(new AppenderAttachableImpl(pool)), dispatcher(), locationInfo(false), blocking(true) { dispatcher = std::thread( &AsyncAppender::dispatch, this ); } AsyncAppender::~AsyncAppender() { finalize(); delete discardMap; } void AsyncAppender::addAppender(const AppenderPtr newAppender) { 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::unique_lock lock(mutex); doAppendImpl(event, pool1); } void AsyncAppender::append(const spi::LoggingEventPtr& event, Pool& p) { // // if dispatcher has died then // append subsequent events synchronously // if (!dispatcher.joinable() || bufferSize <= 0) { std::unique_lock lock(appenders->getMutex()); appenders->appendLoopOnAppenders(event, p); return; } // Set the NDC and thread name for the calling thread as these // LoggingEvent fields were not set at event creation time. LogString ndcVal; event->getNDC(ndcVal); event->getThreadName(); // Get a copy of this thread's MDC. event->getMDCCopy(); { std::unique_lock lock(bufferMutex); while (true) { size_t previousSize = buffer.size(); if (previousSize < (size_t)bufferSize) { buffer.push_back(event); if (previousSize == 0) { 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 (blocking //&& !Thread::interrupted() && (dispatcher.get_id() != std::this_thread::get_id()) ) { try { bufferNotFull.wait(lock); discard = false; } catch (InterruptedException&) { // // reset interrupt status so // calling code can see interrupt on // their next wait or sleep. //Thread::currentThreadInterrupt(); } } // // if blocking is false or thread has been interrupted // add event to discard map. // if (discard) { LogString loggerName = event->getLoggerName(); DiscardMap::iterator iter = discardMap->find(loggerName); if (iter == discardMap->end()) { DiscardSummary summary(event); discardMap->insert(DiscardMap::value_type(loggerName, summary)); } else { (*iter).second.add(event); } break; } } } } void AsyncAppender::close() { { std::unique_lock lock(bufferMutex); closed = true; bufferNotEmpty.notify_all(); bufferNotFull.notify_all(); } if ( dispatcher.joinable() ) { dispatcher.join(); } { std::unique_lock lock(appenders->getMutex()); AppenderList appenderList = appenders->getAllAppenders(); for (AppenderList::iterator iter = appenderList.begin(); iter != appenderList.end(); iter++) { (*iter)->close(); } } } AppenderList AsyncAppender::getAllAppenders() const { return appenders->getAllAppenders(); } AppenderPtr AsyncAppender::getAppender(const LogString& n) const { return appenders->getAppender(n); } bool AsyncAppender::isAttached(const AppenderPtr appender) const { return appenders->isAttached(appender); } bool AsyncAppender::requiresLayout() const { return false; } void AsyncAppender::removeAllAppenders() { appenders->removeAllAppenders(); } void AsyncAppender::removeAppender(const AppenderPtr appender) { appenders->removeAppender(appender); } void AsyncAppender::removeAppender(const LogString& n) { appenders->removeAppender(n); } bool AsyncAppender::getLocationInfo() const { return locationInfo; } void AsyncAppender::setLocationInfo(bool flag) { locationInfo = flag; } void AsyncAppender::setBufferSize(int size) { if (size < 0) { throw IllegalArgumentException(LOG4CXX_STR("size argument must be non-negative")); } std::unique_lock lock(bufferMutex); bufferSize = (size < 1) ? 1 : size; bufferNotFull.notify_all(); } int AsyncAppender::getBufferSize() const { return bufferSize; } void AsyncAppender::setBlocking(bool value) { std::unique_lock lock(bufferMutex); blocking = value; bufferNotFull.notify_all(); } bool AsyncAppender::getBlocking() const { return blocking; } AsyncAppender::DiscardSummary::DiscardSummary(const LoggingEventPtr& event) : maxEvent(event), count(1) { } AsyncAppender::DiscardSummary::DiscardSummary(const DiscardSummary& src) : maxEvent(src.maxEvent), count(src.count) { } AsyncAppender::DiscardSummary& AsyncAppender::DiscardSummary::operator=(const DiscardSummary& src) { maxEvent = src.maxEvent; count = src.count; return *this; } void AsyncAppender::DiscardSummary::add(const LoggingEventPtr& event) { if (event->getLevel()->toInt() > maxEvent->getLevel()->toInt()) { maxEvent = event; } count++; } LoggingEventPtr AsyncAppender::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 LoggingEventPtr( new LoggingEvent( maxEvent->getLoggerName(), maxEvent->getLevel(), msg, LocationInfo::getLocationUnavailable()) ); } ::log4cxx::spi::LoggingEventPtr AsyncAppender::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 LoggingEventPtr( new LoggingEvent( LOG4CXX_STR(""), log4cxx::Level::getError(), msg, LocationInfo::getLocationUnavailable()) ); } void AsyncAppender::dispatch() { bool isActive = true; try { while (isActive) { // // process events after lock on buffer is released. // Pool p; LoggingEventList events; { std::unique_lock lock(bufferMutex); size_t bufferSize = buffer.size(); isActive = !closed; while ((bufferSize == 0) && isActive) { bufferNotEmpty.wait(lock); bufferSize = buffer.size(); isActive = !closed; } for (LoggingEventList::iterator eventIter = buffer.begin(); eventIter != buffer.end(); eventIter++) { events.push_back(*eventIter); } for (DiscardMap::iterator discardIter = discardMap->begin(); discardIter != discardMap->end(); discardIter++) { events.push_back(discardIter->second.createEvent(p)); } buffer.clear(); discardMap->clear(); bufferNotFull.notify_all(); } for (LoggingEventList::iterator iter = events.begin(); iter != events.end(); iter++) { appenders->appendLoopOnAppenders(*iter, p); } } } catch (InterruptedException&) { //Thread::currentThreadInterrupt(); } catch (...) { } } apache-log4cxx-0.12.1/src/main/cpp/loggermatchfilter.cpp000644 001750 001750 00000004216 14120250670 023741 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; IMPLEMENT_LOG4CXX_OBJECT(LoggerMatchFilter) LoggerMatchFilter::LoggerMatchFilter() : acceptOnMatch(true), loggerToMatch(LOG4CXX_STR("root")) { } void LoggerMatchFilter::setLoggerToMatch(const LogString& value) { loggerToMatch = value; } LogString LoggerMatchFilter::getLoggerToMatch() const { return 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"))) { acceptOnMatch = OptionConverter::toBoolean(value, acceptOnMatch); } } Filter::FilterDecision LoggerMatchFilter::decide( const spi::LoggingEventPtr& event) const { bool matchOccured = loggerToMatch == event->getLoggerName(); if (matchOccured) { if (acceptOnMatch) { return Filter::ACCEPT; } else { return Filter::DENY; } } else { return Filter::NEUTRAL; } } apache-log4cxx-0.12.1/src/main/cpp/nteventlogappender.cpp000644 001750 001750 00000017310 14120250670 024142 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; using namespace log4cxx::nt; 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() : hEventLog(NULL), pCurrentUserSID(NULL) { } NTEventLogAppender::NTEventLogAppender(const LogString& server, const LogString& log, const LogString& source, const LayoutPtr& layout) : server(server), log(log), source(source), hEventLog(NULL), pCurrentUserSID(NULL) { this->layout = layout; Pool pool; activateOptions(pool); } NTEventLogAppender::~NTEventLogAppender() { finalize(); } void NTEventLogAppender::close() { if (hEventLog != NULL) { ::DeregisterEventSource(hEventLog); hEventLog = NULL; } if (pCurrentUserSID != NULL) { CCtUserSIDHelper::FreeSid((::SID*) pCurrentUserSID); pCurrentUserSID = NULL; } } void NTEventLogAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SERVER"), LOG4CXX_STR("server"))) { server = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOG"), LOG4CXX_STR("log"))) { log = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SOURCE"), LOG4CXX_STR("source"))) { source = value; } else { AppenderSkeleton::setOption(option, value); } } void NTEventLogAppender::activateOptions(Pool&) { if (source.empty()) { LogLog::warn( ((LogString) LOG4CXX_STR("Source option not set for appender [")) + name + LOG4CXX_STR("].")); return; } if (log.empty()) { log = LOG4CXX_STR("Application"); } close(); // current user security identifier CCtUserSIDHelper::GetCurrentUserSID((::SID**) &pCurrentUserSID); addRegistryInfo(); LOG4CXX_ENCODE_WCHAR(wsource, source); LOG4CXX_ENCODE_WCHAR(wserver, server); hEventLog = ::RegisterEventSourceW( wserver.empty() ? NULL : wserver.c_str(), wsource.c_str()); if (hEventLog == NULL) { LogString msg(LOG4CXX_STR("Cannot register NT EventLog -- server: '")); msg.append(server); msg.append(LOG4CXX_STR("' source: '")); msg.append(source); LogLog::error(msg); LogLog::error(getErrorString(LOG4CXX_STR("RegisterEventSource"))); } } void NTEventLogAppender::append(const LoggingEventPtr& event, Pool& p) { if (hEventLog == NULL) { LogLog::warn(LOG4CXX_STR("NT EventLog not opened.")); return; } LogString oss; layout->format(oss, event, p); wchar_t* msgs = Transcoder::wencode(oss, p); BOOL bSuccess = ::ReportEventW( hEventLog, getEventType(event), getEventCategory(event), 0x1000, 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(log); subkey.append(1, (logchar) 0x5C /* '\\' */); subkey.append(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, wcslen(modpath) * sizeof(wchar_t)); RegSetValueExW(hkey, L"CategoryMessageFile", 0, REG_SZ, (LPBYTE) modpath, 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; } #endif // WIN32 apache-log4cxx-0.12.1/src/main/cpp/hierarchy.cpp000644 001750 001750 00000022757 14121416577 022242 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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; IMPLEMENT_LOG4CXX_OBJECT(Hierarchy) Hierarchy::Hierarchy() : pool(), loggers(new LoggerMap()), provisionNodes(new ProvisionNodeMap()) { std::unique_lock lock(mutex); root = LoggerPtr(new RootLogger(pool, Level::getDebug())); defaultFactory = LoggerFactoryPtr(new DefaultLoggerFactory()); emittedNoAppenderWarning = false; configured = false; thresholdInt = Level::ALL_INT; threshold = Level::getAll(); emittedNoResourceBundleWarning = false; } Hierarchy::~Hierarchy() { // TODO LOGCXX-430 // https://issues.apache.org/jira/browse/LOGCXX-430?focusedCommentId=15175254&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-15175254 #ifndef APR_HAS_THREADS delete loggers; delete provisionNodes; #endif } void Hierarchy::addHierarchyEventListener(const spi::HierarchyEventListenerPtr& listener) { std::unique_lock lock(mutex); if (std::find(listeners.begin(), listeners.end(), listener) != listeners.end()) { LogLog::warn(LOG4CXX_STR("Ignoring attempt to add an existent listener.")); } else { listeners.push_back(listener); } } void Hierarchy::clear() { std::unique_lock lock(mutex); loggers->clear(); } void Hierarchy::emitNoAppenderWarning(const Logger* logger) { bool emitWarning = false; { std::unique_lock lock(mutex); emitWarning = !emittedNoAppenderWarning; 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(mutex); LoggerPtr logger; LoggerMap::iterator it = loggers->find(name); if (it != loggers->end()) { logger = it->second; } return logger; } void Hierarchy::setThreshold(const LevelPtr& l) { if (l != 0) { std::unique_lock lock(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) { thresholdInt = l->toInt(); threshold = l; if (thresholdInt != Level::ALL_INT) { configured = true; } } void Hierarchy::fireAddAppenderEvent(const Logger* logger, const Appender* appender) { setConfigured(true); HierarchyEventListenerList clonedList; { std::unique_lock lock(mutex); clonedList = 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(mutex); clonedList = listeners; } HierarchyEventListenerList::iterator it, itEnd = clonedList.end(); HierarchyEventListenerPtr listener; for (it = clonedList.begin(); it != itEnd; it++) { listener = *it; listener->removeAppenderEvent(logger, appender); } } const LevelPtr& Hierarchy::getThreshold() const { return threshold; } LoggerPtr Hierarchy::getLogger(const LogString& name) { return getLogger(name, defaultFactory); } LoggerPtr Hierarchy::getLogger(const LogString& name, const spi::LoggerFactoryPtr& factory) { std::unique_lock lock(mutex); LoggerMap::iterator it = loggers->find(name); if (it != loggers->end()) { return it->second; } else { LoggerPtr logger(factory->makeNewLoggerInstance(pool, name)); logger->setHierarchy(shared_from_this()); loggers->insert(LoggerMap::value_type(name, logger)); ProvisionNodeMap::iterator it2 = provisionNodes->find(name); if (it2 != provisionNodes->end()) { updateChildren(it2->second, logger); provisionNodes->erase(it2); } updateParents(logger); return logger; } } LoggerList Hierarchy::getCurrentLoggers() const { std::unique_lock lock(mutex); LoggerList v; LoggerMap::const_iterator it, itEnd = loggers->end(); for (it = loggers->begin(); it != itEnd; it++) { v.push_back(it->second); } return v; } LoggerPtr Hierarchy::getRootLogger() const { return root; } bool Hierarchy::isDisabled(int level) const { bool currentlyConfigured; { std::unique_lock lock(mutex); currentlyConfigured = configured; } if (!currentlyConfigured) { std::shared_ptr nonconstThis = std::const_pointer_cast(shared_from_this()); DefaultConfigurator::configure( nonconstThis); } return thresholdInt > level; } void Hierarchy::resetConfiguration() { std::unique_lock lock(mutex); getRootLogger()->setLevel(Level::getDebug()); root->setResourceBundle(0); setThresholdInternal(Level::getAll()); shutdownInternal(); LoggerMap::const_iterator it, itEnd = loggers->end(); for (it = loggers->begin(); it != itEnd; it++) { it->second->setLevel(0); it->second->setAdditivity(true); it->second->setResourceBundle(0); } //rendererMap.clear(); } void Hierarchy::shutdown() { std::unique_lock lock(mutex); shutdownInternal(); } void Hierarchy::shutdownInternal() { configured = false; LoggerPtr root1 = getRootLogger(); // begin by closing nested appenders root1->closeNestedAppenders(); LoggerMap::iterator it, itEnd = loggers->end(); for (it = loggers->begin(); it != itEnd; it++) { LoggerPtr logger = it->second; logger->closeNestedAppenders(); } // then, remove all appenders root1->removeAllAppenders(); for (it = loggers->begin(); it != itEnd; it++) { LoggerPtr logger = it->second; logger->removeAllAppenders(); } } void Hierarchy::updateParents(LoggerPtr logger) { 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 = loggers->find(substr); if (it != loggers->end()) { parentFound = true; logger->parent = it->second; break; // no need to update the ancestors of the closest ancestor } else { ProvisionNodeMap::iterator it2 = provisionNodes->find(substr); if (it2 != provisionNodes->end()) { it2->second.push_back(logger); } else { ProvisionNode node(1, logger); provisionNodes->insert( ProvisionNodeMap::value_type(substr, node)); } } } // If we could not find any existing parents, then link with root. if (!parentFound) { logger->parent = root; } } void Hierarchy::updateChildren(ProvisionNode& pn, 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 cat.parent point to l.parent and l.parent to cat. if (!StringHelper::startsWith(l->parent->name, logger->name)) { logger->parent = l->parent; l->parent = logger; } } } void Hierarchy::setConfigured(bool newValue) { std::unique_lock lock(mutex); configured = newValue; } bool Hierarchy::isConfigured() { return configured; } HierarchyPtr Hierarchy::create(){ HierarchyPtr ret( new Hierarchy() ); ret->configureRoot(); return ret; } void Hierarchy::configureRoot(){ // This should really be done in the constructor, but in order to fix // LOGCXX-322 we need to turn the repositroy into a weak_ptr, and we // can't use weak_from_this() in the constructor. if( !root->getLoggerRepository().lock() ){ root->setHierarchy(shared_from_this()); } } apache-log4cxx-0.12.1/src/main/cpp/threadlocal.cpp000644 001750 001750 00000003303 14120250670 022515 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/main/cpp/stringhelper.cpp000644 001750 001750 00000011040 14120250670 022736 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include #include #include //LOG4CXX-417: need stdlib.h for atoi on some systems. #ifdef APR_HAVE_STDLIB_H #include #endif 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) { std::string as; Transcoder::encode(s, as); return atoi(as.c_str()); } log4cxx_int64_t StringHelper::toInt64(const LogString& s) { std::string as; Transcoder::encode(s, as); return apr_atoi64(as.c_str()); } void StringHelper::toString(int n, Pool& pool, LogString& s) { char* fmt = pool.itoa(n); Transcoder::decode(fmt, s); } void StringHelper::toString(bool val, LogString& dst) { if (val) { dst.append(LOG4CXX_STR("true")); } else { dst.append(LOG4CXX_STR("false")); } } void StringHelper::toString(log4cxx_int64_t n, Pool& pool, LogString& dst) { if (n >= INT_MIN && n <= INT_MAX) { toString((int) n, pool, dst); } else { const log4cxx_int64_t BILLION = APR_INT64_C(1000000000); int billions = (int) (n / BILLION); char* upper = pool.itoa(billions); int remain = (int) (n - billions * BILLION); if (remain < 0) { remain *= -1; } char* lower = pool.itoa(remain); Transcoder::decode(upper, dst); dst.append(9 - strlen(lower), 0x30 /* '0' */); Transcoder::decode(lower, dst); } } void StringHelper::toString(size_t n, Pool& pool, LogString& s) { toString((log4cxx_int64_t) n, pool, s); } 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-0.12.1/src/main/cpp/gzcompressaction.cpp000644 001750 001750 00000006154 14120250670 023634 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(GZCompressAction) GZCompressAction::GZCompressAction(const File& src, const File& dest, bool del) : source(src), destination(dest), deleteSource(del) { } bool GZCompressAction::execute(log4cxx::helpers::Pool& p) const { if (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 = 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); } } const char** args = (const char**) apr_palloc(aprpool, 4 * sizeof(*args)); int i = 0; args[i++] = "gzip"; args[i++] = "-c"; args[i++] = Transcoder::encode(source.getPath(), p); args[i++] = NULL; apr_proc_t pid; stat = apr_proc_create(&pid, "gzip", args, NULL, attr, aprpool); if (stat != APR_SUCCESS) { throw IOException(stat); } apr_proc_wait(&pid, NULL, NULL, APR_WAIT); stat = apr_file_close(child_out); if (stat != APR_SUCCESS) { throw IOException(stat); } if (deleteSource) { source.deleteFile(p); } return true; } return false; } apache-log4cxx-0.12.1/src/main/cpp/bufferedwriter.cpp000644 001750 001750 00000003201 14120250670 023247 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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(BufferedWriter) BufferedWriter::BufferedWriter(WriterPtr& out1) : out(out1), sz(1024) { } BufferedWriter::BufferedWriter(WriterPtr& out1, size_t sz1) : out(out1), sz(sz1) { } BufferedWriter::~BufferedWriter() { } void BufferedWriter::close(Pool& p) { flush(p); out->close(p); } void BufferedWriter::flush(Pool& p) { if (buf.length() > 0) { out->write(buf, p); buf.erase(buf.begin(), buf.end()); } } void BufferedWriter::write(const LogString& str, Pool& p) { if (buf.length() + str.length() > sz) { out->write(buf, p); buf.erase(buf.begin(), buf.end()); } if (str.length() > sz) { out->write(str, p); } else { buf.append(str); } } apache-log4cxx-0.12.1/src/main/cpp/ndc.cpp000644 001750 001750 00000014726 14120250670 021012 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(stack.top().message, 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(stack.top().message, 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-0.12.1/src/main/cpp/charsetencoder.cpp000644 001750 001750 00000034336 14120250670 023236 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 CharsetEncoderPtr( new UTF8CharsetEncoder() ); } CharsetEncoderPtr CharsetEncoder::getEncoder(const LogString& charset) { if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-8"), LOG4CXX_STR("utf-8"))) { return CharsetEncoderPtr( new UTF8CharsetEncoder() ); } 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 CharsetEncoderPtr( new USASCIICharsetEncoder() ); } 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 CharsetEncoderPtr( new ISOLatinCharsetEncoder() ); } 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 CharsetEncoderPtr( new UTF16BECharsetEncoder() ); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-16LE"), LOG4CXX_STR("utf-16le"))) { return CharsetEncoderPtr( new UTF16LECharsetEncoder() ); } #if APR_HAS_XLATE return CharsetEncoderPtr( new APRCharsetEncoder(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-0.12.1/src/main/cpp/telnetappender.cpp000644 001750 001750 00000014213 14122472113 023247 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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::net; IMPLEMENT_LOG4CXX_OBJECT(TelnetAppender) /** 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() : port(DEFAULT_PORT), connections(MAX_CONNECTIONS), encoding(LOG4CXX_STR("UTF-8")), encoder(CharsetEncoder::getUTF8Encoder()), serverSocket(NULL), sh() { activeConnections = 0; } TelnetAppender::~TelnetAppender() { finalize(); delete serverSocket; } void TelnetAppender::activateOptions(Pool& /* p */) { if (serverSocket == NULL) { serverSocket = new ServerSocket(port); serverSocket->setSoTimeout(1000); } sh = std::thread( &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 { log4cxx::shared_lock lock(mutex); return encoding; } void TelnetAppender::setEncoding(const LogString& value) { std::unique_lock lock(mutex); encoder = CharsetEncoder::getEncoder(value); encoding = value; } void TelnetAppender::close() { std::unique_lock lock(mutex); if (closed) { return; } closed = true; SocketPtr nullSocket; for (ConnectionList::iterator iter = connections.begin(); iter != connections.end(); iter++) { if (*iter != 0) { (*iter)->close(); *iter = nullSocket; } } if (serverSocket != NULL) { try { serverSocket->close(); } catch (Exception&) { } } if ( sh.joinable() ) { sh.join(); } activeConnections = 0; } void TelnetAppender::write(ByteBuffer& buf) { for (ConnectionList::iterator iter = connections.begin(); iter != 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; 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()) { encoder->encode(msg, msgIter, buf); buf.flip(); socket->write(buf); buf.clear(); } } void TelnetAppender::append(const spi::LoggingEventPtr& event, Pool& p) { size_t count = activeConnections; if (count > 0) { LogString msg; this->layout->format(msg, event, 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); log4cxx::shared_lock lock(mutex); while (msgIter != msg.end()) { log4cxx_status_t stat = 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 = 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 = serverSocket->accept(); bool done = closed; if (done) { Pool p; writeStatus(newClient, LOG4CXX_STR("Log closed.\r\n"), p); newClient->close(); break; } size_t count = activeConnections; if (count >= connections.size()) { Pool p; writeStatus(newClient, LOG4CXX_STR("Too many connections.\r\n"), p); newClient->close(); } else { // // find unoccupied connection // std::unique_lock lock(mutex); for (ConnectionList::iterator iter = connections.begin(); iter != connections.end(); iter++) { if (*iter == NULL) { *iter = newClient; 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 (closed) { break; } } catch (Exception& e) { if (!closed) { LogLog::error(LOG4CXX_STR("Encountered error while in SocketHandler loop."), e); } else { break; } } } } apache-log4cxx-0.12.1/src/main/cpp/messagepatternconverter.cpp000644 001750 001750 00000003273 14120250670 025213 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(MessagePatternConverter) MessagePatternConverter::MessagePatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Message"), LOG4CXX_STR("message")) { } PatternConverterPtr MessagePatternConverter::newInstance( const std::vector& /* options */) { static PatternConverterPtr def(new MessagePatternConverter()); return def; } void MessagePatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(event->getRenderedMessage()); } apache-log4cxx-0.12.1/src/main/cpp/onlyonceerrorhandler.cpp000644 001750 001750 00000004027 14120250670 024475 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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) OnlyOnceErrorHandler::OnlyOnceErrorHandler() : WARN_PREFIX(LOG4CXX_STR("log4cxx warning: ")), ERROR_PREFIX(LOG4CXX_STR("log4cxx error: ")), firstTime(true) { } 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 (firstTime) { LogLog::error(message, e); 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 (firstTime) { LogLog::error(message); firstTime = false; } } void OnlyOnceErrorHandler::setAppender(const AppenderPtr&) { } void OnlyOnceErrorHandler::setBackupAppender(const AppenderPtr&) { } apache-log4cxx-0.12.1/src/main/cpp/threadpatternconverter.cpp000644 001750 001750 00000003253 14120250670 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. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new ThreadPatternConverter()); return def; } void ThreadPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(event->getThreadName()); } apache-log4cxx-0.12.1/src/main/cpp/fileappender.cpp000644 001750 001750 00000020576 14120250670 022704 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; IMPLEMENT_LOG4CXX_OBJECT(FileAppender) FileAppender::FileAppender() { std::unique_lock lock(mutex); fileAppend = true; bufferedIO = false; bufferSize = 8 * 1024; } FileAppender::FileAppender(const LayoutPtr& layout1, const LogString& fileName1, bool append1, bool bufferedIO1, int bufferSize1) : WriterAppender(layout1) { { std::unique_lock lock(mutex); fileAppend = append1; fileName = fileName1; bufferedIO = bufferedIO1; bufferSize = bufferSize1; } Pool p; activateOptions(p); } FileAppender::FileAppender(const LayoutPtr& layout1, const LogString& fileName1, bool append1) : WriterAppender(layout1) { { std::unique_lock lock(mutex); fileAppend = append1; fileName = fileName1; bufferedIO = false; bufferSize = 8 * 1024; } Pool p; activateOptions(p); } FileAppender::FileAppender(const LayoutPtr& layout1, const LogString& fileName1) : WriterAppender(layout1) { { std::unique_lock lock(mutex); fileAppend = true; fileName = fileName1; bufferedIO = false; bufferSize = 8 * 1024; } Pool p; activateOptions(p); } FileAppender::~FileAppender() { finalize(); } void FileAppender::setAppend(bool fileAppend1) { std::unique_lock lock(mutex); this->fileAppend = fileAppend1; } void FileAppender::setFile(const LogString& file) { std::unique_lock lock(mutex); setFileInternal(file); } void FileAppender::setFileInternal(const LogString& file) { fileName = file; } void FileAppender::setBufferedIO(bool bufferedIO1) { std::unique_lock lock(mutex); this->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::unique_lock lock(mutex); fileName = stripDuplicateBackslashes(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("APPEND"), LOG4CXX_STR("append"))) { std::unique_lock lock(mutex); fileAppend = OptionConverter::toBoolean(value, true); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFEREDIO"), LOG4CXX_STR("bufferedio"))) { std::unique_lock lock(mutex); bufferedIO = OptionConverter::toBoolean(value, true); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("IMMEDIATEFLUSH"), LOG4CXX_STR("immediateflush"))) { std::unique_lock lock(mutex); bufferedIO = !OptionConverter::toBoolean(value, false); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize"))) { std::unique_lock lock(mutex); bufferSize = OptionConverter::toFileSize(value, 8 * 1024); } else { WriterAppender::setOption(option, value); } } void FileAppender::activateOptions(Pool& p) { std::unique_lock lock(mutex); activateOptionsInternal(p); } void FileAppender::activateOptionsInternal(Pool& p) { int errors = 0; if (!fileName.empty()) { try { setFileInternal(fileName, fileAppend, bufferedIO, bufferSize, p); } catch (IOException& e) { errors++; LogString msg(LOG4CXX_STR("setFile(")); msg.append(fileName); msg.append(1, (logchar) 0x2C /* ',' */); StringHelper::toString(fileAppend, msg); msg.append(LOG4CXX_STR(") call failed.")); errorHandler->error(msg, e, ErrorCode::FILE_OPEN_FAILURE); } } else { errors++; LogLog::error(LogString(LOG4CXX_STR("File option not set for appender [")) + 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 = WriterPtr(new BufferedWriter(newWriter, bufferSize1)); } setWriterInternal(newWriter); this->fileAppend = append1; this->bufferedIO = bufferedIO1; this->fileName = filename; this->bufferSize = (int)bufferSize1; writeHeader(p); } apache-log4cxx-0.12.1/src/main/cpp/cacheddateformat.cpp000644 001750 001750 00000024205 14120250670 023515 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::pattern; /** * 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 }; #undef min /** * 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) : formatter(dateFormat), millisecondStart(0), slotBegin(std::numeric_limits::min()), cache(50, 0x20), expiration(expiration1), previousTime(std::numeric_limits::min()) { if (dateFormat == NULL) { throw IllegalArgumentException(LOG4CXX_STR("dateFormat cannot be null")); } if (expiration1 < 0) { throw IllegalArgumentException(LOG4CXX_STR("expiration must be non-negative")); } } /** * 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 == previousTime) { buf.append(cache); return; } // // If millisecond pattern was not unrecognized // (that is if it was found or milliseconds did not appear) // if (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 < slotBegin + expiration && now >= slotBegin && now < slotBegin + 1000000L) { // // if there was a millisecond field then update it // if (millisecondStart >= 0) { millisecondFormat((int) ((now - slotBegin) / 1000), cache, millisecondStart); } // // update the previously requested time // (the slot begin should be unchanged) previousTime = now; buf.append(cache); return; } } // // could not use previous value. // Call underlying formatter to format date. cache.erase(cache.begin(), cache.end()); formatter->format(cache, now, p); buf.append(cache); previousTime = now; slotBegin = (previousTime / 1000000) * 1000000; if (slotBegin > previousTime) { slotBegin -= 1000000; } // // if the milliseconds field was previous found // then reevaluate in case it moved. // if (millisecondStart >= 0) { millisecondStart = findMillisecondStart(now, cache, 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) { formatter->setTimeZone(timeZone); previousTime = std::numeric_limits::min(); slotBegin = std::numeric_limits::min(); } void CachedDateFormat::numberFormat(LogString& s, int n, Pool& p) const { 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-0.12.1/src/main/cpp/filter.cpp000644 001750 001750 00000002300 14120250670 021514 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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::spi; using namespace log4cxx::helpers; Filter::Filter() : next() { } FilterPtr Filter::getNext() const { return next; } void Filter::setNext(const FilterPtr& newNext) { next = newNext; } void Filter::activateOptions(Pool&) { } void Filter::setOption(const LogString&, const LogString&) { } apache-log4cxx-0.12.1/src/main/cpp/datagramsocket.cpp000644 001750 001750 00000011442 14120250670 023227 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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" #include "apr_lib.h" using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(DatagramSocket) DatagramSocket::DatagramSocket() : socket(0), address(), localAddress(), port(0), localPort(0) { create(); } DatagramSocket::DatagramSocket(int localPort1) : socket(0), address(), localAddress(), port(0), localPort(0) { InetAddressPtr bindAddr = InetAddress::anyAddress(); create(); bind(localPort1, bindAddr); } DatagramSocket::DatagramSocket(int localPort1, InetAddressPtr localAddress1) : socket(0), address(), localAddress(), port(0), localPort(0) { create(); bind(localPort1, localAddress1); } DatagramSocket::~DatagramSocket() { try { close(); } catch (SocketException&) { } } /** Binds a datagram socket to a local port and address.*/ void DatagramSocket::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(socket, server_addr); if (status != APR_SUCCESS) { throw BindException(status); } this->localPort = localPort1; this->localAddress = localAddress1; } /** Close the socket.*/ void DatagramSocket::close() { if (socket != 0) { apr_status_t status = apr_socket_close(socket); if (status != APR_SUCCESS) { throw SocketException(status); } socket = 0; localPort = 0; } } void DatagramSocket::connect(InetAddressPtr address1, int port1) { this->address = address1; this->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, port, 0, addrPool.getAPRPool()); if (status != APR_SUCCESS) { throw ConnectException(status); } // connect the socket status = apr_socket_connect(socket, client_addr); if (status != APR_SUCCESS) { throw ConnectException(status); } } /** Creates a datagram socket.*/ void DatagramSocket::create() { apr_socket_t* newSocket; apr_status_t status = apr_socket_create(&newSocket, APR_INET, SOCK_DGRAM, APR_PROTO_UDP, socketPool.getAPRPool()); socket = newSocket; if (status != APR_SUCCESS) { throw SocketException(status); } } /** Receive the datagram packet.*/ void DatagramSocket::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, socket, 0, (char*)p->getData(), &len); if (status != APR_SUCCESS) { throw IOException(status); } } /** Sends a datagram packet.*/ void DatagramSocket::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(socket, addr, 0, (char*)p->getData(), &len); if (status != APR_SUCCESS) { throw IOException(status); } } apache-log4cxx-0.12.1/src/main/cpp/datagrampacket.cpp000644 001750 001750 00000004134 14120250670 023206 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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(DatagramPacket) /** Constructs a DatagramPacket for receiving packets of length length. */ DatagramPacket::DatagramPacket(void* buf1, int length1) : buf(buf1), offset(0), length(length1), address(), port(0) { } /** 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) : buf(buf1), offset(0), length(length1), address(address1), port(port1) { } /** Constructs a DatagramPacket for receiving packets of length length, specifying an offset into the buffer. */ DatagramPacket::DatagramPacket(void* buf1, int offset1, int length1) : buf(buf1), offset(offset1), length(length1), address(), port(0) { } /** 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) : buf(buf1), offset(offset1), length(length1), address(address1), port(port1) { } DatagramPacket::~DatagramPacket() { } apache-log4cxx-0.12.1/src/main/cpp/levelpatternconverter.cpp000644 001750 001750 00000004710 14120250670 024673 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new LevelPatternConverter()); 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-0.12.1/src/main/cpp/messagebuffer.cpp000644 001750 001750 00000036762 14120250670 023070 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; static bool gMessageBufferUseStaticStream = false; namespace log4cxx { namespace helpers { void MessageBufferUseStaticStream() { gMessageBufferUseStaticStream = true; } } } template void ResetStream(std::basic_ostringstream& stream) { stream.seekp(0); stream.str(std::basic_string()); stream.clear(); } CharMessageBuffer::CharMessageBuffer() : stream(0) { #if defined(STATIC_STRINGSTREAM) if (gMessageBufferUseStaticStream) { thread_local static char ossBuf[8192]; thread_local static std::basic_ostringstream sStream; thread_local static bool inited = false; if (!inited) { inited = true; sStream.rdbuf()->pubsetbuf(ossBuf, 8192); ResetStream(sStream); } stream = &sStream; } #endif } CharMessageBuffer::~CharMessageBuffer() { if (!gMessageBufferUseStaticStream) { delete stream; } } CharMessageBuffer& CharMessageBuffer::operator<<(const std::basic_string& msg) { if (stream == 0) { buf.append(msg); } else { *stream << msg; } return *this; } CharMessageBuffer& CharMessageBuffer::operator<<(const char* msg) { const char* actualMsg = msg; if (actualMsg == 0) { actualMsg = "null"; } if (stream == 0) { buf.append(actualMsg); } else { *stream << actualMsg; } return *this; } CharMessageBuffer& CharMessageBuffer::operator<<(char* msg) { return operator<<((const char*) msg); } CharMessageBuffer& CharMessageBuffer::operator<<(const char msg) { if (stream == 0) { buf.append(1, msg); } else { buf.assign(1, msg); *stream << buf; } return *this; } CharMessageBuffer::operator std::basic_ostream& () { if (stream == 0) { stream = new std::basic_ostringstream(); if (!buf.empty()) { *stream << buf; } } return *stream; } const std::basic_string& CharMessageBuffer::str(std::basic_ostream&) { buf = stream->str(); ResetStream(*stream); return buf; } const std::basic_string& CharMessageBuffer::str(CharMessageBuffer&) { return buf; } bool CharMessageBuffer::hasStream() const { return (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 WideMessageBuffer::WideMessageBuffer() : stream(0) { #if defined(STATIC_STRINGSTREAM) if (gMessageBufferUseStaticStream) { thread_local static wchar_t ossBuf[8192]; thread_local static std::basic_ostringstream sStream; thread_local static bool inited = false; if (!inited) { inited = true; sStream.rdbuf()->pubsetbuf(ossBuf, 8192); ResetStream(sStream); } stream = &sStream; } #endif } WideMessageBuffer::~WideMessageBuffer() { if (!gMessageBufferUseStaticStream) { delete stream; } } WideMessageBuffer& WideMessageBuffer::operator<<(const std::basic_string& msg) { if (stream == 0) { buf.append(msg); } else { *stream << msg; } return *this; } WideMessageBuffer& WideMessageBuffer::operator<<(const wchar_t* msg) { const wchar_t* actualMsg = msg; if (actualMsg == 0) { actualMsg = L"null"; } if (stream == 0) { buf.append(actualMsg); } else { *stream << actualMsg; } return *this; } WideMessageBuffer& WideMessageBuffer::operator<<(wchar_t* msg) { return operator<<((const wchar_t*) msg); } WideMessageBuffer& WideMessageBuffer::operator<<(const wchar_t msg) { if (stream == 0) { buf.append(1, msg); } else { buf.assign(1, msg); *stream << buf; } return *this; } WideMessageBuffer::operator std::basic_ostream& () { if (stream == 0) { stream = new std::basic_ostringstream(); if (!buf.empty()) { *stream << buf; } } return *stream; } const std::basic_string& WideMessageBuffer::str(std::basic_ostream&) { buf = stream->str(); ResetStream(*stream); return buf; } const std::basic_string& WideMessageBuffer::str(WideMessageBuffer&) { return buf; } bool WideMessageBuffer::hasStream() const { return (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); } MessageBuffer::MessageBuffer() : wbuf(0) #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API , ubuf(0) #endif { } MessageBuffer::~MessageBuffer() { delete wbuf; #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API delete ubuf; #endif } bool MessageBuffer::hasStream() const { bool retval = cbuf.hasStream() || (wbuf != 0 && wbuf->hasStream()); #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API retval = retval || (ubuf != 0 && 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&) cbuf; } CharMessageBuffer& MessageBuffer::operator<<(const std::string& msg) { return cbuf.operator << (msg); } CharMessageBuffer& MessageBuffer::operator<<(const char* msg) { return cbuf.operator << (msg); } CharMessageBuffer& MessageBuffer::operator<<(char* msg) { return cbuf.operator << ((const char*) msg); } CharMessageBuffer& MessageBuffer::operator<<(const char msg) { return cbuf.operator << (msg); } const std::string& MessageBuffer::str(CharMessageBuffer& buf) { return cbuf.str(buf); } const std::string& MessageBuffer::str(std::ostream& os) { return cbuf.str(os); } WideMessageBuffer& MessageBuffer::operator<<(const std::wstring& msg) { wbuf = new WideMessageBuffer(); return (*wbuf) << msg; } WideMessageBuffer& MessageBuffer::operator<<(const wchar_t* msg) { wbuf = new WideMessageBuffer(); return (*wbuf) << msg; } WideMessageBuffer& MessageBuffer::operator<<(wchar_t* msg) { wbuf = new WideMessageBuffer(); return (*wbuf) << (const wchar_t*) msg; } WideMessageBuffer& MessageBuffer::operator<<(const wchar_t msg) { wbuf = new WideMessageBuffer(); return (*wbuf) << msg; } const std::wstring& MessageBuffer::str(WideMessageBuffer& buf) { return wbuf->str(buf); } const std::wstring& MessageBuffer::str(std::basic_ostream& os) { return wbuf->str(os); } std::ostream& MessageBuffer::operator<<(bool val) { return cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(short val) { return cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(int val) { return cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(unsigned int val) { return cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(long val) { return cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(unsigned long val) { return cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(float val) { return cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(double val) { return cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(long double val) { return cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(void* val) { return cbuf.operator << (val); } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API UniCharMessageBuffer& MessageBuffer::operator<<(const std::basic_string& msg) { ubuf = new UniCharMessageBuffer(); return (*ubuf) << msg; } UniCharMessageBuffer& MessageBuffer::operator<<(const log4cxx::UniChar* msg) { ubuf = new UniCharMessageBuffer(); return (*ubuf) << msg; } UniCharMessageBuffer& MessageBuffer::operator<<(log4cxx::UniChar* msg) { ubuf = new UniCharMessageBuffer(); return (*ubuf) << (const log4cxx::UniChar*) msg; } UniCharMessageBuffer& MessageBuffer::operator<<(const log4cxx::UniChar msg) { ubuf = new UniCharMessageBuffer(); return (*ubuf) << msg; } const std::basic_string& MessageBuffer::str(UniCharMessageBuffer& buf) { return ubuf->str(buf); } const std::basic_string& MessageBuffer::str(std::basic_ostream& os) { return ubuf->str(os); } UniCharMessageBuffer::UniCharMessageBuffer() : stream(0) { #if defined(STATIC_STRINGSTREAM) if (gMessageBufferUseStaticStream) { thread_local static log4cxx::UniChar ossBuf[8192]; thread_local static std::basic_ostringstream sStream; thread_local static bool inited = false; if (!inited) { inited = true; sStream.rdbuf()->pubsetbuf(ossBuf, 8192); ResetStream(sStream); } stream = &sStream; } #endif } UniCharMessageBuffer::~UniCharMessageBuffer() { if (!gMessageBufferUseStaticStream) { delete stream; } } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const std::basic_string& msg) { if (stream == 0) { buf.append(msg); } else { *stream << 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 (stream == 0) { buf.append(actualMsg); } else { *stream << actualMsg; } return *this; } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(log4cxx::UniChar* msg) { return operator<<((const log4cxx::UniChar*) msg); } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const log4cxx::UniChar msg) { if (stream == 0) { buf.append(1, msg); } else { *stream << msg; } return *this; } UniCharMessageBuffer::operator UniCharMessageBuffer::uostream& () { if (stream == 0) { stream = new std::basic_ostringstream(); if (!buf.empty()) { *stream << buf; } } return *stream; } const std::basic_string& UniCharMessageBuffer::str(UniCharMessageBuffer::uostream&) { buf = stream->str(); ResetStream(*stream); return buf; } const std::basic_string& UniCharMessageBuffer::str(UniCharMessageBuffer&) { return buf; } bool UniCharMessageBuffer::hasStream() const { return (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 #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 (stream) { std::basic_string s(&tmp[0], tmp.size()); *stream << s; } else { buf.append(&tmp[0], tmp.size()); } } return *this; } UniCharMessageBuffer& MessageBuffer::operator<<(const CFStringRef& msg) { ubuf = new UniCharMessageBuffer(); return (*ubuf) << msg; } #endif apache-log4cxx-0.12.1/src/main/cpp/level.cpp000644 001750 001750 00000014761 14120250670 021354 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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) volatile bool Level::initialized = false; std::mutex Level::initMutex; LevelPtr Level::allLevel; LevelPtr Level::fatalLevel; LevelPtr Level::errorLevel; LevelPtr Level::warnLevel; LevelPtr Level::infoLevel; LevelPtr Level::debugLevel; LevelPtr Level::traceLevel; LevelPtr Level::offLevel; void Level::initializeLevels() { if ( initialized ) { return; } std::unique_lock lock(initMutex); if ( initialized ) { return; } allLevel = LevelPtr(new Level(Level::ALL_INT, LOG4CXX_STR("ALL"), 7)); fatalLevel = LevelPtr(new Level(Level::FATAL_INT, LOG4CXX_STR("FATAL"), 0)); errorLevel = LevelPtr(new Level(Level::ERROR_INT, LOG4CXX_STR("ERROR"), 3)); warnLevel = LevelPtr(new Level(Level::WARN_INT, LOG4CXX_STR("WARN"), 4)); infoLevel = LevelPtr(new Level(Level::INFO_INT, LOG4CXX_STR("INFO"), 6)); debugLevel = LevelPtr(new Level(Level::DEBUG_INT, LOG4CXX_STR("DEBUG"), 7)); traceLevel = LevelPtr(new Level(Level::TRACE_INT, LOG4CXX_STR("TRACE"), 7)); offLevel = LevelPtr(new Level(Level::OFF_INT, LOG4CXX_STR("OFF"), 0)); initialized = true; } LevelPtr Level::getOff() { initializeLevels(); return offLevel; } LevelPtr Level::getFatal() { initializeLevels(); return fatalLevel; } LevelPtr Level::getError() { initializeLevels(); return errorLevel; } LevelPtr Level::getWarn() { initializeLevels(); return warnLevel; } LevelPtr Level::getInfo() { initializeLevels(); return infoLevel; } LevelPtr Level::getDebug() { initializeLevels(); return debugLevel; } LevelPtr Level::getTrace() { initializeLevels(); return traceLevel; } LevelPtr Level::getAll() { initializeLevels(); 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 (this->level == level1->level); } bool Level::isGreaterOrEqual(const LevelPtr& level1) const { return this->level >= level1->level; } apache-log4cxx-0.12.1/src/main/cpp/appenderskeleton.cpp000644 001750 001750 00000007532 14121416704 023611 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(AppenderSkeleton) AppenderSkeleton::AppenderSkeleton() : layout(), name(), threshold(Level::getAll()), errorHandler(new OnlyOnceErrorHandler()), headFilter(), tailFilter(), pool() { std::unique_lock lock(mutex); closed = false; } AppenderSkeleton::AppenderSkeleton(const LayoutPtr& layout1) : layout(layout1), name(), threshold(Level::getAll()), errorHandler(new OnlyOnceErrorHandler()), headFilter(), tailFilter(), pool() { std::unique_lock lock(mutex); closed = false; } void AppenderSkeleton::finalize() { // An appender might be closed then garbage collected. There is no // point in closing twice. if (closed) { return; } close(); } void AppenderSkeleton::addFilter(const spi::FilterPtr& newFilter) { std::unique_lock lock(mutex); if (headFilter == 0) { headFilter = tailFilter = newFilter; } else { tailFilter->setNext(newFilter); tailFilter = newFilter; } } void AppenderSkeleton::clearFilters() { std::unique_lock lock(mutex); headFilter = tailFilter = 0; } bool AppenderSkeleton::isAsSevereAsThreshold(const LevelPtr& level) const { return ((level == 0) || level->isGreaterOrEqual(threshold)); } void AppenderSkeleton::doAppend(const spi::LoggingEventPtr& event, Pool& pool1) { std::unique_lock lock(mutex); doAppendImpl(event, pool1); } void AppenderSkeleton::doAppendImpl(const spi::LoggingEventPtr& event, Pool& pool1) { if (closed) { LogLog::error(((LogString) LOG4CXX_STR("Attempted to append to closed appender named [")) + name + LOG4CXX_STR("].")); return; } if (!isAsSevereAsThreshold(event->getLevel())) { return; } FilterPtr f = headFilter; while (f != 0) { switch (f->decide(event)) { case Filter::DENY: return; case Filter::ACCEPT: f = 0; break; case Filter::NEUTRAL: f = f->getNext(); } } append(event, pool1); } void AppenderSkeleton::setErrorHandler(const spi::ErrorHandlerPtr errorHandler1) { std::unique_lock lock(mutex); if (errorHandler1 == 0) { // 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 { this->errorHandler = errorHandler1; } } void AppenderSkeleton::setThreshold(const LevelPtr& threshold1) { std::unique_lock lock(mutex); this->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)); } } apache-log4cxx-0.12.1/src/main/cpp/lineseparatorpatternconverter.cpp000644 001750 001750 00000003603 14120250670 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new LineSeparatorPatternConverter()); 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-0.12.1/src/main/cpp/patternlayout.cpp000644 001750 001750 00000013516 14120250670 023155 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #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 #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; using namespace log4cxx::pattern; IMPLEMENT_LOG4CXX_OBJECT(PatternLayout) PatternLayout::PatternLayout() { } /** Constructs a PatternLayout using the supplied conversion pattern. */ PatternLayout::PatternLayout(const LogString& pattern) : conversionPattern(pattern) { Pool pool; activateOptions(pool); } void PatternLayout::setConversionPattern(const LogString& pattern) { conversionPattern = pattern; Pool pool; activateOptions(pool); } void PatternLayout::format(LogString& output, const spi::LoggingEventPtr& event, Pool& pool) const { std::vector::const_iterator formatterIter = patternFields.begin(); for (std::vector::const_iterator converterIter = patternConverters.begin(); converterIter != 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"))) { conversionPattern = OptionConverter::convertSpecialChars(value); } } void PatternLayout::activateOptions(Pool&) { LogString pat(conversionPattern); if (pat.empty()) { pat = LOG4CXX_STR("%m%n"); } patternConverters.erase(patternConverters.begin(), patternConverters.end()); patternFields.erase(patternFields.begin(), patternFields.end()); std::vector converters; PatternParser::parse(pat, converters, 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) { patternConverters.push_back(eventConverter); } } } #define RULES_PUT(spec, cls) \ specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR(spec)), (PatternConstructor) 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); 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("x", NDCPatternConverter); RULES_PUT("ndc", NDCPatternConverter); RULES_PUT("X", PropertiesPatternConverter); RULES_PUT("properties", PropertiesPatternConverter); RULES_PUT("throwable", ThrowableInformationPatternConverter); return specs; } apache-log4cxx-0.12.1/src/main/cpp/smtpappender.cpp000644 001750 001750 00000041273 14120250670 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 #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #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); 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; 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 = strlen(pThis->current); } 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. */ virtual bool isTriggeringEvent(const spi::LoggingEventPtr& event); private: DefaultEvaluator(const DefaultEvaluator&); DefaultEvaluator& operator=(const DefaultEvaluator&); }; // class DefaultEvaluator } } IMPLEMENT_LOG4CXX_OBJECT(DefaultEvaluator) IMPLEMENT_LOG4CXX_OBJECT(SMTPAppender) DefaultEvaluator::DefaultEvaluator() { } bool DefaultEvaluator::isTriggeringEvent(const spi::LoggingEventPtr& event) { return event->getLevel()->isGreaterOrEqual(Level::getError()); } SMTPAppender::SMTPAppender() : smtpPort(25), bufferSize(512), locationInfo(false), cb(bufferSize), evaluator(new DefaultEvaluator()) { } /** Use evaluator passed as parameter as the TriggeringEventEvaluator for this SMTPAppender. */ SMTPAppender::SMTPAppender(spi::TriggeringEventEvaluatorPtr evaluator) : smtpPort(25), bufferSize(512), locationInfo(false), cb(bufferSize), evaluator(evaluator) { } SMTPAppender::~SMTPAppender() { finalize(); } bool SMTPAppender::requiresLayout() const { return true; } LogString SMTPAppender::getFrom() const { return from; } void SMTPAppender::setFrom(const LogString& newVal) { from = newVal; } LogString SMTPAppender::getSubject() const { return subject; } void SMTPAppender::setSubject(const LogString& newVal) { subject = newVal; } LogString SMTPAppender::getSMTPHost() const { return smtpHost; } void SMTPAppender::setSMTPHost(const LogString& newVal) { smtpHost = newVal; } int SMTPAppender::getSMTPPort() const { return smtpPort; } void SMTPAppender::setSMTPPort(int newVal) { smtpPort = newVal; } bool SMTPAppender::getLocationInfo() const { return locationInfo; } void SMTPAppender::setLocationInfo(bool newVal) { locationInfo = newVal; } LogString SMTPAppender::getSMTPUsername() const { return smtpUsername; } void SMTPAppender::setSMTPUsername(const LogString& newVal) { smtpUsername = newVal; } LogString SMTPAppender::getSMTPPassword() const { return smtpPassword; } void SMTPAppender::setSMTPPassword(const LogString& newVal) { 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 (layout == 0) { errorHandler->error(LOG4CXX_STR("No layout set for appender named [") + name + LOG4CXX_STR("].")); activate = false; } if (evaluator == 0) { errorHandler->error(LOG4CXX_STR("No TriggeringEventEvaluator is set for appender [") + name + LOG4CXX_STR("].")); activate = false; } if (smtpHost.empty()) { errorHandler->error(LOG4CXX_STR("No smtpHost is set for appender [") + name + LOG4CXX_STR("].")); activate = false; } if (to.empty() && cc.empty() && bcc.empty()) { errorHandler->error(LOG4CXX_STR("No recipient address is set for appender [") + name + LOG4CXX_STR("].")); activate = false; } activate &= asciiCheck(to, LOG4CXX_STR("to")); activate &= asciiCheck(cc, LOG4CXX_STR("cc")); activate &= asciiCheck(bcc, LOG4CXX_STR("bcc")); activate &= asciiCheck(from, LOG4CXX_STR("from")); #if !LOG4CXX_HAVE_LIBESMTP 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(); cb.add(event); if (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 ((to.empty() && cc.empty() && bcc.empty()) || from.empty() || smtpHost.empty()) { errorHandler->error(LOG4CXX_STR("Message not configured.")); return false; } if (evaluator == 0) { errorHandler->error(LOG4CXX_STR("No TriggeringEventEvaluator is set for appender [") + name + LOG4CXX_STR("].")); return false; } if (layout == 0) { errorHandler->error(LOG4CXX_STR("No layout set for appender named [") + name + LOG4CXX_STR("].")); return false; } return true; #else return false; #endif } void SMTPAppender::close() { this->closed = true; } LogString SMTPAppender::getTo() const { return to; } void SMTPAppender::setTo(const LogString& addressStr) { to = addressStr; } LogString SMTPAppender::getCc() const { return cc; } void SMTPAppender::setCc(const LogString& addressStr) { cc = addressStr; } LogString SMTPAppender::getBcc() const { return bcc; } void SMTPAppender::setBcc(const LogString& addressStr) { 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; layout->appendHeader(sbuf, p); int len = cb.length(); for (int i = 0; i < len; i++) { LoggingEventPtr event = cb.get(); layout->format(sbuf, event, p); } layout->appendFooter(sbuf, p); SMTPSession session(smtpHost, smtpPort, smtpUsername, smtpPassword, p); SMTPMessage message(session, from, to, cc, bcc, 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 evaluator == 0 ? LogString() : evaluator->getClass().getName(); } log4cxx::spi::TriggeringEventEvaluatorPtr SMTPAppender::getEvaluator() const { return evaluator; } void SMTPAppender::setEvaluator(log4cxx::spi::TriggeringEventEvaluatorPtr& trigger) { 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) { this->bufferSize = sz; 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()); evaluator = log4cxx::cast(obj); } apache-log4cxx-0.12.1/src/main/cpp/systemoutwriter.cpp000644 001750 001750 00000003553 14120250670 023553 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/main/cpp/ndcpatternconverter.cpp000644 001750 001750 00000003267 14120250670 024336 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new NDCPatternConverter()); return def; } void NDCPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { if (!event->getNDC(toAppendTo)) { toAppendTo.append(LOG4CXX_STR("null")); } } apache-log4cxx-0.12.1/src/main/cpp/objectoutputstream.cpp000644 001750 001750 00000014172 14120250670 024204 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ObjectOutputStream) ObjectOutputStream::ObjectOutputStream(OutputStreamPtr outputStream, Pool& p) : os(outputStream), utf8Encoder(CharsetEncoder::getUTF8Encoder()), objectHandleDefault(0x7E0000), objectHandle(objectHandleDefault), classDescriptions(new ClassDescriptionMap()) { unsigned char start[] = { 0xAC, 0xED, 0x00, 0x05 }; ByteBuffer buf((char*) start, sizeof(start)); os->write(buf, p); } ObjectOutputStream::~ObjectOutputStream() { delete classDescriptions; } void ObjectOutputStream::close(Pool& p) { os->close(p); } void ObjectOutputStream::flush(Pool& p) { os->flush(p); } void ObjectOutputStream::reset(Pool& p) { os->flush(p); writeByte(TC_RESET, p); os->flush(p); objectHandle = objectHandleDefault; classDescriptions->clear(); } void ObjectOutputStream::writeObject(const LogString& val, Pool& p) { objectHandle++; writeByte(TC_STRING, p); char bytes[2]; #if LOG4CXX_LOGCHAR_IS_UTF8 size_t len = val.size(); ByteBuffer dataBuf(const_cast(val.data()), val.size()); #else size_t maxSize = 6 * val.size(); char* data = p.pstralloc(maxSize); ByteBuffer dataBuf(data, maxSize); LogString::const_iterator iter(val.begin()); utf8Encoder->encode(val, iter, dataBuf); dataBuf.flip(); size_t len = dataBuf.limit(); #endif bytes[1] = (char) (len & 0xFF); bytes[0] = (char) ((len >> 8) & 0xFF); ByteBuffer lenBuf(bytes, sizeof(bytes)); os->write(lenBuf, p); os->write(dataBuf, p); } void ObjectOutputStream::writeObject(const MDC::Map& val, Pool& p) { // // TC_OBJECT and the classDesc for java.util.Hashtable // unsigned char prolog[] = { 0x72, 0x00, 0x13, 0x6A, 0x61, 0x76, 0x61, 0x2E, 0x75, 0x74, 0x69, 0x6C, 0x2E, 0x48, 0x61, 0x73, 0x68, 0x74, 0x61, 0x62, 0x6C, 0x65, 0x13, 0xBB, 0x0F, 0x25, 0x21, 0x4A, 0xE4, 0xB8, 0x03, 0x00, 0x02, 0x46, 0x00, 0x0A, 0x6C, 0x6F, 0x61, 0x64, 0x46, 0x61, 0x63, 0x74, 0x6F, 0x72, 0x49, 0x00, 0x09, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6F, 0x6C, 0x64, 0x78, 0x70 }; writeProlog("java.util.Hashtable", 1, (char*) prolog, sizeof(prolog), p); // loadFactor = 0.75, threshold = 5, blockdata start, buckets.size = 7 char data[] = { 0x3F, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, TC_BLOCKDATA, 0x08, 0x00, 0x00, 0x00, 0x07 }; ByteBuffer dataBuf(data, sizeof(data)); os->write(dataBuf, p); char size[4]; size_t sz = val.size(); size[3] = (char) (sz & 0xFF); size[2] = (char) ((sz >> 8) & 0xFF); size[1] = (char) ((sz >> 16) & 0xFF); size[0] = (char) ((sz >> 24) & 0xFF); ByteBuffer sizeBuf(size, sizeof(size)); os->write(sizeBuf, p); for (MDC::Map::const_iterator iter = val.begin(); iter != val.end(); iter++) { writeObject(iter->first, p); writeObject(iter->second, p); } writeByte(TC_ENDBLOCKDATA, p); } void ObjectOutputStream::writeUTFString(const std::string& val, Pool& p) { char bytes[3]; size_t len = val.size(); ByteBuffer dataBuf(const_cast(val.data()), val.size()); objectHandle++; bytes[0] = 0x74; bytes[1] = (char) ((len >> 8) & 0xFF); bytes[2] = (char) (len & 0xFF); ByteBuffer lenBuf(bytes, sizeof(bytes)); os->write(lenBuf, p); os->write(dataBuf, p); } void ObjectOutputStream::writeByte(char val, Pool& p) { ByteBuffer buf(&val, 1); os->write(buf, p); } void ObjectOutputStream::writeInt(int val, Pool& p) { char bytes[4]; bytes[3] = (char) (val & 0xFF); bytes[2] = (char) ((val >> 8) & 0xFF); bytes[1] = (char) ((val >> 16) & 0xFF); bytes[0] = (char) ((val >> 24) & 0xFF); ByteBuffer buf(bytes, sizeof(bytes)); os->write(buf, p); } void ObjectOutputStream::writeLong(log4cxx_time_t val, Pool& p) { char bytes[8]; bytes[7] = (char) (val & 0xFF); bytes[6] = (char) ((val >> 8) & 0xFF); bytes[5] = (char) ((val >> 16) & 0xFF); bytes[4] = (char) ((val >> 24) & 0xFF); bytes[3] = (char) ((val >> 32) & 0xFF); bytes[2] = (char) ((val >> 40) & 0xFF); bytes[1] = (char) ((val >> 48) & 0xFF); bytes[0] = (char) ((val >> 56) & 0xFF); ByteBuffer buf(bytes, sizeof(bytes)); os->write(buf, p); } void ObjectOutputStream::writeBytes(const char* bytes, size_t len, Pool& p) { ByteBuffer buf(const_cast(bytes), len); os->write(buf, p); } void ObjectOutputStream::writeNull(Pool& p) { writeByte(TC_NULL, p); } void ObjectOutputStream::writeProlog(const char* className, int classDescIncrement, char* classDesc, size_t len, Pool& p) { ClassDescriptionMap::const_iterator match = classDescriptions->find(className); if (match != classDescriptions->end()) { char bytes[6]; bytes[0] = TC_OBJECT; bytes[1] = TC_REFERENCE; bytes[2] = (char) ((match->second >> 24) & 0xFF); bytes[3] = (char) ((match->second >> 16) & 0xFF); bytes[4] = (char) ((match->second >> 8) & 0xFF); bytes[5] = (char) (match->second & 0xFF); ByteBuffer buf(bytes, sizeof(bytes)); os->write(buf, p); objectHandle++; } else { classDescriptions->insert(ClassDescriptionMap::value_type(className, objectHandle)); writeByte(TC_OBJECT, p); ByteBuffer buf(classDesc, len); os->write(buf, p); objectHandle += (classDescIncrement + 1); } } apache-log4cxx-0.12.1/src/main/cpp/asyncappender_nonblocking.cpp000644 001750 001750 00000022504 14120250670 025456 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(AsyncAppender) AsyncAppender::AsyncAppender() : AppenderSkeleton(), buffer(DEFAULT_BUFFER_SIZE), SHARED_MUTEX_INIT(bufferMutex, pool), bufferNotFull(pool), bufferNotEmpty(pool), discardMap(new DiscardMap()), bufferSize(DEFAULT_BUFFER_SIZE), appenders(new AppenderAttachableImpl(pool)), dispatcher(), locationInfo(false), blocking(true) { #if APR_HAS_THREADS dispatcher.run(dispatch, this); #endif } AsyncAppender::~AsyncAppender() { finalize(); delete discardMap; } void AsyncAppender::addRef() const { ObjectImpl::addRef(); } void AsyncAppender::releaseRef() const { ObjectImpl::releaseRef(); } void AsyncAppender::addAppender(const AppenderPtr& newAppender) { synchronized sync(appenders->getMutex()); 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) { LOCK_R sync(mutex); doAppendImpl(event, pool1); } void AsyncAppender::append(const spi::LoggingEventPtr& event, Pool& p) { #if APR_HAS_THREADS // // if dispatcher has died then // append subsequent events synchronously // if (!dispatcher.isAlive() || bufferSize <= 0) { synchronized sync(appenders->getMutex()); appenders->appendLoopOnAppenders(event, p); return; } // Set the NDC and thread name for the calling thread as these // LoggingEvent fields were not set at event creation time. LogString ndcVal; event->getNDC(ndcVal); event->getThreadName(); // Get a copy of this thread's MDC. event->getMDCCopy(); { LOCK_R sync(bufferMutex); while (true) { event->addRef(); if (buffer.bounded_push(event)) { bufferNotEmpty.signalAll(); break; } else { event->releaseRef(); } // // 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 (blocking && !Thread::interrupted() && !dispatcher.isCurrentThread()) { try { bufferNotFull.await(); discard = false; } catch (InterruptedException& e) { // // reset interrupt status so // calling code can see interrupt on // their next wait or sleep. Thread::currentThreadInterrupt(); } } // // if blocking is false or thread has been interrupted // add event to discard map. // if (discard) { discardedCount++; break; } } } #else synchronized sync(appenders->getMutex()); appenders->appendLoopOnAppenders(event, p); #endif } void AsyncAppender::close() { { LOCK_W sync(bufferMutex); closed = true; } bufferNotEmpty.signalAll(); bufferNotFull.signalAll(); #if APR_HAS_THREADS try { dispatcher.join(); } catch (InterruptedException& e) { Thread::currentThreadInterrupt(); LogLog::error(LOG4CXX_STR("Got an InterruptedException while waiting for the dispatcher to finish,"), e); } #endif { synchronized sync(appenders->getMutex()); AppenderList appenderList = appenders->getAllAppenders(); for (AppenderList::iterator iter = appenderList.begin(); iter != appenderList.end(); iter++) { (*iter)->close(); } } } AppenderList AsyncAppender::getAllAppenders() const { synchronized sync(appenders->getMutex()); return appenders->getAllAppenders(); } AppenderPtr AsyncAppender::getAppender(const LogString& n) const { synchronized sync(appenders->getMutex()); return appenders->getAppender(n); } bool AsyncAppender::isAttached(const AppenderPtr& appender) const { synchronized sync(appenders->getMutex()); return appenders->isAttached(appender); } bool AsyncAppender::requiresLayout() const { return false; } void AsyncAppender::removeAllAppenders() { synchronized sync(appenders->getMutex()); appenders->removeAllAppenders(); } void AsyncAppender::removeAppender(const AppenderPtr& appender) { synchronized sync(appenders->getMutex()); appenders->removeAppender(appender); } void AsyncAppender::removeAppender(const LogString& n) { synchronized sync(appenders->getMutex()); appenders->removeAppender(n); } bool AsyncAppender::getLocationInfo() const { return locationInfo; } void AsyncAppender::setLocationInfo(bool flag) { locationInfo = flag; } void AsyncAppender::setBufferSize(int size) { if (size < 0) { throw IllegalArgumentException(LOG4CXX_STR("size argument must be non-negative")); } { LOCK_W sync(bufferMutex); bufferSize = (size < 1) ? 1 : size; buffer.reserve_unsafe(bufferSize); } bufferNotFull.signalAll(); } int AsyncAppender::getBufferSize() const { return bufferSize; } void AsyncAppender::setBlocking(bool value) { { LOCK_W sync(bufferMutex); blocking = value; } bufferNotFull.signalAll(); } bool AsyncAppender::getBlocking() const { return blocking; } AsyncAppender::DiscardSummary::DiscardSummary(const LoggingEventPtr& event) : maxEvent(event), count(1) { } AsyncAppender::DiscardSummary::DiscardSummary(const DiscardSummary& src) : maxEvent(src.maxEvent), count(src.count) { } AsyncAppender::DiscardSummary& AsyncAppender::DiscardSummary::operator=(const DiscardSummary& src) { maxEvent = src.maxEvent; count = src.count; return *this; } void AsyncAppender::DiscardSummary::add(const LoggingEventPtr& event) { if (event->getLevel()->toInt() > maxEvent->getLevel()->toInt()) { maxEvent = event; } count++; } LoggingEventPtr AsyncAppender::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 new LoggingEvent( maxEvent->getLoggerName(), maxEvent->getLevel(), msg, LocationInfo::getLocationUnavailable()); } ::log4cxx::spi::LoggingEventPtr AsyncAppender::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 new LoggingEvent( LOG4CXX_STR(""), log4cxx::Level::getError(), msg, LocationInfo::getLocationUnavailable()); } #if APR_HAS_THREADS void* LOG4CXX_THREAD_FUNC AsyncAppender::dispatch(apr_thread_t* /*thread*/, void* data) { AsyncAppender* pThis = (AsyncAppender*) data; try { while (!pThis->closed || !pThis->buffer.empty()) { pThis->bufferNotEmpty.await(); // // process events after lock on buffer is released. // Pool p; LoggingEventList events; { LOCK_R sync(pThis->bufferMutex); unsigned count = 0; log4cxx::spi::LoggingEvent* logPtr = nullptr; while (pThis->buffer.pop(logPtr)) { log4cxx::spi::LoggingEventPtr ptr(logPtr); events.push_back(ptr); logPtr->releaseRef(); count++; } if (pThis->blocking) { pThis->bufferNotFull.signalAll(); } size_t discarded = pThis->discardedCount.exchange(0); if (discarded != 0) { events.push_back(AsyncAppender::DiscardSummary::createEvent(p, discarded)); } } for (LoggingEventList::iterator iter = events.begin(); iter != events.end(); iter++) { synchronized sync(pThis->appenders->getMutex()); pThis->appenders->appendLoopOnAppenders(*iter, p); } } } catch (InterruptedException& ex) { Thread::currentThreadInterrupt(); } catch (...) { } return 0; } #endif apache-log4cxx-0.12.1/src/main/cpp/pool.cpp000644 001750 001750 00000004152 14120250670 021207 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/main/cpp/optionconverter.cpp000644 001750 001750 00000022403 14120250670 023475 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 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) { 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 = ConfiguratorPtr(new PropertyConfigurator()); } configurator->doConfigure(configFileName, hierarchy); } apache-log4cxx-0.12.1/src/main/cpp/syslogwriter.cpp000644 001750 001750 00000004113 14120250670 023010 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; SyslogWriter::SyslogWriter(const LogString& syslogHost1, int syslogHostPort1) : syslogHost(syslogHost1), syslogHostPort(syslogHostPort1) { try { this->address = InetAddress::getByName(syslogHost1); } catch (UnknownHostException& e) { LogLog::error(((LogString) LOG4CXX_STR("Could not find ")) + syslogHost1 + LOG4CXX_STR(". All logging will FAIL."), e); } try { this->ds = DatagramSocketPtr(new DatagramSocket()); } catch (SocketException& e) { LogLog::error(((LogString) LOG4CXX_STR("Could not instantiate DatagramSocket to ")) + syslogHost1 + LOG4CXX_STR(". All logging will FAIL."), e); } } void SyslogWriter::write(const LogString& source) { if (this->ds != 0 && this->address != 0) { LOG4CXX_ENCODE_CHAR(data, source); DatagramPacketPtr packet( new DatagramPacket((void*) data.data(), data.length(), address, syslogHostPort)); ds->send(packet); } } apache-log4cxx-0.12.1/src/main/cpp/threadspecificdata.cpp000644 001750 001750 00000006522 14120250670 024050 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; ThreadSpecificData::ThreadSpecificData() : ndcStack(), mdcMap() { } ThreadSpecificData::~ThreadSpecificData() { } log4cxx::NDC::Stack& ThreadSpecificData::getStack() { return ndcStack; } log4cxx::MDC::Map& ThreadSpecificData::getMap() { return 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 (ndcStack.empty() && 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-0.12.1/src/main/cpp/inetaddress.cpp000644 001750 001750 00000007460 14120250670 022550 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include #include #include "apr_network_io.h" using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(InetAddress) 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) : ipAddrString(hostAddr), hostNameString(hostName) { } /** 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(InetAddressPtr(new InetAddress(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 ipAddrString; } /** Gets the host name for this IP address. */ LogString InetAddress::getHostName() const { return 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-0.12.1/src/main/cpp/patternconverter.cpp000644 001750 001750 00000003067 14120250670 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. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include using namespace log4cxx; using namespace log4cxx::pattern; IMPLEMENT_LOG4CXX_OBJECT(PatternConverter) PatternConverter::PatternConverter( const LogString& name1, const LogString& style1) : name(name1), style(style1) { } PatternConverter::~PatternConverter() { } LogString PatternConverter::getName() const { return name; } LogString PatternConverter::getStyleClass(const log4cxx::helpers::ObjectPtr& /* e */) const { return style; } void PatternConverter::append(LogString& toAppendTo, const std::string& src) { LOG4CXX_DECODE_CHAR(decoded, src); toAppendTo.append(decoded); } apache-log4cxx-0.12.1/src/main/cpp/manualtriggeringpolicy.cpp000644 001750 001750 00000002752 14120250670 025021 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/main/cpp/patternparser.cpp000644 001750 001750 00000023074 14120250670 023134 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 = FormattingInfoPtr( new FormattingInfo( true, formattingInfo->getMinLength(), formattingInfo->getMaxLength())); break; case 0x2E: // '.' state = DOT_STATE; break; default: if ((c >= 0x30 /* '0' */) && (c <= 0x39 /* '9' */)) { formattingInfo = FormattingInfoPtr( new FormattingInfo( 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 = FormattingInfoPtr( new FormattingInfo( 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 = FormattingInfoPtr( new FormattingInfo( 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 = FormattingInfoPtr( new FormattingInfo( 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-0.12.1/src/main/cpp/fileinputstream.cpp000644 001750 001750 00000005075 14120250670 023456 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; IMPLEMENT_LOG4CXX_OBJECT(FileInputStream) FileInputStream::FileInputStream(const LogString& filename) : fileptr(0) { open(filename); } FileInputStream::FileInputStream(const logchar* filename) : fileptr(0) { 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(&fileptr, flags, perm, pool); if (stat != APR_SUCCESS) { throw IOException(stat); } } FileInputStream::FileInputStream(const File& aFile) { apr_fileperms_t perm = APR_OS_DEFAULT; apr_int32_t flags = APR_READ; apr_status_t stat = aFile.open(&fileptr, flags, perm, pool); if (stat != APR_SUCCESS) { throw IOException(stat); } } FileInputStream::~FileInputStream() { if (fileptr != NULL && !APRInitializer::isDestructed) { apr_file_close(fileptr); } } void FileInputStream::close() { apr_status_t stat = apr_file_close(fileptr); if (stat == APR_SUCCESS) { fileptr = NULL; } else { throw IOException(stat); } } int FileInputStream::read(ByteBuffer& buf) { apr_size_t bytesRead = buf.remaining(); apr_status_t stat = apr_file_read(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-0.12.1/src/main/cpp/action.cpp000644 001750 001750 00000003350 14120250670 021512 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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(Action) Action::Action() : complete(false), interrupted(false), pool() { } Action::~Action() { } /** * {@inheritDoc} */ void Action::run(log4cxx::helpers::Pool& pool1) { std::unique_lock lock(mutex); if (!interrupted) { try { execute(pool1); } catch (std::exception& ex) { reportException(ex); } complete = true; interrupted = true; } } /** * {@inheritDoc} */ void Action::close() { std::unique_lock lock(mutex); interrupted = true; } /** * Tests if the action is complete. * @return true if action is complete. */ bool Action::isComplete() const { return complete; } /** * Capture exception. * * @param ex exception. */ void Action::reportException(const std::exception& /* ex */) { } apache-log4cxx-0.12.1/src/main/cpp/fulllocationpatternconverter.cpp000644 001750 001750 00000003750 14120250670 026262 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new FullLocationPatternConverter()); 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-0.12.1/src/main/cpp/mapfilter.cpp000644 001750 001750 00000004546 14120250670 022230 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; IMPLEMENT_LOG4CXX_OBJECT(MapFilter) MapFilter::MapFilter() : acceptOnMatch(true), mustMatchAll(false) { } void MapFilter::setOption( const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch"))) { acceptOnMatch = OptionConverter::toBoolean(value, acceptOnMatch); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("OPERATOR"), LOG4CXX_STR("operator"))) { mustMatchAll = StringHelper::equalsIgnoreCase(value, LOG4CXX_STR("AND"), LOG4CXX_STR("and")) ? true : false; } else if (!option.empty() && !value.empty()) { keyVals[option] = value; } } Filter::FilterDecision MapFilter::decide( const log4cxx::spi::LoggingEventPtr& event) const { if (keyVals.empty()) { return Filter::NEUTRAL; } bool matched = true; for (KeyVals::const_iterator it = keyVals.begin(); it != keyVals.end(); ++it) { LogString curval; event->getMDC(it->first, curval); if (curval.empty() || curval != it->second) { matched = false; } else { matched = true; } if (mustMatchAll != matched) { break; } } if (acceptOnMatch) { return matched ? Filter::ACCEPT : Filter::NEUTRAL; } else { return matched ? Filter::DENY : Filter::NEUTRAL; } } apache-log4cxx-0.12.1/src/main/cpp/filedatepatternconverter.cpp000644 001750 001750 00000002704 14120250670 025342 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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-0.12.1/src/main/cpp/CMakeLists.txt000644 001750 001750 00000012243 14122472113 022272 0ustar00robertrobert000000 000000 # Options option(LOG4CXX_BLOCKING_ASYNC_APPENDER "Async appender behaviour" ON) 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) target_sources(log4cxx PRIVATE action.cpp andfilter.cpp appenderattachableimpl.cpp appenderskeleton.cpp aprinitializer.cpp $,asyncappender.cpp,asyncappender_nonblocking.cpp> basicconfigurator.cpp bufferedwriter.cpp bytearrayinputstream.cpp bytearrayoutputstream.cpp bytebuffer.cpp cacheddateformat.cpp charsetdecoder.cpp charsetencoder.cpp class.cpp classnamepatternconverter.cpp classregistration.cpp configurator.cpp consoleappender.cpp cyclicbuffer.cpp dailyrollingfileappender.cpp datagrampacket.cpp datagramsocket.cpp date.cpp dateformat.cpp datelayout.cpp datepatternconverter.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 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 ndcpatternconverter.cpp nteventlogappender.cpp objectoutputstream.cpp obsoleterollingfileappender.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 serversocket.cpp simpledateformat.cpp simplelayout.cpp sizebasedtriggeringpolicy.cpp smtpappender.cpp socket.cpp socketappender.cpp socketappenderskeleton.cpp sockethubappender.cpp socketoutputstream.cpp strftimedateformat.cpp stringhelper.cpp stringmatchfilter.cpp stringtokenizer.cpp syslogappender.cpp syslogwriter.cpp system.cpp systemerrwriter.cpp systemoutwriter.cpp telnetappender.cpp threadlocal.cpp threadpatternconverter.cpp threadspecificdata.cpp throwableinformationpatternconverter.cpp timebasedrollingpolicy.cpp timezone.cpp transcoder.cpp transform.cpp triggeringpolicy.cpp ttcclayout.cpp writer.cpp writerappender.cpp xmllayout.cpp xmlsocketappender.cpp zipcompressaction.cpp ) set_target_properties(log4cxx PROPERTIES VERSION ${LIBLOG4CXX_LIB_VERSION} SOVERSION ${LIBLOG4CXX_LIB_SOVERSION} ) boostfallback_link(log4cxx) 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 ${PROJECT_VERSION_MINOR} $ DEPENDS log4cxx COMMENT "Dumping ABI symbols") add_custom_target(compare-abi ALL COMMAND perl ${abi-compliance-script} -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-0.12.1/src/main/cpp/strftimedateformat.cpp000644 001750 001750 00000003343 14120250670 024143 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; StrftimeDateFormat::StrftimeDateFormat(const LogString& fmt) : timeZone(TimeZone::getDefault()) { log4cxx::helpers::Transcoder::encode(fmt, pattern); } StrftimeDateFormat::~StrftimeDateFormat() { } void StrftimeDateFormat::format(LogString& s, log4cxx_time_t time, Pool& /* p */ ) const { apr_time_exp_t exploded; apr_status_t stat = 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, pattern.c_str(), &exploded); if (stat == APR_SUCCESS) { log4cxx::helpers::Transcoder::decode(std::string(buf, bufLen), s); } } } void StrftimeDateFormat::setTimeZone(const TimeZonePtr& zone) { timeZone = zone; } apache-log4cxx-0.12.1/src/main/cpp/levelrangefilter.cpp000644 001750 001750 00000005250 14120250670 023570 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; IMPLEMENT_LOG4CXX_OBJECT(LevelRangeFilter) LevelRangeFilter::LevelRangeFilter() : acceptOnMatch(false), levelMin(Level::getAll()), levelMax(Level::getOff()) { } void LevelRangeFilter::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LEVELMIN"), LOG4CXX_STR("levelmin"))) { levelMin = OptionConverter::toLevel(value, levelMin); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LEVELMAX"), LOG4CXX_STR("levelmax"))) { levelMax = OptionConverter::toLevel(value, levelMax); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch"))) { acceptOnMatch = OptionConverter::toBoolean(value, acceptOnMatch); } } Filter::FilterDecision LevelRangeFilter::decide( const spi::LoggingEventPtr& event) const { if (levelMin != 0 && !event->getLevel()->isGreaterOrEqual(levelMin)) { // level of event is less than minimum return Filter::DENY; } if (levelMax != 0 && event->getLevel()->toInt() > levelMax->toInt()) { // level of event is greater than maximum // Alas, there is no Level.isGreater method. and using // a combo of isGreaterOrEqual && !Equal seems worse than // checking the int values of the level objects.. return Filter::DENY; } if (acceptOnMatch) { // this filter set up to bypass later filters and always return // accept if level in range return Filter::ACCEPT; } else { // event is ok for this filter; allow later filters to have a look.. return Filter::NEUTRAL; } } apache-log4cxx-0.12.1/src/main/cpp/logstream.cpp000644 001750 001750 00000027700 14120250670 022237 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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; 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-0.12.1/src/main/cpp/filerenameaction.cpp000644 001750 001750 00000002454 14120250670 023546 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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(FileRenameAction) FileRenameAction::FileRenameAction(const File& toRename, const File& renameTo, bool renameEmptyFile1) : source(toRename), destination(renameTo), renameEmptyFile(renameEmptyFile1) { } bool FileRenameAction::execute(log4cxx::helpers::Pool& pool1) const { return source.renameTo(destination, pool1); } apache-log4cxx-0.12.1/src/main/cpp/nameabbreviator.cpp000644 001750 001750 00000020150 14120250670 023373 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 { } }; /** * 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 { // 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 { // // 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 NameAbbreviatorPtr(new MaxElementAbbreviator(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++; } NameAbbreviatorPtr abbrev(new PatternAbbreviator(fragments)); return abbrev; } // // no matching abbreviation, return defaultAbbreviator // return getDefaultAbbreviator(); } /** * Gets default abbreviator. * * @return default abbreviator. */ NameAbbreviatorPtr NameAbbreviator::getDefaultAbbreviator() { static NameAbbreviatorPtr def(new NOPAbbreviator()); return def; } apache-log4cxx-0.12.1/src/main/cpp/throwableinformationpatternconverter.cpp000644 001750 001750 00000004275 14120250670 030027 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ThrowableInformationPatternConverter) ThrowableInformationPatternConverter::ThrowableInformationPatternConverter(bool shortReport1) : LoggingEventPatternConverter(LOG4CXX_STR("Throwable"), LOG4CXX_STR("throwable")), shortReport(shortReport1) { } PatternConverterPtr ThrowableInformationPatternConverter::newInstance( const std::vector& options) { if (options.size() > 0 && options[0].compare(LOG4CXX_STR("short")) == 0) { static PatternConverterPtr shortConverter(new ThrowableInformationPatternConverter(true)); return shortConverter; } static PatternConverterPtr converter(new ThrowableInformationPatternConverter(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-0.12.1/src/main/cpp/dateformat.cpp000644 001750 001750 00000002322 14120250670 022361 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/main/cpp/appenderattachableimpl.cpp000644 001750 001750 00000010127 14120250670 024726 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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) AppenderAttachableImpl::AppenderAttachableImpl(Pool& pool) : appenderList() { } void AppenderAttachableImpl::addAppender(const AppenderPtr newAppender) { // Null values for newAppender parameter are strictly forbidden. if (newAppender == 0) { return; } std::unique_lock lock( m_mutex ); AppenderList::iterator it = std::find( appenderList.begin(), appenderList.end(), newAppender); if (it == appenderList.end()) { appenderList.push_back(newAppender); } } int AppenderAttachableImpl::appendLoopOnAppenders( const spi::LoggingEventPtr& event, Pool& p) { AppenderList allAppenders; int numberAppended = 0; { // There are occasions where we want to modify our list of appenders // while we are iterating over them. For example, if one of the // appenders fails, we may want to swap it out for a new one. // So, make a local copy of the appenders that we want to iterate over // before actually iterating over them. std::unique_lock lock( m_mutex ); allAppenders = appenderList; } for (AppenderList::iterator it = allAppenders.begin(); it != allAppenders.end(); it++) { (*it)->doAppend(event, p); numberAppended++; } return numberAppended; } AppenderList AppenderAttachableImpl::getAllAppenders() const { return appenderList; } AppenderPtr AppenderAttachableImpl::getAppender(const LogString& name) const { if (name.empty()) { return 0; } std::unique_lock lock( m_mutex ); AppenderList::const_iterator it, itEnd = appenderList.end(); AppenderPtr appender; for (it = 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::unique_lock lock( m_mutex ); AppenderList::const_iterator it = std::find( appenderList.begin(), appenderList.end(), appender); return it != appenderList.end(); } void AppenderAttachableImpl::removeAllAppenders() { std::unique_lock lock( m_mutex ); AppenderList::iterator it, itEnd = appenderList.end(); AppenderPtr a; for (it = appenderList.begin(); it != itEnd; it++) { a = *it; a->close(); } appenderList.clear(); } void AppenderAttachableImpl::removeAppender(const AppenderPtr appender) { if (appender == 0) { return; } std::unique_lock lock( m_mutex ); AppenderList::iterator it = std::find( appenderList.begin(), appenderList.end(), appender); if (it != appenderList.end()) { appenderList.erase(it); } } void AppenderAttachableImpl::removeAppender(const LogString& name) { if (name.empty()) { return; } std::unique_lock lock( m_mutex ); AppenderList::iterator it, itEnd = appenderList.end(); AppenderPtr appender; for (it = appenderList.begin(); it != itEnd; it++) { appender = *it; if (name == appender->getName()) { appenderList.erase(it); return; } } } apache-log4cxx-0.12.1/src/main/cpp/defaultrepositoryselector.cpp000644 001750 001750 00000002214 14120250670 025560 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; DefaultRepositorySelector::DefaultRepositorySelector(const LoggerRepositoryPtr repository1) : repository(repository1) { } LoggerRepositoryPtr DefaultRepositorySelector::getLoggerRepository() { return repository; } apache-log4cxx-0.12.1/src/main/cpp/integerpatternconverter.cpp000644 001750 001750 00000003320 14120250670 025215 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new IntegerPatternConverter()); 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-0.12.1/src/main/cpp/reader.cpp000644 001750 001750 00000001731 14120250670 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. */ #include #include using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(Reader) Reader::Reader() { } Reader::~Reader() { } apache-log4cxx-0.12.1/src/main/cpp/htmllayout.cpp000644 001750 001750 00000016040 14120250670 022437 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; IMPLEMENT_LOG4CXX_OBJECT(HTMLLayout) HTMLLayout::HTMLLayout() : locationInfo(false), title(LOG4CXX_STR("Log4cxx Log Messages")), dateFormat() { dateFormat.setTimeZone(TimeZone::getGMT()); } 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("")); 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 (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(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 ")); dateFormat.format(output, apr_time_now(), 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 (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("")); } apache-log4cxx-0.12.1/src/main/cpp/propertysetter.cpp000644 001750 001750 00000005744 14120250670 023361 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/main/cpp/simpledateformat.cpp000644 001750 001750 00000040461 14120250670 023601 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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, (wchar_t) 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 ); } } SimpleDateFormat::SimpleDateFormat( const LogString& fmt ) : timeZone( TimeZone::getDefault() ) { #if LOG4CXX_HAS_STD_LOCALE std::locale defaultLocale; parsePattern( fmt, & defaultLocale, pattern ); #else parsePattern( fmt, NULL, pattern ); #endif for ( PatternTokenList::iterator iter = pattern.begin(); iter != pattern.end(); iter++ ) { ( * iter )->setTimeZone( timeZone ); } } SimpleDateFormat::SimpleDateFormat( const LogString& fmt, const std::locale* locale ) : timeZone( TimeZone::getDefault() ) { parsePattern( fmt, locale, pattern ); for ( PatternTokenList::iterator iter = pattern.begin(); iter != pattern.end(); iter++ ) { ( * iter )->setTimeZone( timeZone ); } } SimpleDateFormat::~SimpleDateFormat() { for ( PatternTokenList::iterator iter = pattern.begin(); iter != 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 = timeZone->explode( & exploded, time ); if ( stat == APR_SUCCESS ) { for ( PatternTokenList::const_iterator iter = pattern.begin(); iter != pattern.end(); iter++ ) { ( * iter )->format( s, exploded, p ); } } } void SimpleDateFormat::setTimeZone( const TimeZonePtr& zone ) { timeZone = zone; } apache-log4cxx-0.12.1/src/main/cpp/aprinitializer.cpp000644 001750 001750 00000005700 14120250670 023264 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 using namespace log4cxx::helpers; using namespace log4cxx; bool APRInitializer::isDestructed = false; namespace { extern "C" void tlsDestruct(void* ptr) { delete ((ThreadSpecificData*) ptr); } } APRInitializer::APRInitializer() : p(0), startTime(0), tlsKey(0) { apr_initialize(); apr_pool_create(&p, NULL); apr_atomic_init(p); startTime = apr_time_now(); #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_create(&tlsKey, tlsDestruct, p); assert(stat == APR_SUCCESS); assert(stat == APR_SUCCESS); #endif } APRInitializer::~APRInitializer() { { #if APR_HAS_THREADS std::unique_lock lock(mutex); apr_threadkey_private_delete(tlsKey); #endif for (std::list::iterator iter = watchdogs.begin(); iter != watchdogs.end(); iter++) { delete *iter; } } // TODO LOGCXX-322 #ifndef APR_HAS_THREADS apr_terminate(); #endif isDestructed = true; } APRInitializer& APRInitializer::getInstance() { static APRInitializer init; return init; } log4cxx_time_t APRInitializer::initialize() { return getInstance().startTime; } apr_pool_t* APRInitializer::getRootPool() { return getInstance().p; } apr_threadkey_t* APRInitializer::getTlsKey() { return getInstance().tlsKey; } void APRInitializer::registerCleanup(FileWatchdog* watchdog) { APRInitializer& instance(getInstance()); #if APR_HAS_THREADS std::unique_lock lock(instance.mutex); #endif instance.watchdogs.push_back(watchdog); } void APRInitializer::unregisterCleanup(FileWatchdog* watchdog) { APRInitializer& instance(getInstance()); #if APR_HAS_THREADS std::unique_lock lock(instance.mutex); #endif for (std::list::iterator iter = instance.watchdogs.begin(); iter != instance.watchdogs.end(); iter++) { if (*iter == watchdog) { instance.watchdogs.erase(iter); return; } } } apache-log4cxx-0.12.1/src/main/cpp/levelmatchfilter.cpp000644 001750 001750 00000004301 14120250670 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 using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(LevelMatchFilter) LevelMatchFilter::LevelMatchFilter() : acceptOnMatch(true) { } 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"))) { acceptOnMatch = OptionConverter::toBoolean(value, acceptOnMatch); } } void LevelMatchFilter::setLevelToMatch(const LogString& levelToMatch1) { this->levelToMatch = OptionConverter::toLevel(levelToMatch1, this->levelToMatch); } LogString LevelMatchFilter::getLevelToMatch() const { return levelToMatch->toString(); } Filter::FilterDecision LevelMatchFilter::decide( const log4cxx::spi::LoggingEventPtr& event) const { if (levelToMatch != 0 && levelToMatch->equals(event->getLevel())) { if (acceptOnMatch) { return Filter::ACCEPT; } else { return Filter::DENY; } } else { return Filter::NEUTRAL; } } apache-log4cxx-0.12.1/src/main/cpp/fixedwindowrollingpolicy.cpp000644 001750 001750 00000017650 14120250670 025403 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(FixedWindowRollingPolicy) FixedWindowRollingPolicy::FixedWindowRollingPolicy() : minIndex(1), maxIndex(7) { } void FixedWindowRollingPolicy::setMaxIndex(int maxIndex1) { this->maxIndex = maxIndex1; } void FixedWindowRollingPolicy::setMinIndex(int minIndex1) { this->minIndex = minIndex1; } void FixedWindowRollingPolicy::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MININDEX"), LOG4CXX_STR("minindex"))) { minIndex = OptionConverter::toInt(value, 1); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MAXINDEX"), LOG4CXX_STR("maxindex"))) { maxIndex = OptionConverter::toInt(value, 7); } else { RollingPolicyBase::setOption(option, value); } } /** * {@inheritDoc} */ void FixedWindowRollingPolicy::activateOptions(Pool& p) { RollingPolicyBase::activateOptions(p); if (maxIndex < minIndex) { LogLog::warn( LOG4CXX_STR("MaxIndex cannot be smaller than MinIndex.")); maxIndex = minIndex; } if ((maxIndex - minIndex) > MAX_WINDOW_SIZE) { LogLog::warn(LOG4CXX_STR("Large window sizes are not allowed.")); maxIndex = 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); explicitActiveFile = false; if (currentActiveFile.length() > 0) { explicitActiveFile = true; newActiveFile = currentActiveFile; } if (!explicitActiveFile) { LogString buf; ObjectPtr obj(new Integer(minIndex)); formatFileName(obj, buf, pool); newActiveFile = buf; } ActionPtr noAction; return RolloverDescriptionPtr( new RolloverDescription(newActiveFile, append, noAction, noAction)); } /** * {@inheritDoc} */ RolloverDescriptionPtr FixedWindowRollingPolicy::rollover( const LogString& currentActiveFile, const bool append, Pool& pool) { RolloverDescriptionPtr desc; if (maxIndex < 0) { return desc; } int purgeStart = minIndex; if (!explicitActiveFile) { purgeStart++; } if (!purge(purgeStart, maxIndex, pool)) { return desc; } LogString buf; ObjectPtr obj(new Integer(purgeStart)); formatFileName(obj, buf, pool); LogString renameTo(buf); LogString compressedName(renameTo); ActionPtr compressAction ; if (StringHelper::endsWith(renameTo, LOG4CXX_STR(".gz"))) { renameTo.resize(renameTo.size() - 3); compressAction = ActionPtr( new GZCompressAction( File().setPath(renameTo), File().setPath(compressedName), true)); } else if (StringHelper::endsWith(renameTo, LOG4CXX_STR(".zip"))) { renameTo.resize(renameTo.size() - 4); compressAction = ActionPtr( new ZipCompressAction( File().setPath(renameTo), File().setPath(compressedName), true)); } FileRenameActionPtr renameAction = FileRenameActionPtr( new FileRenameAction( File().setPath(currentActiveFile), File().setPath(renameTo), false)); desc = RolloverDescriptionPtr(new RolloverDescription( 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 maxIndex; } /** * Get index of most recent log file. * @return index of oldest log file. */ int FixedWindowRollingPolicy::getMinIndex() const { return 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 = ObjectPtr(new Integer(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 = ObjectPtr(new Integer(i + 1)); formatFileName(obj, buf, p); LogString highFilename(buf); LogString renameTo(highFilename); if (isBase) { renameTo = highFilename.substr(0, highFilename.length() - suffixLength); } renames.push_back(FileRenameActionPtr(new FileRenameAction(*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-0.12.1/src/main/cpp/propertiespatternconverter.cpp000644 001750 001750 00000005146 14120250670 025764 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(PropertiesPatternConverter) PropertiesPatternConverter::PropertiesPatternConverter(const LogString& name1, const LogString& propertyName) : LoggingEventPatternConverter(name1, LOG4CXX_STR("property")), option(propertyName) { } PatternConverterPtr PropertiesPatternConverter::newInstance( const std::vector& options) { if (options.size() == 0) { static PatternConverterPtr def(new PropertiesPatternConverter( LOG4CXX_STR("Properties"), LOG4CXX_STR(""))); return def; } LogString converterName(LOG4CXX_STR("Property{")); converterName.append(options[0]); converterName.append(LOG4CXX_STR("}")); PatternConverterPtr converter(new PropertiesPatternConverter( converterName, options[0])); return converter; } void PropertiesPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { if (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(option, toAppendTo); } } apache-log4cxx-0.12.1/src/main/cpp/charsetdecoder.cpp000644 001750 001750 00000030464 14120250670 023222 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 CharsetDecoderPtr( new UTF8CharsetDecoder() ); } return decoder; } CharsetDecoderPtr CharsetDecoder::getISOLatinDecoder() { return CharsetDecoderPtr( new ISOLatinCharsetDecoder() ); } 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 CharsetDecoderPtr( new UTF8CharsetDecoder() ); } 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 CharsetDecoderPtr( new USASCIICharsetDecoder() ); } 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 CharsetDecoderPtr( new ISOLatinCharsetDecoder() ); } #if APR_HAS_XLATE return CharsetDecoderPtr( new APRCharsetDecoder(charset) ); #else throw IllegalArgumentException(charset); #endif } apache-log4cxx-0.12.1/src/main/cpp/relativetimedateformat.cpp000644 001750 001750 00000002573 14120250670 025004 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { log4cxx_int64_t interval = (date - startTime) / APR_INT64_C(1000); StringHelper::toString(interval, p, s); } apache-log4cxx-0.12.1/src/main/cpp/logger.cpp000644 001750 001750 00000053714 14120250670 021525 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(Logger) Logger::Logger(Pool& p, const LogString& name1) : pool(&p), name(), level(), parent(), resourceBundle(), repository(), aai(new AppenderAttachableImpl(*pool)) { name = name1; additive = true; } Logger::~Logger() { } void Logger::addAppender(const AppenderPtr newAppender) { log4cxx::spi::LoggerRepositoryPtr rep; aai->addAppender(newAppender); rep = repository.lock(); if (rep) { rep->fireAddAppenderEvent(this, newAppender.get()); } } void Logger::reconfigure( const std::vector& appenders, bool additive1 ) { std::unique_lock lock(mutex); additive = additive1; aai->removeAllAppenders(); for ( std::vector::const_iterator it = appenders.cbegin(); it != appenders.cend(); it++ ) { aai->addAppender( *it ); if (log4cxx::spi::LoggerRepositoryPtr rep = repository.lock()) { 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->parent.get()) { writes += logger->aai->appendLoopOnAppenders(event, p); if (!logger->additive) { break; } } log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); 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 { Pool p; LOG4CXX_DECODE_CHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, location)); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::string& message) const { Pool p; LOG4CXX_DECODE_CHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, LocationInfo::getLocationUnavailable())); callAppenders(event, p); } void Logger::forcedLogLS(const LevelPtr& level1, const LogString& message, const LocationInfo& location) const { Pool p; LoggingEventPtr event(new LoggingEvent(name, level1, message, location)); callAppenders(event, p); } bool Logger::getAdditivity() const { return additive; } AppenderList Logger::getAllAppenders() const { return aai->getAllAppenders(); } AppenderPtr Logger::getAppender(const LogString& name1) const { return aai->getAppender(name1); } const LevelPtr Logger::getEffectiveLevel() const { for (const Logger* l = this; l != 0; l = l->parent.get()) { if (l->level != 0) { return l->level; } } throw NullPointerException(LOG4CXX_STR("No level specified for logger or ancestors.")); #if LOG4CXX_RETURN_AFTER_THROW return this->level; #endif } LoggerRepositoryWeakPtr Logger::getLoggerRepository() const { return repository; } ResourceBundlePtr Logger::getResourceBundle() const { for (const Logger* l = this; l != 0; l = l->parent.get()) { if (l->resourceBundle != 0) { return l->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 parent; } LevelPtr Logger::getLevel() const { return level; } bool Logger::isAttached(const AppenderPtr appender) const { return aai->isAttached(appender); } bool Logger::isTraceEnabled() const { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); if (!rep || rep->isDisabled(Level::TRACE_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::TRACE_INT; } bool Logger::isDebugEnabled() const { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); if (!rep || rep->isDisabled(Level::DEBUG_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::DEBUG_INT; } bool Logger::isEnabledFor(const LevelPtr& level1) const { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); if (!rep || rep->isDisabled(level1->toInt())) { return false; } return level1->isGreaterOrEqual(getEffectiveLevel()); } bool Logger::isInfoEnabled() const { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); if (!rep || rep->isDisabled(Level::INFO_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::INFO_INT; } bool Logger::isErrorEnabled() const { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); if (!rep || rep->isDisabled(Level::ERROR_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::ERROR_INT; } bool Logger::isWarnEnabled() const { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); if (!rep || rep->isDisabled(Level::WARN_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::WARN_INT; } bool Logger::isFatalEnabled() const { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); 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) { if (repository == 0 || repository->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 { log4cxx::spi::LoggerRepositoryPtr rep = repository.lock(); 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() { aai->removeAllAppenders(); } void Logger::removeAppender(const AppenderPtr appender) { aai->removeAppender(appender); } void Logger::removeAppender(const LogString& name1) { aai->removeAppender(name1); } void Logger::setAdditivity(bool additive1) { this->additive = additive1; } void Logger::setHierarchy(spi::LoggerRepositoryWeakPtr repository1) { this->repository = repository1; } void Logger::setLevel(const LevelPtr level1) { this->level = level1; } LoggerPtr Logger::getLogger(const std::string& name) { return LogManager::getLogger(name); } LoggerPtr Logger::getLogger(const char* const name) { return LogManager::getLogger(name); } 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(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 { Pool p; LOG4CXX_DECODE_WCHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, location)); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::wstring& message) const { Pool p; LOG4CXX_DECODE_WCHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, LocationInfo::getLocationUnavailable())); callAppenders(event, p); } void Logger::getName(std::wstring& rv) const { Transcoder::encode(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 { Pool p; LOG4CXX_DECODE_UNICHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, location)); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::basic_string& message) const { Pool p; LOG4CXX_DECODE_UNICHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, LocationInfo::getLocationUnavailable())); callAppenders(event, p); } #endif #if LOG4CXX_UNICHAR_API void Logger::getName(std::basic_string& rv) const { Transcoder::encode(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 { Pool p; LOG4CXX_DECODE_CFSTRING(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, location)); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const CFStringRef& message) const { Pool p; LOG4CXX_DECODE_CFSTRING(msg, message); LoggingEventPtr event(new LoggingEvent(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-0.12.1/src/main/cpp/transform.cpp000644 001750 001750 00000005330 14120250670 022250 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/cpp/stringmatchfilter.cpp000644 001750 001750 00000004115 14120250670 023766 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; IMPLEMENT_LOG4CXX_OBJECT(StringMatchFilter) StringMatchFilter::StringMatchFilter() : acceptOnMatch(true), stringToMatch() { } void StringMatchFilter::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("STRINGTOMATCH"), LOG4CXX_STR("stringtomatch"))) { stringToMatch = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch"))) { acceptOnMatch = OptionConverter::toBoolean(value, acceptOnMatch); } } Filter::FilterDecision StringMatchFilter::decide( const log4cxx::spi::LoggingEventPtr& event) const { const LogString& msg = event->getRenderedMessage(); if (msg.empty() || stringToMatch.empty()) { return Filter::NEUTRAL; } if ( msg.find(stringToMatch) == LogString::npos ) { return Filter::NEUTRAL; } else { // we've got a match if (acceptOnMatch) { return Filter::ACCEPT; } else { return Filter::DENY; } } } apache-log4cxx-0.12.1/src/main/cpp/andfilter.cpp000644 001750 001750 00000003457 14120250670 022215 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(AndFilter) AndFilter::AndFilter() : headFilter(), tailFilter(), acceptOnMatch(true) { } void AndFilter::addFilter(const FilterPtr& filter) { if (headFilter == NULL) { headFilter = filter; tailFilter = filter; } else { tailFilter->setNext(filter); } } void AndFilter::setAcceptOnMatch(bool newValue) { acceptOnMatch = newValue; } Filter::FilterDecision AndFilter::decide( const spi::LoggingEventPtr& event) const { bool accepted = true; FilterPtr f(headFilter); while (f != NULL) { accepted = accepted && (Filter::ACCEPT == f->decide(event)); f = f->getNext(); } if (accepted) { if (acceptOnMatch) { return Filter::ACCEPT; } return Filter::DENY; } return Filter::NEUTRAL; } apache-log4cxx-0.12.1/src/main/cpp/writer.cpp000644 001750 001750 00000002257 14120250670 021556 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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; IMPLEMENT_LOG4CXX_OBJECT(Writer) Writer::Writer() { } Writer::~Writer() { } #ifdef LOG4CXX_MULTI_PROCESS OutputStreamPtr Writer::getOutPutStreamPtr() { throw std::logic_error("getOutPutStreamPtr must be implemented in the derived class that you are using"); } #endif apache-log4cxx-0.12.1/src/main/cpp/class.cpp000644 001750 001750 00000013130 14120250670 021337 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include #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 #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; using namespace log4cxx::filter; using namespace log4cxx::xml; using namespace log4cxx::rolling; 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 log4cxx::RollingFileAppender::registerClass(); SMTPAppender::registerClass(); SocketAppender::registerClass(); #if APR_HAS_THREADS SocketHubAppender::registerClass(); #endif SyslogAppender::registerClass(); #if APR_HAS_THREADS TelnetAppender::registerClass(); #endif XMLSocketAppender::registerClass(); DateLayout::registerClass(); HTMLLayout::registerClass(); PatternLayout::registerClass(); SimpleLayout::registerClass(); TTCCLayout::registerClass(); XMLLayout::registerClass(); LevelMatchFilter::registerClass(); LevelRangeFilter::registerClass(); StringMatchFilter::registerClass(); log4cxx::RollingFileAppender::registerClass(); log4cxx::rolling::RollingFileAppender::registerClass(); DailyRollingFileAppender::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(); } apache-log4cxx-0.12.1/src/main/cpp/transcoder.cpp000644 001750 001750 00000032364 14120250670 022410 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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_LOGCHAR_IS_UNICHAR || LOG4CXX_CFSTRING_API || LOG4CXX_UNICHAR_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 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-0.12.1/src/main/cpp/propertyresourcebundle.cpp000644 001750 001750 00000003331 14120250670 025062 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/main/cpp/loggerpatternconverter.cpp000644 001750 001750 00000003620 14120250670 025042 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new LoggerPatternConverter(options)); return def; } return PatternConverterPtr(new LoggerPatternConverter(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-0.12.1/src/main/cpp/xmllayout.cpp000644 001750 001750 00000012046 14120250670 022275 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; IMPLEMENT_LOG4CXX_OBJECT(XMLLayout) XMLLayout::XMLLayout() : locationInfo(false), properties(false) { } 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 (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 (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); } apache-log4cxx-0.12.1/src/main/cpp/integer.cpp000644 001750 001750 00000002056 14120250670 021674 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/cpp/timebasedrollingpolicy.cpp000644 001750 001750 00000025124 14120250670 025004 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #ifdef LOG4CXX_MULTI_PROCESS #include #endif #include #include #include #include #include #include #include #include #include #include #include #ifndef INT64_C #define INT64_C(x) x ## LL #endif #include using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::helpers; using namespace log4cxx::pattern; IMPLEMENT_LOG4CXX_OBJECT(TimeBasedRollingPolicy) #ifdef LOG4CXX_MULTI_PROCESS #define MMAP_FILE_SUFFIX ".map" #define LOCK_FILE_SUFFIX ".maplck" #define MAX_FILE_LEN 2048 bool TimeBasedRollingPolicy::isMapFileEmpty(log4cxx::helpers::Pool& pool) { apr_finfo_t finfo; apr_status_t st = apr_stat(&finfo, _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 (!_mmap) { iRet = createMMapFile(std::string(_fileNamePattern), pool); } if (!iRet && isMapFileEmpty(pool)) { lockMMapFile(APR_FLOCK_EXCLUSIVE); memset(_mmap->mm, 0, MAX_FILE_LEN); memcpy(_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); } return std::string(::dirname(szDirName)) + "/." + ::basename(szBaseName) + szUid + suffix; } int TimeBasedRollingPolicy::createMMapFile(const std::string& fileName, log4cxx::helpers::Pool& pool) { _mapFileName = createFile(fileName, MMAP_FILE_SUFFIX, pool); apr_status_t stat = apr_file_open(&_file_map, _mapFileName.c_str(), APR_CREATE | APR_READ | APR_WRITE, APR_OS_DEFAULT, _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 " + _mapFileName + " if exist."); LogLog::warn(LOG4CXX_STR(err.c_str())); return -1; } if (isMapFileEmpty(pool)) { stat = apr_file_trunc(_file_map, MAX_FILE_LEN + 1); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("apr_file_trunc failed.")); apr_file_close(_file_map); return -1; } } stat = apr_mmap_create(&_mmap, _file_map, 0, MAX_FILE_LEN, APR_MMAP_WRITE | APR_MMAP_READ, _mmapPool->getAPRPool()); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("mmap failed.")); apr_file_close(_file_map); return -1; } return 0; } int TimeBasedRollingPolicy::lockMMapFile(int type) { apr_status_t stat = apr_file_lock(_lock_file, type); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("apr_file_lock for mmap failed.")); } } int TimeBasedRollingPolicy::unLockMMapFile() { apr_status_t stat = apr_file_unlock(_lock_file); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("apr_file_unlock for mmap failed.")); } } #endif TimeBasedRollingPolicy::TimeBasedRollingPolicy() #ifdef LOG4CXX_MULTI_PROCESS : _mmap(NULL), _file_map(NULL), bAlreadyInitialized(false), _mmapPool(new Pool()), _lock_file(NULL), bRefreshCurFile(false) #endif { } #ifdef LOG4CXX_MULTI_PROCESS TimeBasedRollingPolicy::~TimeBasedRollingPolicy() { //no-need to delete mmap delete _mmapPool; } #endif 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(); } apr_time_t n = apr_time_now(); LogString buf; ObjectPtr obj(new Date(n)); formatFileName(obj, buf, pool); lastFileName = buf; #ifdef LOG4CXX_MULTI_PROCESS if (getPatternConverterList().size()) { (*(getPatternConverterList().begin()))->format(obj, _fileNamePattern, pool); } else { _fileNamePattern = lastFileName; } if (!_lock_file) { const std::string lockname = createFile(std::string(_fileNamePattern), LOCK_FILE_SUFFIX, *_mmapPool); apr_status_t stat = apr_file_open(&_lock_file, lockname.c_str(), APR_CREATE | APR_READ | APR_WRITE, APR_OS_DEFAULT, (*_mmapPool).getAPRPool()); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("open lock file failed.")); } } initMMapFile(lastFileName, *_mmapPool); #endif suffixLength = 0; if (lastFileName.length() >= 3) { if (lastFileName.compare(lastFileName.length() - 3, 3, LOG4CXX_STR(".gz")) == 0) { suffixLength = 3; } else if (lastFileName.length() >= 4 && lastFileName.compare(lastFileName.length() - 4, 4, LOG4CXX_STR(".zip")) == 0) { 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) { apr_time_t n = apr_time_now(); nextCheck = ((n / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC; File currentFile(currentActiveFile); LogString buf; ObjectPtr obj(new Date(currentFile.exists(pool) ? currentFile.lastModified(pool) : n)); formatFileName(obj, buf, pool); lastFileName = buf; ActionPtr noAction; if (currentActiveFile.length() > 0) { return RolloverDescriptionPtr(new RolloverDescription( currentActiveFile, append, noAction, noAction)); } else { bRefreshCurFile = true; return RolloverDescriptionPtr(new RolloverDescription( lastFileName.substr(0, lastFileName.length() - suffixLength), append, noAction, noAction)); } } RolloverDescriptionPtr TimeBasedRollingPolicy::rollover( const LogString& currentActiveFile, const bool append, Pool& pool) { apr_time_t n = apr_time_now(); nextCheck = ((n / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC; LogString buf; ObjectPtr obj(new Date(n)); formatFileName(obj, buf, pool); LogString newFileName(buf); #ifdef LOG4CXX_MULTI_PROCESS bAlreadyInitialized = true; if (_mmap && !isMapFileEmpty(*_mmapPool)) { lockMMapFile(APR_FLOCK_SHARED); LogString mapLastFile((char*)_mmap->mm); lastFileName = mapLastFile; unLockMMapFile(); } else { _mmap = NULL; initMMapFile(lastFileName, *_mmapPool); } #endif // // if file names haven't changed, no rollover // if (newFileName == lastFileName) { RolloverDescriptionPtr desc; return desc; } ActionPtr renameAction; ActionPtr compressAction; LogString lastBaseName( lastFileName.substr(0, lastFileName.length() - suffixLength)); LogString nextActiveFile( newFileName.substr(0, newFileName.length() - suffixLength)); // // if currentActiveFile is not lastBaseName then // active file name is not following file pattern // and requires a rename plus maintaining the same name if (currentActiveFile != lastBaseName) { renameAction = FileRenameActionPtr( new FileRenameAction( File().setPath(currentActiveFile), File().setPath(lastBaseName), true)); nextActiveFile = currentActiveFile; } if (suffixLength == 3) { compressAction = GZCompressActionPtr( new GZCompressAction( File().setPath(lastBaseName), File().setPath(lastFileName), true)); } if (suffixLength == 4) { compressAction = ZipCompressActionPtr( new ZipCompressAction( File().setPath(lastBaseName), File().setPath(lastFileName), true)); } #ifdef LOG4CXX_MULTI_PROCESS if (_mmap && !isMapFileEmpty(*_mmapPool)) { lockMMapFile(APR_FLOCK_EXCLUSIVE); memset(_mmap->mm, 0, MAX_FILE_LEN); memcpy(_mmap->mm, std::string(newFileName).c_str(), std::string(newFileName).size()); unLockMMapFile(); } else { _mmap = NULL; initMMapFile(newFileName, *_mmapPool); } #else lastFileName = newFileName; #endif return RolloverDescriptionPtr(new RolloverDescription(nextActiveFile, append, renameAction, compressAction)); } bool TimeBasedRollingPolicy::isTriggeringEvent( Appender* appender, const log4cxx::spi::LoggingEventPtr& /* event */, const LogString& filename, size_t /* fileLength */) { #ifdef LOG4CXX_MULTI_PROCESS if (bRefreshCurFile && _mmap && !isMapFileEmpty(*_mmapPool)) { lockMMapFile(APR_FLOCK_SHARED); LogString mapCurrent((char*)_mmap->mm); unLockMMapFile(); LogString mapCurrentBase(mapCurrent.substr(0, mapCurrent.length() - suffixLength)); if (!mapCurrentBase.empty() && mapCurrentBase != filename) { dynamic_cast(appender)->setFile(mapCurrentBase); } } return ((apr_time_now()) > nextCheck) || (!bAlreadyInitialized); #else return apr_time_now() > nextCheck; #endif } apache-log4cxx-0.12.1/src/main/cpp/logmanager.cpp000644 001750 001750 00000012535 14120250670 022356 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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; spi::RepositorySelectorPtr LogManager::repositorySelector; RepositorySelectorPtr LogManager::getRepositorySelector() { // // call to initialize APR and trigger "start" of logging clock // APRInitializer::initialize(); if (!repositorySelector) { LoggerRepositoryPtr hierarchy = Hierarchy::create(); RepositorySelectorPtr selector(new DefaultRepositorySelector(hierarchy)); repositorySelector = selector; } return repositorySelector; } 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; LogManager::getRepositorySelector() = selector; } LoggerRepositoryPtr LogManager::getLoggerRepository() { return getRepositorySelector()->getLoggerRepository(); } LoggerPtr LogManager::getRootLogger() { // Delegate the actual manufacturing of the logger to the logger repository. return getLoggerRepository()->getRootLogger(); } /** Retrieve the appropriate Logger instance. */ LoggerPtr LogManager::getLoggerLS(const LogString& name) { return getLoggerRepository()->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. return getLoggerRepository()->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() { LoggerRepositoryPtr repPtr = getLoggerRepository(); getLoggerRepository()->shutdown(); } void LogManager::resetConfiguration() { getLoggerRepository()->resetConfiguration(); } apache-log4cxx-0.12.1/src/main/cpp/relativetimepatternconverter.cpp000644 001750 001750 00000003520 14120250670 026254 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new RelativeTimePatternConverter()); 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-0.12.1/src/main/cpp/sizebasedtriggeringpolicy.cpp000644 001750 001750 00000003565 14120250670 025520 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/main/cpp/system.cpp000644 001750 001750 00000005134 14120250670 021563 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/main/cpp/properties.cpp000644 001750 001750 00000017633 14120250670 022442 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; InputStreamReaderPtr lineReader( new InputStreamReader(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-0.12.1/src/main/cpp/namepatternconverter.cpp000644 001750 001750 00000003603 14120250670 024504 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(NamePatternConverter) NamePatternConverter::NamePatternConverter( const LogString& name1, const LogString& style1, const std::vector& options) : LoggingEventPatternConverter(name1, style1), abbreviator(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(int nameStart, LogString& buf) const { abbreviator->abbreviate(nameStart, buf); } apache-log4cxx-0.12.1/src/main/cpp/filelocationpatternconverter.cpp000644 001750 001750 00000003365 14120250670 026241 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new FileLocationPatternConverter()); return instance; } void FileLocationPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */ ) const { append(toAppendTo, event->getLocationInformation().getFileName()); } apache-log4cxx-0.12.1/src/main/cpp/stringtokenizer.cpp000644 001750 001750 00000003421 14120250670 023475 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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; StringTokenizer::StringTokenizer(const LogString& str, const LogString& delim1) : src(str), delim(delim1), pos(0) { } StringTokenizer::~StringTokenizer() { } bool StringTokenizer::hasMoreTokens() const { return (pos != LogString::npos && src.find_first_not_of(delim, pos) != LogString::npos); } LogString StringTokenizer::nextToken() { if (pos != LogString::npos) { size_t nextPos = src.find_first_not_of(delim, pos); if (nextPos != LogString::npos) { pos = src.find_first_of(delim, nextPos); if (pos == LogString::npos) { return src.substr(nextPos); } return src.substr(nextPos, pos - nextPos); } } throw NoSuchElementException(); #if LOG4CXX_RETURN_AFTER_THROW return LogString(); #endif } apache-log4cxx-0.12.1/src/main/cpp/formattinginfo.cpp000644 001750 001750 00000004213 14120250670 023262 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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; 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) : minLength(minLength1), maxLength(maxLength1), leftAlign(leftAlign1) { } /** * Gets default instance. * @return default instance. */ FormattingInfoPtr FormattingInfo::getDefault() { static FormattingInfoPtr def(new FormattingInfo(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 > maxLength) { buffer.erase(buffer.begin() + fieldStart, buffer.begin() + fieldStart + (rawLength - maxLength)); } else if (rawLength < minLength) { if (leftAlign) { buffer.append(minLength - rawLength, (logchar) 0x20 /* ' ' */); } else { buffer.insert(fieldStart, minLength - rawLength, 0x20 /* ' ' */); } } } apache-log4cxx-0.12.1/src/main/cpp/rollingpolicy.cpp000644 001750 001750 00000001635 14120250670 023127 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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-0.12.1/src/main/cpp/ttcclayout.cpp000644 001750 001750 00000004471 14120250670 022435 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(TTCCLayout) TTCCLayout::TTCCLayout() : DateLayout(LOG4CXX_STR("RELATIVE")), threadPrinting(true), categoryPrefixing(true), contextPrinting(true), filePrinting(false) { Pool pool; activateOptions(pool); } TTCCLayout::TTCCLayout(const LogString& dateFormatType) : DateLayout(dateFormatType), threadPrinting(true), categoryPrefixing(true), contextPrinting(true), filePrinting(false) { Pool pool; activateOptions(pool); } void TTCCLayout::format(LogString& output, const spi::LoggingEventPtr& event, Pool& p) const { formatDate(output, event, p); if (threadPrinting) { output.append(1, (logchar) 0x5B /* '[' */); output.append(event->getThreadName()); output.append(1, (logchar) 0x5D /* ']' */); output.append(1, (logchar) 0x20 /* ' ' */); } output.append(event->getLevel()->toString()); output.append(1, (logchar) 0x20 /* ' ' */); if (categoryPrefixing) { output.append(event->getLoggerName()); output.append(1, (logchar) 0x20 /* ' ' */); } if (contextPrinting && event->getNDC(output)) { output.append(1, (logchar) 0x20 /* ' ' */); } output.append(1, (logchar) 0x2D /* '-' */); output.append(1, (logchar) 0x20 /* ' ' */); output.append(event->getRenderedMessage()); output.append(LOG4CXX_EOL); } apache-log4cxx-0.12.1/src/main/cpp/mdc.cpp000644 001750 001750 00000012413 14120250670 021000 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/main/cpp/layout.cpp000644 001750 001750 00000002252 14120250670 021552 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-0.12.1/src/main/cpp/classnamepatternconverter.cpp000644 001750 001750 00000003713 14120250670 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. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new ClassNamePatternConverter(options)); return def; } return PatternConverterPtr( new ClassNamePatternConverter(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-0.12.1/src/main/cpp/methodlocationpatternconverter.cpp000644 001750 001750 00000003400 14120250670 026570 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new MethodLocationPatternConverter()); return def; } void MethodLocationPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */ ) const { append(toAppendTo, event->getLocationInformation().getMethodName()); } apache-log4cxx-0.12.1/src/main/cpp/configurator.cpp000644 001750 001750 00000002036 14120250670 022737 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/main/cpp/odbcappender.cpp000644 001750 001750 00000021225 14120250670 022664 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 #if LOG4CXX_HAVE_ODBC #if defined(WIN32) || defined(_WIN32) #include #endif #include #endif using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::db; using namespace log4cxx::spi; 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) ODBCAppender::ODBCAppender() : connection(0), env(0), bufferSize(1) { } ODBCAppender::~ODBCAppender() { finalize(); } 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 { AppenderSkeleton::setOption(option, value); } } void ODBCAppender::activateOptions(log4cxx::helpers::Pool&) { #if !LOG4CXX_HAVE_ODBC LogLog::error(LOG4CXX_STR("Can not activate ODBCAppender unless compiled with ODBC support.")); #endif } void ODBCAppender::append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) { #if LOG4CXX_HAVE_ODBC buffer.push_back(event); if (buffer.size() >= bufferSize) { flushBuffer(p); } #endif } LogString ODBCAppender::getLogStatement(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) const { LogString sbuf; getLayout()->format(sbuf, event, p); return sbuf; } void ODBCAppender::execute(const LogString& sql, log4cxx::helpers::Pool& p) { #if LOG4CXX_HAVE_ODBC SQLRETURN ret; SQLHDBC con = SQL_NULL_HDBC; SQLHSTMT stmt = SQL_NULL_HSTMT; try { con = getConnection(p); ret = SQLAllocHandle( SQL_HANDLE_STMT, con, &stmt); if (ret < 0) { throw SQLException( SQL_HANDLE_DBC, con, "Failed to allocate sql handle.", p); } SQLWCHAR* wsql; encode(&wsql, sql, p); ret = SQLExecDirectW(stmt, wsql, SQL_NTS); if (ret < 0) { throw SQLException(SQL_HANDLE_STMT, stmt, "Failed to execute sql statement.", p); } } catch (SQLException&) { if (stmt != SQL_NULL_HSTMT) { SQLFreeHandle(SQL_HANDLE_STMT, stmt); } throw; } SQLFreeHandle(SQL_HANDLE_STMT, stmt); closeConnection(con); #else throw SQLException("log4cxx build without ODBC support"); #endif } /* 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 (env == SQL_NULL_HENV) { ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); if (ret < 0) { SQLException ex(SQL_HANDLE_ENV, env, "Failed to allocate SQL handle.", p); env = SQL_NULL_HENV; throw ex; } ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER); if (ret < 0) { SQLException ex(SQL_HANDLE_ENV, env, "Failed to set odbc version.", p); SQLFreeHandle(SQL_HANDLE_ENV, env); env = SQL_NULL_HENV; throw ex; } } if (connection == SQL_NULL_HDBC) { ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &connection); if (ret < 0) { SQLException ex(SQL_HANDLE_DBC, connection, "Failed to allocate sql handle.", p); connection = SQL_NULL_HDBC; throw ex; } SQLWCHAR* wURL, *wUser, *wPwd; encode(&wURL, databaseURL, p); encode(&wUser, databaseUser, p); encode(&wPwd, databasePassword, p); ret = SQLConnectW( connection, wURL, SQL_NTS, wUser, SQL_NTS, wPwd, SQL_NTS); if (ret < 0) { SQLException ex(SQL_HANDLE_DBC, connection, "Failed to connect to database.", p); SQLFreeHandle(SQL_HANDLE_DBC, connection); connection = SQL_NULL_HDBC; throw ex; } } return connection; #else return 0; #endif } void ODBCAppender::close() { if (closed) { return; } Pool p; try { flushBuffer(p); } catch (SQLException& e) { errorHandler->error(LOG4CXX_STR("Error closing connection"), e, ErrorCode::GENERIC_FAILURE); } #if LOG4CXX_HAVE_ODBC if (connection != SQL_NULL_HDBC) { SQLDisconnect(connection); SQLFreeHandle(SQL_HANDLE_DBC, connection); } if (env != SQL_NULL_HENV) { SQLFreeHandle(SQL_HANDLE_ENV, env); } #endif this->closed = true; } void ODBCAppender::flushBuffer(Pool& p) { std::list::iterator i; for (i = buffer.begin(); i != buffer.end(); i++) { try { const LoggingEventPtr& logEvent = *i; LogString sql = getLogStatement(logEvent, p); execute(sql, p); } catch (SQLException& e) { errorHandler->error(LOG4CXX_STR("Failed to execute sql"), e, ErrorCode::FLUSH_FAILURE); } } // clear the buffer of reported events buffer.clear(); } void ODBCAppender::setSql(const LogString& s) { sqlStatement = s; if (getLayout() == 0) { this->setLayout(PatternLayoutPtr(new PatternLayout(s))); } else { PatternLayoutPtr patternLayout; LayoutPtr asLayout = this->getLayout(); patternLayout = log4cxx::cast(asLayout); if (patternLayout != 0) { patternLayout->setConversionPattern(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; } apache-log4cxx-0.12.1/src/main/cpp/bytebuffer.cpp000644 001750 001750 00000003151 14120250670 022371 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; ByteBuffer::ByteBuffer(char* data1, size_t capacity) : base(data1), pos(0), lim(capacity), cap(capacity) { } ByteBuffer::~ByteBuffer() { } void ByteBuffer::clear() { lim = cap; pos = 0; } void ByteBuffer::flip() { lim = pos; pos = 0; } void ByteBuffer::position(size_t newPosition) { if (newPosition < lim) { pos = newPosition; } else { pos = lim; } } void ByteBuffer::limit(size_t newLimit) { if (newLimit > cap) { throw IllegalArgumentException(LOG4CXX_STR("newLimit")); } lim = newLimit; } bool ByteBuffer::put(char byte) { if (pos < lim) { base[pos++] = byte; return true; } return false; } apache-log4cxx-0.12.1/src/main/cpp/fallbackerrorhandler.cpp000644 001750 001750 00000006363 14120250670 024413 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; using namespace log4cxx::varia; IMPLEMENT_LOG4CXX_OBJECT(FallbackErrorHandler) FallbackErrorHandler::FallbackErrorHandler() : backup(), primary(), loggers() { } void FallbackErrorHandler::setLogger(const LoggerPtr& logger) { LogLog::debug(((LogString) LOG4CXX_STR("FB: Adding logger [")) + logger->getName() + LOG4CXX_STR("].")); 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 = primary.lock(); AppenderPtr backupLocked = backup.lock(); if ( !primaryLocked || !backupLocked ) { return; } for (LoggerPtr l : 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("].")); this->primary = primary1; } void FallbackErrorHandler::setBackupAppender(const AppenderPtr& backup1) { LogLog::debug(((LogString) LOG4CXX_STR("FB: Setting backup appender to [")) + backup1->getName() + LOG4CXX_STR("].")); this->backup = backup1; } void FallbackErrorHandler::activateOptions(Pool&) { } void FallbackErrorHandler::setOption(const LogString&, const LogString&) { } apache-log4cxx-0.12.1/src/main/cpp/rootlogger.cpp000644 001750 001750 00000002640 14120250670 022421 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 level; } void RootLogger::setLevel(const LevelPtr level1) { if (level1 == 0) { LogLog::error(LOG4CXX_STR("You have tried to set a null level to root.")); } else { this->level = level1; } } apache-log4cxx-0.12.1/src/main/cpp/writerappender.cpp000644 001750 001750 00000014274 14120250670 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 using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(WriterAppender) WriterAppender::WriterAppender() { immediateFlush = true; } WriterAppender::WriterAppender(const LayoutPtr& layout1, log4cxx::helpers::WriterPtr& writer1) : AppenderSkeleton(layout1), writer(writer1) { Pool p; immediateFlush = true; activateOptions(p); } WriterAppender::WriterAppender(const LayoutPtr& layout1) : AppenderSkeleton(layout1) { immediateFlush = true; } WriterAppender::~WriterAppender() { finalize(); } void WriterAppender::activateOptions(Pool& p) { int errors = 0; if (layout == 0) { errorHandler->error( ((LogString) LOG4CXX_STR("No layout set for the appender named [")) + name + LOG4CXX_STR("].")); errors++; } if (writer == 0) { errorHandler->error( ((LogString) LOG4CXX_STR("No writer set for the appender named [")) + 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 (closed) { if (!warnedClosed) { LogLog::warn(LOG4CXX_STR("Not allowed to write to a closed appender.")); warnedClosed = true; } return false; } if (writer == 0) { if (warnedNoWriter) { errorHandler->error( LogString(LOG4CXX_STR("No output stream or file set for the appender named [")) + name + LOG4CXX_STR("].")); warnedNoWriter = true; } return false; } if (layout == 0) { errorHandler->error( LogString(LOG4CXX_STR("No layout set for the appender named [")) + 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::unique_lock lock(mutex); if (closed) { return; } closed = true; closeWriter(); } /** * Close the underlying {@link java.io.Writer}. * */ void WriterAppender::closeWriter() { if (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(pool); writer->close(pool); writer = 0; } catch (IOException& e) { LogLog::error(LogString(LOG4CXX_STR("Could not close writer for WriterAppender named ")) + 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 encoding; } void WriterAppender::setEncoding(const LogString& enc) { encoding = enc; } void WriterAppender::subAppend(const spi::LoggingEventPtr& event, Pool& p) { LogString msg; layout->format(msg, event, p); if (writer != NULL) { writer->write(msg, p); if (immediateFlush) { writer->flush(p); } } } void WriterAppender::writeFooter(Pool& p) { if (layout != NULL) { LogString foot; layout->appendFooter(foot, p); writer->write(foot, p); } } void WriterAppender::writeHeader(Pool& p) { if (layout != NULL) { LogString header; layout->appendHeader(header, p); writer->write(header, p); } } void WriterAppender::setWriter(const WriterPtr& newWriter) { std::unique_lock lock(mutex); setWriterInternal(newWriter); } void WriterAppender::setWriterInternal(const WriterPtr& newWriter) { 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) { immediateFlush = value; } apache-log4cxx-0.12.1/src/main/cpp/datelayout.cpp000644 001750 001750 00000006753 14120250670 022422 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; DateLayout::DateLayout(const LogString& dateFormatOption1) : timeZoneID(), dateFormatOption(dateFormatOption1), dateFormat(0) { } DateLayout::~DateLayout() { } void DateLayout::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("DATEFORMAT"), LOG4CXX_STR("dateformat"))) { dateFormatOption = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("TIMEZONE"), LOG4CXX_STR("timezone"))) { timeZoneID = value; } } void DateLayout::activateOptions(Pool&) { if (!dateFormatOption.empty()) { if (dateFormatOption.empty()) { dateFormat = 0; } else if (StringHelper::equalsIgnoreCase(dateFormatOption, LOG4CXX_STR("NULL"), LOG4CXX_STR("null"))) { dateFormat = 0; dateFormatOption = LOG4CXX_STR("NULL"); } else if (StringHelper::equalsIgnoreCase(dateFormatOption, LOG4CXX_STR("RELATIVE"), LOG4CXX_STR("relative"))) { dateFormat = DateFormatPtr(new RelativeTimeDateFormat()); dateFormatOption = LOG4CXX_STR("RELATIVE"); } else if (StringHelper::equalsIgnoreCase(dateFormatOption, LOG4CXX_STR("ABSOLUTE"), LOG4CXX_STR("absolute"))) { dateFormat = DateFormatPtr(new AbsoluteTimeDateFormat()); dateFormatOption = LOG4CXX_STR("ABSOLUTE"); } else if (StringHelper::equalsIgnoreCase(dateFormatOption, LOG4CXX_STR("DATE"), LOG4CXX_STR("date"))) { dateFormat = DateFormatPtr(new DateTimeDateFormat()); dateFormatOption = LOG4CXX_STR("DATE"); } else if (StringHelper::equalsIgnoreCase(dateFormatOption, LOG4CXX_STR("ISO8601"), LOG4CXX_STR("iso8601"))) { dateFormat = DateFormatPtr(new ISO8601DateFormat()); dateFormatOption = LOG4CXX_STR("iso8601"); } else { dateFormat = DateFormatPtr(new SimpleDateFormat(dateFormatOption)); } } if (dateFormat != NULL) { if (timeZoneID.empty()) { dateFormat->setTimeZone(TimeZone::getDefault()); } else { dateFormat->setTimeZone(TimeZone::getTimeZone(timeZoneID)); } } } void DateLayout::formatDate(LogString& s, const spi::LoggingEventPtr& event, Pool& p) const { if (dateFormat != 0) { dateFormat->format(s, event->getTimeStamp(), p); s.append(1, (logchar) 0x20 /* ' ' */); } } apache-log4cxx-0.12.1/src/main/cpp/file.cpp000644 001750 001750 00000012750 14120250670 021160 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; File::File() { } 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) : path(decodeLS(name1)) { } File::File(const char* name1) : path(decodeLS(name1)) { } #if LOG4CXX_WCHAR_T_API File::File(const std::wstring& name1) : path(decodeLS(name1)) { } File::File(const wchar_t* name1) : path(decodeLS(name1)) { } #endif #if LOG4CXX_UNICHAR_API File::File(const std::basic_string& name1) : path(decodeLS(name1)) { } File::File(const UniChar* name1) : path(decodeLS(name1)) { } #endif #if LOG4CXX_CFSTRING_API File::File(const CFStringRef& name1) : path(decodeLS(name1)) { } #endif File::File(const File& src) : path(src.path) { } File& File::operator=(const File& src) { if (this == &src) { return *this; } path.assign(src.path); return *this; } File::~File() { } LogString File::getPath() const { return path; } File& File::setPath(const LogString& newName) { path.assign(newName); return *this; } LogString File::getName() const { const logchar slashes[] = { 0x2F, 0x5C, 0 }; size_t lastSlash = path.find_last_of(slashes); if (lastSlash != LogString::npos) { return path.substr(lastSlash + 1); } return 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(path, p); } else { retval = Transcoder::encode(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 = path.rfind(LOG4CXX_STR('/')); LogString::size_type backPos = 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(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; } apache-log4cxx-0.12.1/src/main/cpp/simplelayout.cpp000644 001750 001750 00000002432 14120250670 022764 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/main/cpp/socketappender.cpp000644 001750 001750 00000006132 14120250670 023245 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include #include #include #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; IMPLEMENT_LOG4CXX_OBJECT(SocketAppender) // The default port number of remote logging server (4560) int SocketAppender::DEFAULT_PORT = 4560; // The default reconnection delay (30000 milliseconds or 30 seconds). int SocketAppender::DEFAULT_RECONNECTION_DELAY = 30000; SocketAppender::SocketAppender() : SocketAppenderSkeleton(DEFAULT_PORT, DEFAULT_RECONNECTION_DELAY) { } SocketAppender::SocketAppender(InetAddressPtr& address1, int port1) : SocketAppenderSkeleton(address1, port1, DEFAULT_RECONNECTION_DELAY) { Pool p; activateOptions(p); } SocketAppender::SocketAppender(const LogString& host, int port1) : SocketAppenderSkeleton(host, port1, DEFAULT_RECONNECTION_DELAY) { Pool p; activateOptions(p); } SocketAppender::~SocketAppender() { finalize(); } int SocketAppender::getDefaultDelay() const { return DEFAULT_RECONNECTION_DELAY; } int SocketAppender::getDefaultPort() const { return DEFAULT_PORT; } void SocketAppender::setSocket(log4cxx::helpers::SocketPtr& socket, Pool& p) { std::unique_lock lock(mutex); SocketOutputStreamPtr sock = SocketOutputStreamPtr(new SocketOutputStream(socket)); oos = ObjectOutputStreamPtr(new ObjectOutputStream(sock, p)); } void SocketAppender::cleanUp(Pool& p) { if (oos == 0) { return; } try { oos->close(p); oos = 0; } catch (std::exception&) {} } void SocketAppender::append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) { if (oos == 0) { return; } LogString ndcVal; event->getNDC(ndcVal); event->getThreadName(); event->getMDCCopy(); try { event->write(*oos, p); oos->reset(p); } catch (std::exception& e) { oos = 0; LogLog::warn(LOG4CXX_STR("Detected problem with connection: "), e); if (getReconnectionDelay() > 0) { fireConnector(); } } } apache-log4cxx-0.12.1/src/main/cpp/linelocationpatternconverter.cpp000644 001750 001750 00000003460 14120250670 026245 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #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(new LineLocationPatternConverter()); return instance; } void LineLocationPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { StringHelper::toString( event->getLocationInformation().getLineNumber(), p, toAppendTo); } apache-log4cxx-0.12.1/src/main/cpp/classregistration.cpp000644 001750 001750 00000002072 14120250670 023775 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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-0.12.1/src/main/cpp/inputstreamreader.cpp000644 001750 001750 00000004335 14120250670 023777 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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) InputStreamReader::InputStreamReader(const InputStreamPtr& in1) : in(in1), dec(CharsetDecoder::getDefaultDecoder()) { if (in1 == 0) { throw NullPointerException(LOG4CXX_STR("in parameter may not be null.")); } } InputStreamReader::InputStreamReader(const InputStreamPtr& in1, const CharsetDecoderPtr& dec1) : in(in1), dec(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& ) { in->close(); } LogString InputStreamReader::read(Pool& p) { const size_t BUFSIZE = 4096; ByteBuffer buf(p.pstralloc(BUFSIZE), BUFSIZE); LogString output; // read whole file while (in->read(buf) >= 0) { buf.flip(); log4cxx_status_t stat = 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-0.12.1/src/main/cpp/locale.cpp000644 001750 001750 00000002657 14120250670 021505 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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; Locale::Locale(const LogString& language1) : language(language1) { } Locale::Locale(const LogString& language1, const LogString& country1) : language(language1), country(country1) { } Locale::Locale(const LogString& language1, const LogString& country1, const LogString& variant1) : language(language1), country(country1), variant(variant1) { } const LogString& Locale::getLanguage() const { return language; } const LogString& Locale::getCountry() const { return country; } const LogString& Locale::getVariant() const { return variant; } apache-log4cxx-0.12.1/src/main/cpp/domconfigurator.cpp000644 001750 001750 00000071263 14122472113 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 #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; #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" DOMConfigurator::DOMConfigurator() : props(), repository() { } /** 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 { log4cxx::net::SMTPAppenderPtr smtpa = log4cxx::cast(appender); if (smtpa != NULL) { log4cxx::spi::TriggeringEventEvaluatorPtr evaluator = log4cxx::cast(policyPtr); 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 = repository->getLogger(loggerName, loggerFactory); eh->setLogger(logger); } else if (tagName == ROOT_REF) { LoggerPtr root = 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 = repository->getLogger(loggerName, 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); loggerFactory = log4cxx::cast(obj); PropertySetter propSetter(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 = 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); } void DOMConfigurator::doConfigure(const File& filename, spi::LoggerRepositoryPtr repository1) { repository1->setConfigured(true); this->repository = repository1; LogString msg(LOG4CXX_STR("DOMConfigurator configuring file ")); msg.append(filename.getPath()); msg.append(LOG4CXX_STR("...")); LogLog::debug(msg); loggerFactory = LoggerFactoryPtr(new DefaultLoggerFactory()); Pool p; apr_file_t* fd; log4cxx_status_t rv = filename.open(&fd, APR_READ, APR_OS_DEFAULT, p); if (rv != APR_SUCCESS) { LogString msg2(LOG4CXX_STR("Could not open file [")); msg2.append(filename.getPath()); msg2.append(LOG4CXX_STR("].")); LogLog::error(msg2); } else { apr_xml_parser* parser = NULL; apr_xml_doc* doc = NULL; 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); } else { AppenderMap appenders; CharsetDecoderPtr utf8Decoder(CharsetDecoder::getUTF8Decoder()); parse(p, utf8Decoder, doc->root, doc, appenders); } } } void DOMConfigurator::configure(const std::string& filename) { File file(filename); DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #if LOG4CXX_WCHAR_T_API void DOMConfigurator::configure(const std::wstring& filename) { File file(filename); DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #endif #if LOG4CXX_UNICHAR_API void DOMConfigurator::configure(const std::basic_string& filename) { File file(filename); DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #endif #if LOG4CXX_CFSTRING_API void DOMConfigurator::configure(const CFStringRef& filename) { File file(filename); DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #endif void DOMConfigurator::configureAndWatch(const std::string& filename) { configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #if LOG4CXX_WCHAR_T_API void DOMConfigurator::configureAndWatch(const std::wstring& filename) { configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #endif #if LOG4CXX_UNICHAR_API void DOMConfigurator::configureAndWatch(const std::basic_string& filename) { configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #endif #if LOG4CXX_CFSTRING_API void DOMConfigurator::configureAndWatch(const CFStringRef& filename) { configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #endif void DOMConfigurator::configureAndWatch(const std::string& filename, long delay) { File file(filename); #if APR_HAS_THREADS if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(delay); xdog->start(); #else DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); #endif } #if LOG4CXX_WCHAR_T_API void DOMConfigurator::configureAndWatch(const std::wstring& filename, long delay) { File file(filename); #if APR_HAS_THREADS if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(delay); xdog->start(); #else DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); #endif } #endif #if LOG4CXX_UNICHAR_API void DOMConfigurator::configureAndWatch(const std::basic_string& filename, long delay) { File file(filename); #if APR_HAS_THREADS if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(delay); xdog->start(); #else DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); #endif } #endif #if LOG4CXX_CFSTRING_API void DOMConfigurator::configureAndWatch(const CFStringRef& filename, long delay) { File file(filename); #if APR_HAS_THREADS if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(delay); xdog->start(); #else 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(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) { 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) { 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) { repository->setThreshold(thresholdStr); } LogString strstrValue = subst(getAttribute(utf8Decoder, element, STRINGSTREAM_ATTR)); LogLog::debug(LOG4CXX_STR("Stringstream =\"") + strstrValue + LOG4CXX_STR("\".")); if (!strstrValue.empty() && strstrValue != NuLL) { MessageBufferUseStaticStream(); } 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, 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, strlen(attr->value)); utf8Decoder->decode(buf, attrValue); } } return attrValue; } apache-log4cxx-0.12.1/src/main/cpp/basicconfigurator.cpp000644 001750 001750 00000003140 14120250670 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 using namespace log4cxx; void BasicConfigurator::configure() { LogManager::getLoggerRepository()->setConfigured(true); LoggerPtr root = Logger::getRootLogger(); static const LogString TTCC_CONVERSION_PATTERN(LOG4CXX_STR("%r [%t] %p %c %x - %m%n")); LayoutPtr layout(new PatternLayout(TTCC_CONVERSION_PATTERN)); AppenderPtr appender(new ConsoleAppender(layout)); root->addAppender(appender); } void BasicConfigurator::configure(const AppenderPtr& appender) { LoggerPtr root = Logger::getRootLogger(); root->addAppender(appender); } void BasicConfigurator::resetConfiguration() { LogManager::resetConfiguration(); } apache-log4cxx-0.12.1/src/main/cpp/date.cpp000644 001750 001750 00000002602 14120250670 021151 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #ifndef INT64_C #define INT64_C(x) x ## LL #endif using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(Date) Date::Date() : time(apr_time_now()) { } Date::Date(log4cxx_time_t t) : time(t) { } Date::~Date() { } log4cxx_time_t Date::getMicrosecondsPerDay() { return APR_INT64_C(86400000000); } log4cxx_time_t Date::getMicrosecondsPerSecond() { return APR_USEC_PER_SEC; } log4cxx_time_t Date::getNextSecond() const { return ((time / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC; } apache-log4cxx-0.12.1/src/main/resources/000755 001750 001750 00000000000 14122472745 020773 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/main/resources/MSG00001.bin000644 001750 001750 00000000244 14120250671 022462 0ustar00robertrobert000000 000000 Trace Debug Info Warn Error Fatal %1 apache-log4cxx-0.12.1/src/main/resources/log4cxx.rc000644 001750 001750 00000007761 14120250671 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. // // // 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-0.12.1/src/main/resources/CMakeLists.txt000644 001750 001750 00000000133 14120250671 023516 0ustar00robertrobert000000 000000 # Configure if(WIN32) target_sources(log4cxx PRIVATE ../resources/log4cxx.rc ) endif() apache-log4cxx-0.12.1/src/main/resources/EventLogCategories.mc000644 001750 001750 00000002032 14120250671 025030 0ustar00robertrobert000000 000000 ; ; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, ; software distributed under the License is distributed on an ; "AS IS" BASIS, WITHOUT 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-0.12.1/src/CMakeLists.txt000644 001750 001750 00000001726 14120250670 020570 0ustar00robertrobert000000 000000 cmake_policy(SET CMP0079 NEW) 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::EXPAT ${APR_LIBRARIES} ${APR_SYSTEM_LIBS}) if(WIN32) # The ODBC appender is always enabled in the Windows configuration target_link_libraries(log4cxx PRIVATE odbc32.lib) option(LOG4CXX_INSTALL_PDB "Install .pdb files (if generated)" ON) else() if(${odbc_FOUND}) target_include_directories(log4cxx PRIVATE ${odbc_INCLUDE_DIRS}) target_link_directories( log4cxx PRIVATE ${odbc_LIBRARY_DIRS}) target_link_libraries( log4cxx PRIVATE ${odbc_LIBRARIES}) endif(${odbc_FOUND}) endif() if(BUILD_TESTING) add_subdirectory(test) add_subdirectory(examples/cpp) endif() add_subdirectory(site) apache-log4cxx-0.12.1/src/examples/000755 001750 001750 00000000000 14122472745 017653 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/examples/cpp/000755 001750 001750 00000000000 14122472745 020435 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/examples/cpp/stream.cpp000644 001750 001750 00000003637 14120250670 022432 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/examples/cpp/custom-appender.xml000644 001750 001750 00000001344 14120250670 024254 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/examples/cpp/CMakeLists.txt000644 001750 001750 00000002440 14120250670 023162 0ustar00robertrobert000000 000000 set(ALL_LOG4CXX_EXAMPLES console delayedloop stream trivial custom-appender) foreach(exampleName IN LISTS ALL_LOG4CXX_EXAMPLES) add_executable(${exampleName} ${exampleName}.cpp) target_compile_definitions(${exampleName} PRIVATE ${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} ${XMLLIB_LIBRARIES} ${APR_LIBRARIES} ${APR_SYSTEM_LIBS}) endforeach() configure_file( custom-appender.xml ${CMAKE_CURRENT_BINARY_DIR}/custom-appender.xml COPYONLY ) # Custom handling for format string example, since it utilizes libfmt find_package(fmt QUIET) 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} ${XMLLIB_LIBRARIES} ${APR_LIBRARIES} ${APR_SYSTEM_LIBS} fmt::fmt) endif(${fmt_FOUND}) apache-log4cxx-0.12.1/src/examples/cpp/trivial.cpp000644 001750 001750 00000003336 14120250670 022605 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/examples/cpp/console.cpp000644 001750 001750 00000007715 14120250670 022602 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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-0.12.1/src/examples/cpp/custom-appender.cpp000644 001750 001750 00000004502 14120250670 024235 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(){} 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. } } }; 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-0.12.1/src/examples/cpp/format-string.cpp000644 001750 001750 00000003755 14120250670 023734 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } 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-0.12.1/src/examples/cpp/delayedloop.cpp000644 001750 001750 00000006562 14120250670 023440 0ustar00robertrobert000000 000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** 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-0.12.1/src/site/000755 001750 001750 00000000000 14122472745 017001 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/site/markdown/000755 001750 001750 00000000000 14122472745 020623 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/site/markdown/3-development.md000644 001750 001750 00000002107 14120250671 023615 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 apache-log4cxx-0.12.1/src/site/markdown/download.md.in000644 001750 001750 00000010151 14120250671 023345 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-0.12.1/src/site/markdown/change-report-gh.md000644 001750 001750 00000300442 14122472651 024276 0ustar00robertrobert000000 000000 Changelog {#changelog} === # Release History | Version | Date | Description | | -------------------------------------------------------------------------------------- | ---------- | -------------------- | | [0.12.1](#0.12.1) | 2021-09-21 | Bugfix for 0.12.0 | | [0.12.0](#0.12.0) | 2021-05-01 | First release to require C++11. Updates for smart pointers. Standardization on CMake for building. | | [0.11.0](#0.11.0) | 2020-08-09 | Maintenance release. | | [0.10.0](#0.10.0) | 2008-04-03 | First Apache release | | [0.9.7](#0.9.7) | 2004-05-10 | | | [0.9.6](#0.9.6) | 2004-04-11 | | | [0.9.5](#0.9.5) | 2004-02-04 | | | [0.9.4](#0.9.4) | 2003-10-25 | | | [0.9.3](#0.9.3) | 2003-09-19 | | | [0.9.2](#0.9.2) | 2003-08-10 | | | [0.9.1](#0.9.1) | 2003-08-06 | | | [0.9.0](#0.9.0) | 2003-08-06 | | | [0.1.1](#0.1.1) | 2003-07-09 | | | [0.1.0](#0.1.0) | 2003-07-08 | | | [0.0.1](#0.0.1) | 2003-05-31 | | ## Release 0.12.1 - 2021-09-21 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 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 | | | | | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -- | | 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/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 | | | | | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -- | | 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 | | | | | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | -- | | 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 | | | | | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | -- | | 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 | | | | | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -- | | 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 | | | | | ------------------------------------------------------------------- | --------------------------------------------------------- | -- | | 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 | | | | | ------------------------------------------------------------------- | ------------------------------------------------------------------------------- | -- | | 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 | | | | | ------------------------------------------------------------------- | ----------------------------------------------------------------------------- | -- | | 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 | | | | | ------------------------------------------------------------------- | ------------------------------------------------------------ | -- | | 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 | | | | | ---------------------------------------------------------------- | ---------------------------------------------------------------------- | -- | | 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 | | | | | ---------------------------------------------------------------- | ------------------------------------------------------------------- | -- | | 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 | | | | | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -- | | 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 | | | | | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -- | | 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-0.12.1/src/site/markdown/extending.md000644 001750 001750 00000010760 14122472113 023123 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-0.12.1/src/site/markdown/configuration-samples.md000644 001750 001750 00000020104 14122472113 025440 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! ~~~ # 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-0.12.1/src/site/markdown/community/000755 001750 001750 00000000000 14122472745 022647 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/site/markdown/community/issue-tracking.md000644 001750 001750 00000004367 14120250671 026121 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. # 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 *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-0.12.1/src/site/markdown/community/mailing-lists.md000644 001750 001750 00000013441 14120250671 025736 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-0.12.1/src/site/markdown/license.md000644 001750 001750 00000030221 14120250671 022553 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-0.12.1/src/site/markdown/2-get.md000644 001750 001750 00000001675 14120250671 022062 0ustar00robertrobert000000 000000 Get {#get} === * @subpage download * @subpage changelog * @subpage license apache-log4cxx-0.12.1/src/site/markdown/usage.md000644 001750 001750 00000104373 14122472113 022246 0ustar00robertrobert000000 000000 Usage {#usage} === [TOC] # Loggers {#loggers} 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. ## Hierarchy {#hierarchy} 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: **Named 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** 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** 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" log4cxx::LoggerPtr 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()); log4cxx::LoggerPtr 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} log4cxx::LoggerPtr x = log4cxx::Logger::getLogger("wombat"); log4cxx::LoggerPtr 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 and Layouts {#appenders-and-layouts} 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*. Currently, appenders exist for the [console](@ref log4cxx.ConsoleAppender), [files](@ref log4cxx.FileAppender), GUI components, [remote socket](@ref log4cxx.net.SocketAppender) servers, [NT Event Loggers](@ref log4cxx.nt.NTEventLogAppender), and remote UNIX [Syslog](@ref log4cxx.net.SyslogAppender) daemons. It is also possible to log [asynchronously](@ref log4cxx.AsyncAppender). More than one appender can be attached to a logger. The [addAppender](@ref log4cxx.Logger.addAppender) method adds an appender to a given logger. *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. **Appender Additivity** 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. 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*. | 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. # Configuration {#configuration} Inserting log requests into the application code 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. 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. Let us give a taste of how this is done with the help of an imaginary application *MyApp* that uses log4cxx. ~~~{.cpp} #include "com/foo/bar.h" using namespace com::foo; // include log4cxx header files. #include "log4cxx/logger.h" #include "log4cxx/basicconfigurator.h" #include "log4cxx/helpers/exception.h" using namespace log4cxx; using namespace log4cxx::helpers; LoggerPtr logger(Logger::getLogger("MyApp")); int main(int argc, char **argv) { int result = EXIT_SUCCESS; try { // Set up a simple configuration that logs on the console. BasicConfigurator::configure(); LOG4CXX_INFO(logger, "Entering application.") Bar bar; bar.doIt(); LOG4CXX_INFO(logger, "Exiting application.") } catch(Exception&) { result = EXIT_FAILURE; } return result; } ~~~ *MyApp* begins by including log4cxx headers. It then defines a static logger variable with the name *MyApp* which happens to be the fully qualified name of the class. *MyApp* uses the *Bar* class defined in header file *com/foo/bar.h*. ~~~{.cpp} // file com/foo/bar.h #include "log4cxx/logger.h" namespace com { namespace foo { class Bar { static log4cxx::LoggerPtr logger; public: void doIt(); } } } ~~~ ~~~{.cpp} // file bar.cpp #include "com/foo/bar.h" using namespace com::foo; using namespace log4cxx; LoggerPtr Bar::logger(Logger::getLogger("com.foo.bar")); void Bar::doIt() { LOG4CXX_DEBUG(logger, "Did it again!") } ~~~ 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 `%%-4r [%%t] %%-5p %%c %%x - %%m%%n`. Note that by default, the root logger is assigned to *Level::getDebug()*. The output of MyApp is: ~~~ 0 [12345] INFO MyApp - Entering application. 36 [12345] DEBUG com.foo.Bar - Did it again! 51 [12345] INFO MyApp - Exiting application. ~~~ The previous example always outputs the same log information. Fortunately, it is easy to modify *MyApp* so that the log output can be controlled at run-time. Here is a slightly modified version. ~~~{.cpp} // file MyApp2.cpp #include "com/foo/bar.h" using namespace com::foo; // include log4cxx header files. #include "log4cxx/logger.h" #include "log4cxx/basicconfigurator.h" #include "log4cxx/propertyconfigurator.h" #include "log4cxx/helpers/exception.h" using namespace log4cxx; using namespace log4cxx::helpers; // Define a static logger variable so that it references the // Logger instance named "MyApp". LoggerPtr logger(Logger::getLogger("MyApp")); int main(int argc, char **argv) { int result = EXIT_SUCCESS; try { if (argc > 1) { // BasicConfigurator replaced with PropertyConfigurator. PropertyConfigurator::configure(argv[1]); } else { BasicConfigurator::configure(); } LOG4CXX_INFO(logger, "Entering application.") Bar bar bar.doIt(); LOG4CXX_INFO(logger, "Exiting application.") } catch(Exception&) { result = EXIT_FAILURE; } return result; } ~~~ This version of *MyApp* instructs *PropertyConfigurator* to parse a configuration file and set up logging accordingly. Here is a sample configuration file that results in exactly same output as the previous *BasicConfigurator* 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=%-4r [%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. ~~~ 2000-09-07 14:07:41,508 [12345] INFO MyApp - Entering application. 2000-09-07 14:07:41,529 [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. ~~~ 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 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 ~~~ Calling the enhanced MyApp with the this configuration file will output the following on the console. ~~~ INFO [12345] (MyApp2.cpp:31) - Entering application. DEBUG [12345] (Bar.h:16) - Doing it again! INFO [12345] (MyApp2.cpp:34) - 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 Procedure {#default-initialization-procedure} The log4cxx library does not make any assumptions about its environment. In particular, there are no default log4cxx appenders. Under certain well-defined circumstances however, the static inializer of the *Logger* class will attempt to automatically configure log4cxx. The exact default initialization algorithm is defined as follows: 1. Set the configurationOptionStr string variable to the value of the **LOG4CXX\_CONFIGURATION** environment variable if set, otherwise the value of the **log4j.configuration** environment variable if set, otherwise the first of the following file names which exist in the current working directory, "log4cxx.xml", "log4cxx.properties", "log4j.xml" and "log4j.properties". If configurationOptionStr has not been set, then disable logging. 2. 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. # 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. # Performance {#performance} 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. The user should be aware of the following performance issues. 1. **Logging performance when logging is turned off.** When logging 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. The LOG4CXX\_DEBUG and similar macros suppress unnecessary expression evaluation if the request is not enabled. 2. **The performance of deciding whether to log or not to log when logging is turned on.** This is essentially the performance of walking the logger hierarchy. When logging is turned on, log4cxx still needs to compare the level of the log request with the level of the request logger. However, loggers may not have an assigned level; they can inherit them from the logger hierarchy. Thus, before inheriting a level, the logger may need to search its ancestors. 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. The cost of walking the hierarchy is typically 3 times slower than when logging is turned off entirely. 3. **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. # 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. # 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 src/examples/cpp/format-string.cpp file. # 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.Filter) for some more information, or view a [configuration sample](@ref configuration-samples). # 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. apache-log4cxx-0.12.1/src/site/markdown/index.md000644 001750 001750 00000004651 14122472113 022247 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]. Almost every large application includes its own logging or tracing API. Inserting log statements into code is a low-tech method for debugging it. It may also be the only way because debuggers are not always available or applicable. This is usually the case for multithreaded applications and distributed applications at large. Experience indicates that logging is an important component of the development cycle. It offers several advantages. It provides precise context about a run of the application. Once inserted into the code, the generation of logging output requires no human intervention. Moreover, log output can be saved in persistent medium to be studied at a later time. In addition to its use in the development cycle, a sufficiently rich logging package can also be viewed as an auditing tool. Logging does have its drawbacks. It can slow down an application. If too verbose, it can cause scrolling blindness. To alleviate these concerns, log4cxx is designed to be reliable, fast and extensible. Since logging is rarely the main focus of an application, the log4cxx API strives to be simple to understand and to use. [Apache log4j]:https://logging.apache.org/log4j/2.x/ [Apache Portable Runtime]:https://apr.apache.org/ [Apache License]:https://www.apache.org/licenses/ [Open Source Initiative]:https://opensource.org/ apache-log4cxx-0.12.1/src/site/markdown/filters/000755 001750 001750 00000000000 14122472745 022273 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/site/markdown/filters/MapFilter.md000644 001750 001750 00000010724 14120250671 024472 0ustar00robertrobert000000 000000 # MapFilter 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-0.12.1/src/site/markdown/faq.md000644 001750 001750 00000012266 14122472113 021710 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-0.12.1/src/site/markdown/qt-support.md000644 001750 001750 00000003157 14120250671 023277 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-0.12.1/src/site/markdown/0-community.md000644 001750 001750 00000001764 14120250671 023324 0ustar00robertrobert000000 000000 Community {#community} === See the following pages for community information: * @subpage issue-tracking * @subpage mailing-lists apache-log4cxx-0.12.1/src/site/markdown/development/000755 001750 001750 00000000000 14122472745 023145 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/site/markdown/development/build-vcpkg.md000644 001750 001750 00000002630 14120250671 025665 0ustar00robertrobert000000 000000 Building with vcpkg {#build-vcpkg} === # Building Apache log4cxx with vcpkg ## 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-0.12.1/src/site/markdown/development/build-cmake.md000644 001750 001750 00000012644 14120250671 025641 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. ~~~ $ 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 ~~~ * 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. | 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 ~~~ # 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-0.12.1/src/site/markdown/development/building.md000644 001750 001750 00000004166 14120250671 025261 0ustar00robertrobert000000 000000 Building {#building} === # Building Apache log4cxx The project supports different build tools on different platforms, have a look at the menu to find the platform you need. If your environment is not covered already, feel free to ask about it on one of the Mailing Lists or leave a bug in our Issue Tracker. In this case it would be very helpful of course if you could already provide some patches to support your environment or at least provide some technical details about the build tools, compiler etc. you use. ## 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. apache-log4cxx-0.12.1/src/site/markdown/development/source-repository.md000644 001750 001750 00000003042 14120250671 027171 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-0.12.1/src/site/markdown/development/dependencies.md000644 001750 001750 00000006017 14120250671 026107 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. 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-0.12.1/src/site/markdown/1-usage.md000644 001750 001750 00000002062 14122472113 022374 0ustar00robertrobert000000 000000 Usage {#usage-overview} === See the following pages for usage information: * @subpage usage * @subpage extending-log4cxx * @subpage faq * @subpage configuration-samples * @subpage qt-support apache-log4cxx-0.12.1/src/site/doxy/000755 001750 001750 00000000000 14122472745 017764 5ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/site/doxy/DoxygenLayout.xml000644 001750 001750 00000014265 14120250671 023317 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/site/doxy/license_notice_footer.txt000644 001750 001750 00000001420 14120250671 025051 0ustar00robertrobert000000 000000 apache-log4cxx-0.12.1/src/site/doxy/Doxyfile.in000644 001750 001750 00000326460 14120250671 022100 0ustar00robertrobert000000 000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 = # 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. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. For # instance, some of the names that are used will be different. The list of all # members will be omitted, etc. # The default value is: NO. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or # Python sources only. Doxygen will then generate output that is more tailored # for that language. For instance, namespaces will be presented as packages, # qualified scopes will look different, etc. # The default value is: NO. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources. Doxygen will then generate output that is tailored for Fortran. # The default value is: NO. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for VHDL. # The default value is: NO. OPTIMIZE_OUTPUT_VHDL = NO # 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 = 0 # 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 = ${LOG4CXX_SOURCE_DIR}/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 = ${LOG4CXX_SOURCE_DIR}/src/main/include \ ${LOG4CXX_SOURCE_DIR}/src/site/markdown \ ${CMAKE_BINARY_DIR}/src/site/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 = # 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 = # 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 = ${LOG4CXX_SOURCE_DIR}/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 = ${LOG4CXX_SOURCE_DIR}/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 # The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in # which the alphabetical index list will be split. # Minimum value: 1, maximum value: 20, default value: 5. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. COLS_IN_ALPHA_INDEX = 5 # 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 = ${LOG4CXX_SOURCE_DIR}/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 = ${LOG4CXX_SOURCE_DIR}/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 # , /