mirror of
https://github.com/gabime/spdlog.git
synced 2025-04-30 12:23:53 +00:00
Compare commits
No commits in common. "v1.x" and "v0.11.0" have entirely different histories.
@ -1,19 +0,0 @@
|
||||
---
|
||||
Language: Cpp
|
||||
BasedOnStyle: Google
|
||||
AccessModifierOffset: -4
|
||||
Standard: c++17
|
||||
IndentWidth: 4
|
||||
TabWidth: 4
|
||||
UseTab: Never
|
||||
ColumnLimit: 100
|
||||
AlignAfterOpenBracket: Align
|
||||
BinPackParameters: false
|
||||
AlignEscapedNewlines: Left
|
||||
AlwaysBreakTemplateDeclarations: Yes
|
||||
PackConstructorInitializers: Never
|
||||
BreakConstructorInitializersBeforeComma: false
|
||||
IndentPPDirectives: BeforeHash
|
||||
SortIncludes: Never
|
||||
...
|
||||
|
53
.clang-tidy
53
.clang-tidy
@ -1,53 +0,0 @@
|
||||
Checks: 'cppcoreguidelines-*,
|
||||
performance-*,
|
||||
modernize-*,
|
||||
google-*,
|
||||
misc-*
|
||||
cert-*,
|
||||
readability-*,
|
||||
clang-analyzer-*,
|
||||
-performance-unnecessary-value-param,
|
||||
-modernize-use-trailing-return-type,
|
||||
-google-runtime-references,
|
||||
-misc-non-private-member-variables-in-classes,
|
||||
-readability-braces-around-statements,
|
||||
-google-readability-braces-around-statements,
|
||||
-cppcoreguidelines-avoid-magic-numbers,
|
||||
-readability-magic-numbers,
|
||||
-readability-magic-numbers,
|
||||
-cppcoreguidelines-pro-type-vararg,
|
||||
-cppcoreguidelines-pro-bounds-pointer-arithmetic,
|
||||
-cppcoreguidelines-avoid-c-arrays,
|
||||
-modernize-avoid-c-arrays,
|
||||
-cppcoreguidelines-pro-bounds-array-to-pointer-decay,
|
||||
-readability-named-parameter,
|
||||
-cert-env33-c
|
||||
'
|
||||
|
||||
|
||||
WarningsAsErrors: ''
|
||||
HeaderFilterRegex: '*spdlog/[^f].*'
|
||||
FormatStyle: none
|
||||
|
||||
CheckOptions:
|
||||
- key: google-readability-braces-around-statements.ShortStatementLines
|
||||
value: '1'
|
||||
- key: google-readability-function-size.StatementThreshold
|
||||
value: '800'
|
||||
- key: google-readability-namespace-comments.ShortNamespaceLines
|
||||
value: '10'
|
||||
- key: google-readability-namespace-comments.SpacesBeforeComments
|
||||
value: '2'
|
||||
- key: modernize-loop-convert.MaxCopySize
|
||||
value: '16'
|
||||
- key: modernize-loop-convert.MinConfidence
|
||||
value: reasonable
|
||||
- key: modernize-loop-convert.NamingStyle
|
||||
value: CamelCase
|
||||
- key: modernize-pass-by-value.IncludeStyle
|
||||
value: llvm
|
||||
- key: modernize-replace-auto-ptr.IncludeStyle
|
||||
value: llvm
|
||||
- key: modernize-use-nullptr.NullMacros
|
||||
value: 'NULL'
|
||||
|
@ -1,6 +0,0 @@
|
||||
# clang-format
|
||||
1a0bfc7a89f2d58e22605a4dc7e18a9a555b65aa
|
||||
95c226e9c92928e20ccdac0d060e7241859e282b
|
||||
9d52261185b5f2c454c381d626ec5c84d7b195f4
|
||||
4b2a8219d5d1b40062d030441adde7d1fb0d4f84
|
||||
0a53eafe18d983c7c8ba4cadd02d0cc7f7308f28
|
1
.gitattributes
vendored
1
.gitattributes
vendored
@ -1 +0,0 @@
|
||||
* text=false
|
87
.github/workflows/linux.yml
vendored
87
.github/workflows/linux.yml
vendored
@ -1,87 +0,0 @@
|
||||
name: linux
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
# -----------------------------------------------------------------------
|
||||
# Linux build matrix
|
||||
# -----------------------------------------------------------------------
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
config:
|
||||
- { compiler: gcc, version: 7, build_type: Release, cppstd: 11 }
|
||||
- { compiler: gcc, version: 9, build_type: Release, cppstd: 17 }
|
||||
- { compiler: gcc, version: 11, build_type: Debug, cppstd: 20 }
|
||||
- { compiler: gcc, version: 12, build_type: Release, cppstd: 20 }
|
||||
- { compiler: gcc, version: 12, build_type: Debug, cppstd: 20, asan: ON }
|
||||
- { compiler: clang, version: 12, build_type: Debug, cppstd: 17 }
|
||||
- { compiler: clang, version: 15, build_type: Release, cppstd: 20, tsan: ON }
|
||||
container:
|
||||
image: ${{ matrix.config.compiler == 'clang' && 'teeks99/clang-ubuntu' || matrix.config.compiler }}:${{ matrix.config.version }}
|
||||
name: "${{ matrix.config.compiler}} ${{ matrix.config.version }} (C++${{ matrix.config.cppstd }} ${{ matrix.config.build_type }} ${{ matrix.config.asan == 'ON' && 'ASAN' || '' }}${{ matrix.config.tsan == 'ON' && 'TSAN' || '' }})"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y curl git pkg-config libsystemd-dev
|
||||
CMAKE_VERSION="3.24.2"
|
||||
curl -sSL https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.sh -o install-cmake.sh
|
||||
chmod +x install-cmake.sh
|
||||
./install-cmake.sh --prefix=/usr/local --skip-license
|
||||
- name: Setup Compiler
|
||||
if: matrix.config.compiler == 'clang'
|
||||
run: |
|
||||
scripts/ci_setup_clang.sh "${{ matrix.config.version }}"
|
||||
echo "CXXFLAGS=-stdlib=libc++" >> $GITHUB_ENV
|
||||
echo "CC=clang-${{ matrix.config.version }}" >> $GITHUB_ENV
|
||||
echo "CXX=clang++-${{ matrix.config.version }}" >> $GITHUB_ENV
|
||||
- name: Build
|
||||
run: |
|
||||
mkdir -p build && cd build
|
||||
cmake .. \
|
||||
-DCMAKE_BUILD_TYPE=${{ matrix.config.build_type }} \
|
||||
-DCMAKE_CXX_STANDARD=${{ matrix.config.cppstd }} \
|
||||
-DSPDLOG_BUILD_EXAMPLE=${{ matrix.config.examples || 'ON' }} \
|
||||
-DSPDLOG_BUILD_EXAMPLE_HO=${{ matrix.config.examples || 'ON' }} \
|
||||
-DSPDLOG_BUILD_WARNINGS=ON \
|
||||
-DSPDLOG_BUILD_BENCH=OFF \
|
||||
-DSPDLOG_BUILD_TESTS=ON \
|
||||
-DSPDLOG_BUILD_TESTS_HO=OFF \
|
||||
-DSPDLOG_SANITIZE_ADDRESS=${{ matrix.config.asan || 'OFF' }} \
|
||||
-DSPDLOG_SANITIZE_THREAD=${{ matrix.config.tsan || 'OFF' }}
|
||||
make -j 4
|
||||
ctest -j 4 --output-on-failure
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# OS X build matrix
|
||||
# -----------------------------------------------------------------------
|
||||
build_osx:
|
||||
runs-on: macOS-latest
|
||||
name: "OS X Clang (C++11, Release)"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build
|
||||
run: |
|
||||
mkdir -p build && cd build
|
||||
cmake .. \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_CXX_STANDARD=11 \
|
||||
-DSPDLOG_BUILD_EXAMPLE=ON \
|
||||
-DSPDLOG_BUILD_EXAMPLE_HO=ON \
|
||||
-DSPDLOG_BUILD_WARNINGS=ON \
|
||||
-DSPDLOG_BUILD_BENCH=OFF \
|
||||
-DSPDLOG_BUILD_TESTS=ON \
|
||||
-DSPDLOG_BUILD_TESTS_HO=OFF \
|
||||
-DSPDLOG_SANITIZE_ADDRESS=OFF
|
||||
make -j 4
|
||||
ctest -j 4 --output-on-failure
|
38
.github/workflows/macos.yml
vendored
38
.github/workflows/macos.yml
vendored
@ -1,38 +0,0 @@
|
||||
name: macos
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: macOS-latest
|
||||
name: "macOS Clang (C++11, Release)"
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
config:
|
||||
- USE_STD_FORMAT: 'ON'
|
||||
BUILD_EXAMPLE: 'OFF'
|
||||
- USE_STD_FORMAT: 'OFF'
|
||||
BUILD_EXAMPLE: 'ON'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build
|
||||
run: |
|
||||
mkdir -p build && cd build
|
||||
cmake .. \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_CXX_STANDARD=11 \
|
||||
-DSPDLOG_BUILD_EXAMPLE=${{ matrix.config.BUILD_EXAMPLE }} \
|
||||
-DSPDLOG_BUILD_EXAMPLE_HO=${{ matrix.config.BUILD_EXAMPLE }} \
|
||||
-DSPDLOG_BUILD_WARNINGS=ON \
|
||||
-DSPDLOG_BUILD_BENCH=OFF \
|
||||
-DSPDLOG_BUILD_TESTS=ON \
|
||||
-DSPDLOG_BUILD_TESTS_HO=OFF \
|
||||
-DSPDLOG_USE_STD_FORMAT=${{ matrix.config.USE_STD_FORMAT }} \
|
||||
-DSPDLOG_SANITIZE_ADDRESS=OFF
|
||||
make -j 4
|
||||
ctest -j 4 --output-on-failure
|
148
.github/workflows/windows.yml
vendored
148
.github/workflows/windows.yml
vendored
@ -1,148 +0,0 @@
|
||||
name: windows
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
config:
|
||||
- GENERATOR: "Visual Studio 17 2022"
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'ON'
|
||||
FATAL_ERRORS: 'ON'
|
||||
WCHAR: 'OFF'
|
||||
WCHAR_FILES: 'OFF'
|
||||
BUILD_EXAMPLE: 'OFF'
|
||||
USE_STD_FORMAT: 'ON'
|
||||
CXX_STANDARD: 20
|
||||
- GENERATOR: "Visual Studio 17 2022"
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'ON'
|
||||
FATAL_ERRORS: 'ON'
|
||||
WCHAR: 'ON'
|
||||
WCHAR_FILES: 'ON'
|
||||
BUILD_EXAMPLE: 'OFF'
|
||||
USE_STD_FORMAT: 'ON'
|
||||
CXX_STANDARD: 20
|
||||
- GENERATOR: "Visual Studio 17 2022"
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'ON'
|
||||
FATAL_ERRORS: 'ON'
|
||||
WCHAR: 'OFF'
|
||||
WCHAR_FILES: 'OFF'
|
||||
BUILD_EXAMPLE: 'ON'
|
||||
USE_STD_FORMAT: 'OFF'
|
||||
CXX_STANDARD: 17
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: CMake ${{ matrix.config.GENERATOR }} CXX=${{matrix.config.CXX_STANDARD}} WCHAR=${{matrix.config.WCHAR_FILES}} STD_FORMAT=${{matrix.config.USE_STD_FORMAT}}
|
||||
shell: pwsh
|
||||
run: |
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -G "${{ matrix.config.GENERATOR }}" -A x64 `
|
||||
-D CMAKE_BUILD_TYPE=${{ matrix.config.BUILD_TYPE }} `
|
||||
-D BUILD_SHARED_LIBS=${{ matrix.config.BUILD_SHARED }} `
|
||||
-D SPDLOG_WCHAR_SUPPORT=${{ matrix.config.WCHAR }} `
|
||||
-D SPDLOG_WCHAR_FILENAMES=${{ matrix.config.WCHAR_FILES }} `
|
||||
-D SPDLOG_BUILD_EXAMPLE=${{ matrix.config.BUILD_EXAMPLE }} `
|
||||
-D SPDLOG_BUILD_EXAMPLE_HO=${{ matrix.config.BUILD_EXAMPLE }} `
|
||||
-D SPDLOG_BUILD_TESTS=ON `
|
||||
-D SPDLOG_BUILD_TESTS_HO=OFF `
|
||||
-D SPDLOG_BUILD_WARNINGS=${{ matrix.config.FATAL_ERRORS }} `
|
||||
-D SPDLOG_USE_STD_FORMAT=${{ matrix.config.USE_STD_FORMAT }} `
|
||||
-D CMAKE_CXX_STANDARD=${{ matrix.config.CXX_STANDARD }} ..
|
||||
|
||||
- name: Build
|
||||
shell: pwsh
|
||||
run: |
|
||||
cd build
|
||||
cmake --build . --parallel --config ${{ matrix.config.BUILD_TYPE }}
|
||||
|
||||
- name: Run Tests
|
||||
shell: pwsh
|
||||
env:
|
||||
PATH: ${{ env.PATH }};${{ github.workspace }}\build\_deps\catch2-build\src\${{ matrix.config.BUILD_TYPE }};${{ github.workspace }}\build\${{ matrix.config.BUILD_TYPE }}
|
||||
run: |
|
||||
build\tests\${{ matrix.config.BUILD_TYPE }}\spdlog-utests.exe
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# MSVC 2019 build matrix
|
||||
# -----------------------------------------------------------------------
|
||||
build_2019:
|
||||
runs-on: windows-2019
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
config:
|
||||
- GENERATOR: "Visual Studio 16 2019"
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'ON'
|
||||
FATAL_ERRORS: 'ON'
|
||||
WCHAR: 'OFF'
|
||||
WCHAR_FILES: 'OFF'
|
||||
BUILD_EXAMPLE: 'ON'
|
||||
USE_STD_FORMAT: 'OFF'
|
||||
CXX_STANDARD: 17
|
||||
- GENERATOR: "Visual Studio 16 2019"
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'ON'
|
||||
FATAL_ERRORS: 'ON'
|
||||
WCHAR: 'OFF'
|
||||
WCHAR_FILES: 'OFF'
|
||||
BUILD_EXAMPLE: 'ON'
|
||||
USE_STD_FORMAT: 'OFF'
|
||||
CXX_STANDARD: 14
|
||||
- GENERATOR: "Visual Studio 16 2019"
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'ON'
|
||||
FATAL_ERRORS: 'ON'
|
||||
WCHAR: 'OFF'
|
||||
WCHAR_FILES: 'OFF'
|
||||
BUILD_EXAMPLE: 'ON'
|
||||
USE_STD_FORMAT: 'OFF'
|
||||
CXX_STANDARD: 11
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: CMake ${{ matrix.config.GENERATOR }} CXX=${{matrix.config.CXX_STANDARD}} WCHAR=${{matrix.config.WCHAR_FILES}} STD_FORMAT=${{matrix.config.USE_STD_FORMAT}}
|
||||
shell: pwsh
|
||||
run: |
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -G "${{ matrix.config.GENERATOR }}" -A x64 `
|
||||
-D CMAKE_BUILD_TYPE=${{ matrix.config.BUILD_TYPE }} `
|
||||
-D BUILD_SHARED_LIBS=${{ matrix.config.BUILD_SHARED }} `
|
||||
-D SPDLOG_WCHAR_SUPPORT=${{ matrix.config.WCHAR }} `
|
||||
-D SPDLOG_WCHAR_FILENAMES=${{ matrix.config.WCHAR_FILES }} `
|
||||
-D SPDLOG_BUILD_EXAMPLE=${{ matrix.config.BUILD_EXAMPLE }} `
|
||||
-D SPDLOG_BUILD_EXAMPLE_HO=${{ matrix.config.BUILD_EXAMPLE }} `
|
||||
-D SPDLOG_BUILD_TESTS=ON `
|
||||
-D SPDLOG_BUILD_TESTS_HO=OFF `
|
||||
-D SPDLOG_BUILD_WARNINGS=${{ matrix.config.FATAL_ERRORS }} `
|
||||
-D SPDLOG_USE_STD_FORMAT=${{ matrix.config.USE_STD_FORMAT }} `
|
||||
-D CMAKE_CXX_STANDARD=${{ matrix.config.CXX_STANDARD }} ..
|
||||
|
||||
- name: Build
|
||||
shell: pwsh
|
||||
run: |
|
||||
cd build
|
||||
cmake --build . --parallel --config ${{ matrix.config.BUILD_TYPE }}
|
||||
|
||||
- name: Run Tests
|
||||
shell: pwsh
|
||||
env:
|
||||
PATH: ${{ env.PATH }};${{ github.workspace }}\build\_deps\catch2-build\src\${{ matrix.config.BUILD_TYPE }};${{ github.workspace }}\build\${{ matrix.config.BUILD_TYPE }}
|
||||
run: |
|
||||
build\tests\${{ matrix.config.BUILD_TYPE }}\spdlog-utests.exe
|
36
.gitignore
vendored
36
.gitignore
vendored
@ -1,7 +1,4 @@
|
||||
# Auto generated files
|
||||
[Dd]ebug/
|
||||
[Rr]elease/
|
||||
build/*
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
@ -36,9 +33,6 @@ build/*
|
||||
# Codelite
|
||||
.codelite
|
||||
|
||||
# KDevelop
|
||||
*.kdev4
|
||||
|
||||
# .orig files
|
||||
*.orig
|
||||
|
||||
@ -51,13 +45,11 @@ example/*
|
||||
!example/example.sln
|
||||
!example/example.vcxproj
|
||||
!example/CMakeLists.txt
|
||||
!example/meson.build
|
||||
!example/multisink.cpp
|
||||
!example/jni
|
||||
|
||||
# generated files
|
||||
generated
|
||||
version.rc
|
||||
|
||||
# Cmake
|
||||
CMakeCache.txt
|
||||
@ -69,30 +61,4 @@ install_manifest.txt
|
||||
/tests/tests.VC.VC.opendb
|
||||
/tests/tests.VC.db
|
||||
/tests/tests
|
||||
/tests/logs/*
|
||||
spdlogConfig.cmake
|
||||
spdlogConfigVersion.cmake
|
||||
compile_commands.json
|
||||
|
||||
# idea
|
||||
.idea/
|
||||
.cache/
|
||||
.vscode/
|
||||
cmake-build-*/
|
||||
*.db
|
||||
*.ipch
|
||||
*.filters
|
||||
*.db-wal
|
||||
*.opendb
|
||||
*.db-shm
|
||||
*.vcxproj
|
||||
*.tcl
|
||||
*.user
|
||||
*.sln
|
||||
|
||||
# macos
|
||||
*.DS_store
|
||||
*.xcodeproj/
|
||||
/.vs
|
||||
/out/build
|
||||
/CMakeSettings.json
|
||||
/tests/logs/file_helper_test.txt
|
||||
|
90
.travis.yml
Normal file
90
.travis.yml
Normal file
@ -0,0 +1,90 @@
|
||||
# Adapted from various sources, including:
|
||||
# - Louis Dionne's Hana: https://github.com/ldionne/hana
|
||||
# - Paul Fultz II's FIT: https://github.com/pfultz2/Fit
|
||||
# - Eric Niebler's range-v3: https://github.com/ericniebler/range-v3
|
||||
language: cpp
|
||||
|
||||
# Test matrix:
|
||||
# - Build matrix per compiler: C++11/C++14 + Debug/Release
|
||||
# - Optionally: AddressSanitizer (ASAN)
|
||||
# - Valgrind: all release builds are also tested with valgrind
|
||||
# - clang 3.4, 3.5, 3.6, trunk
|
||||
# - Note: 3.4 and trunk are tested with/without ASAN,
|
||||
# the rest is only tested with ASAN=On.
|
||||
# - gcc 4.9, 5.0
|
||||
#
|
||||
matrix:
|
||||
include:
|
||||
|
||||
# Test gcc-4.8: C++11, Build=Debug/Release, ASAN=Off
|
||||
- env: GCC_VERSION=4.8 BUILD_TYPE=Debug CPP=11 ASAN=Off LIBCXX=Off
|
||||
os: linux
|
||||
addons: &gcc48
|
||||
apt:
|
||||
packages:
|
||||
- g++-4.8
|
||||
- valgrind
|
||||
sources:
|
||||
- ubuntu-toolchain-r-test
|
||||
|
||||
- env: GCC_VERSION=4.8 BUILD_TYPE=Release CPP=11 ASAN=Off LIBCXX=Off
|
||||
os: linux
|
||||
addons: *gcc48
|
||||
|
||||
# Test gcc-4.9: C++11, Build=Debug/Release, ASAN=Off
|
||||
- env: GCC_VERSION=4.9 BUILD_TYPE=Debug CPP=11 ASAN=Off LIBCXX=Off
|
||||
os: linux
|
||||
addons: &gcc49
|
||||
apt:
|
||||
packages:
|
||||
- g++-4.9
|
||||
- valgrind
|
||||
sources:
|
||||
- ubuntu-toolchain-r-test
|
||||
|
||||
- env: GCC_VERSION=4.9 BUILD_TYPE=Release CPP=11 ASAN=Off LIBCXX=Off
|
||||
os: linux
|
||||
addons: *gcc49
|
||||
|
||||
# Install dependencies
|
||||
before_install:
|
||||
- export CHECKOUT_PATH=`pwd`;
|
||||
- if [ -n "$GCC_VERSION" ]; then export CXX="g++-${GCC_VERSION}" CC="gcc-${GCC_VERSION}"; fi
|
||||
- if [ -n "$CLANG_VERSION" ]; then export CXX="clang++-${CLANG_VERSION}" CC="clang-${CLANG_VERSION}"; fi
|
||||
- if [ "$CLANG_VERSION" == "3.4" ]; then export CXX="/usr/local/clang-3.4/bin/clang++" CC="/usr/local/clang-3.4/bin/clang"; fi
|
||||
- which $CXX
|
||||
- which $CC
|
||||
- which valgrind
|
||||
- if [ -n "$CLANG_VERSION" ]; then sudo CXX=$CXX CC=$CC ./tests/install_libcxx.sh; fi
|
||||
|
||||
install:
|
||||
- cd $CHECKOUT_PATH
|
||||
|
||||
# Workaround for valgrind bug: https://bugs.kde.org/show_bug.cgi?id=326469.
|
||||
# It is fixed in valgrind 3.10 so this won't be necessary if someone
|
||||
# replaces the current valgrind (3.7) with valgrind-3.10
|
||||
- sed -i 's/march=native/msse4.2/' example/Makefile
|
||||
|
||||
- if [ ! -d build ]; then mkdir build; fi
|
||||
- export CXX_FLAGS="-I${CHECKOUT_PATH}/include"
|
||||
- export CXX_LINKER_FLAGS=""
|
||||
- if [ -z "$BUILD_TYPE" ]; then export BUILD_TYPE=Release; fi
|
||||
- if [ "$ASAN" == "On"]; then export CXX_FLAGS="${CXX_FLAGS} -fsanitize=address,undefined,integer -fno-omit-frame-pointer -fno-sanitize=unsigned-integer-overflow"; fi
|
||||
- if [ -n "$CLANG_VERSION" ]; then CXX_FLAGS="${CXX_FLAGS} -D__extern_always_inline=inline"; fi
|
||||
- if [ "$LIBCXX" == "On" ]; then CXX_FLAGS="${CXX_FLAGS} -stdlib=libc++ -I/usr/include/c++/v1/"; fi
|
||||
- if [ "$LIBCXX" == "On" ]; then CXX_LINKER_FLAGS="${CXX_FLAGS} -L/usr/lib/ -lc++"; fi
|
||||
- CXX_FLAGS="${CXX_FLAGS} -std=c++${CPP}"
|
||||
|
||||
# Build examples
|
||||
- cd example
|
||||
- if [ "$BUILD_TYPE" == "Release" ]; then make rebuild CXXFLAGS="${CXX_FLAGS} ${CXX_LINKER_FLAGS}" VERBOSE=1; export BIN=example; fi
|
||||
- if [ "$BUILD_TYPE" == "Debug" ]; then make rebuild debug CXXFLAGS="${CXX_FLAGS} ${CXX_LINKER_FLAGS}" VERBOSE=1; export BIN=example-debug; fi
|
||||
|
||||
|
||||
script:
|
||||
- ./"${BIN}"
|
||||
- valgrind --trace-children=yes --leak-check=full ./"${BIN}"
|
||||
- cd $CHECKOUT_PATH/tests; make rebuild; ./tests
|
||||
|
||||
notifications:
|
||||
email: false
|
484
CMakeLists.txt
484
CMakeLists.txt
@ -1,404 +1,80 @@
|
||||
# Copyright(c) 2019 spdlog authors Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
cmake_minimum_required(VERSION 3.10...3.21)
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Start spdlog project
|
||||
# ---------------------------------------------------------------------------------------
|
||||
include(cmake/utils.cmake)
|
||||
include(cmake/ide.cmake)
|
||||
|
||||
spdlog_extract_version()
|
||||
|
||||
project(spdlog VERSION ${SPDLOG_VERSION} LANGUAGES CXX)
|
||||
message(STATUS "Build spdlog: ${SPDLOG_VERSION}")
|
||||
|
||||
include(GNUInstallDirs)
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Set default build to release
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
|
||||
set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE)
|
||||
endif ()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Compiler config
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if (SPDLOG_USE_STD_FORMAT)
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
elseif (NOT CMAKE_CXX_STANDARD)
|
||||
set(CMAKE_CXX_STANDARD 11)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
endif ()
|
||||
|
||||
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
if (CMAKE_SYSTEM_NAME MATCHES "CYGWIN" OR CMAKE_SYSTEM_NAME MATCHES "MSYS" OR CMAKE_SYSTEM_NAME MATCHES "MINGW")
|
||||
set(CMAKE_CXX_EXTENSIONS ON)
|
||||
endif ()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Set SPDLOG_MASTER_PROJECT to ON if we are building spdlog
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Check if spdlog is being used directly or via add_subdirectory, but allow overriding
|
||||
if (NOT DEFINED SPDLOG_MASTER_PROJECT)
|
||||
if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
|
||||
set(SPDLOG_MASTER_PROJECT ON)
|
||||
else ()
|
||||
set(SPDLOG_MASTER_PROJECT OFF)
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
option(SPDLOG_BUILD_ALL "Build all artifacts" OFF)
|
||||
|
||||
# build shared option
|
||||
option(SPDLOG_BUILD_SHARED "Build shared library" OFF)
|
||||
|
||||
# precompiled headers option
|
||||
option(SPDLOG_ENABLE_PCH "Build static or shared library using precompiled header to speed up compilation time" OFF)
|
||||
|
||||
# build position independent code
|
||||
option(SPDLOG_BUILD_PIC "Build position independent code (-fPIC)" OFF)
|
||||
|
||||
# example options
|
||||
option(SPDLOG_BUILD_EXAMPLE "Build example" ${SPDLOG_MASTER_PROJECT})
|
||||
option(SPDLOG_BUILD_EXAMPLE_HO "Build header only example" OFF)
|
||||
|
||||
# testing options
|
||||
option(SPDLOG_BUILD_TESTS "Build tests" OFF)
|
||||
option(SPDLOG_BUILD_TESTS_HO "Build tests using the header only version" OFF)
|
||||
|
||||
# bench options
|
||||
option(SPDLOG_BUILD_BENCH "Build benchmarks (Requires https://github.com/google/benchmark.git to be installed)" OFF)
|
||||
|
||||
# sanitizer options
|
||||
option(SPDLOG_SANITIZE_ADDRESS "Enable address sanitizer in tests" OFF)
|
||||
option(SPDLOG_SANITIZE_THREAD "Enable thread sanitizer in tests" OFF)
|
||||
if (SPDLOG_SANITIZE_ADDRESS AND SPDLOG_SANITIZE_THREAD)
|
||||
message(FATAL_ERROR "SPDLOG_SANITIZE_ADDRESS and SPDLOG_SANITIZE_THREAD are mutually exclusive")
|
||||
endif ()
|
||||
|
||||
# warning options
|
||||
option(SPDLOG_BUILD_WARNINGS "Enable compiler warnings" OFF)
|
||||
|
||||
# install options
|
||||
option(SPDLOG_SYSTEM_INCLUDES "Include as system headers (skip for clang-tidy)." OFF)
|
||||
option(SPDLOG_INSTALL "Generate the install target" ${SPDLOG_MASTER_PROJECT})
|
||||
option(SPDLOG_USE_STD_FORMAT "Use std::format instead of fmt library." OFF)
|
||||
option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF)
|
||||
option(SPDLOG_FMT_EXTERNAL_HO "Use external fmt header-only library instead of bundled" OFF)
|
||||
option(SPDLOG_NO_EXCEPTIONS "Compile with -fno-exceptions. Call abort() on any spdlog exceptions" OFF)
|
||||
|
||||
if (SPDLOG_FMT_EXTERNAL AND SPDLOG_FMT_EXTERNAL_HO)
|
||||
message(FATAL_ERROR "SPDLOG_FMT_EXTERNAL and SPDLOG_FMT_EXTERNAL_HO are mutually exclusive")
|
||||
endif ()
|
||||
|
||||
if (SPDLOG_USE_STD_FORMAT AND SPDLOG_FMT_EXTERNAL_HO)
|
||||
message(FATAL_ERROR "SPDLOG_USE_STD_FORMAT and SPDLOG_FMT_EXTERNAL_HO are mutually exclusive")
|
||||
endif ()
|
||||
|
||||
if (SPDLOG_USE_STD_FORMAT AND SPDLOG_FMT_EXTERNAL)
|
||||
message(FATAL_ERROR "SPDLOG_USE_STD_FORMAT and SPDLOG_FMT_EXTERNAL are mutually exclusive")
|
||||
endif ()
|
||||
|
||||
# misc tweakme options
|
||||
if (WIN32)
|
||||
option(SPDLOG_WCHAR_SUPPORT "Support wchar api" OFF)
|
||||
option(SPDLOG_WCHAR_FILENAMES "Support wchar filenames" OFF)
|
||||
option(SPDLOG_WCHAR_CONSOLE "Support wchar output to console" OFF)
|
||||
else ()
|
||||
set(SPDLOG_WCHAR_SUPPORT OFF CACHE BOOL "non supported option" FORCE)
|
||||
set(SPDLOG_WCHAR_FILENAMES OFF CACHE BOOL "non supported option" FORCE)
|
||||
set(SPDLOG_WCHAR_CONSOLE OFF CACHE BOOL "non supported option" FORCE)
|
||||
endif ()
|
||||
|
||||
if (MSVC)
|
||||
option(SPDLOG_MSVC_UTF8 "Enable/disable msvc /utf-8 flag required by fmt lib" ON)
|
||||
endif ()
|
||||
|
||||
if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
|
||||
option(SPDLOG_CLOCK_COARSE "Use CLOCK_REALTIME_COARSE instead of the regular clock," OFF)
|
||||
else ()
|
||||
set(SPDLOG_CLOCK_COARSE OFF CACHE BOOL "non supported option" FORCE)
|
||||
endif ()
|
||||
|
||||
option(SPDLOG_PREVENT_CHILD_FD "Prevent from child processes to inherit log file descriptors" OFF)
|
||||
option(SPDLOG_NO_THREAD_ID "prevent spdlog from querying the thread id on each log call if thread id is not needed" OFF)
|
||||
option(SPDLOG_NO_TLS "prevent spdlog from using thread local storage" OFF)
|
||||
option(
|
||||
SPDLOG_NO_ATOMIC_LEVELS
|
||||
"prevent spdlog from using of std::atomic log levels (use only if your code never modifies log levels concurrently"
|
||||
OFF)
|
||||
option(SPDLOG_DISABLE_DEFAULT_LOGGER "Disable default logger creation" OFF)
|
||||
option(SPDLOG_FWRITE_UNLOCKED "Use the unlocked variant of fwrite. Leave this on unless your libc doesn't have it" ON)
|
||||
|
||||
# clang-tidy
|
||||
option(SPDLOG_TIDY "run clang-tidy" OFF)
|
||||
|
||||
if (SPDLOG_TIDY)
|
||||
set(CMAKE_CXX_CLANG_TIDY "clang-tidy")
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
message(STATUS "Enabled clang-tidy")
|
||||
endif ()
|
||||
|
||||
if (SPDLOG_BUILD_PIC)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
endif ()
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
message(STATUS "Build type: " ${CMAKE_BUILD_TYPE})
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Static/Shared library
|
||||
# ---------------------------------------------------------------------------------------
|
||||
set(SPDLOG_SRCS src/spdlog.cpp src/stdout_sinks.cpp src/color_sinks.cpp src/file_sinks.cpp src/async.cpp src/cfg.cpp)
|
||||
|
||||
if (NOT SPDLOG_USE_STD_FORMAT AND NOT SPDLOG_FMT_EXTERNAL AND NOT SPDLOG_FMT_EXTERNAL_HO)
|
||||
list(APPEND SPDLOG_SRCS src/bundled_fmtlib_format.cpp)
|
||||
endif ()
|
||||
|
||||
if (SPDLOG_BUILD_SHARED OR BUILD_SHARED_LIBS)
|
||||
if (WIN32)
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/version.rc @ONLY)
|
||||
list(APPEND SPDLOG_SRCS ${CMAKE_CURRENT_BINARY_DIR}/version.rc)
|
||||
endif ()
|
||||
add_library(spdlog SHARED ${SPDLOG_SRCS} ${SPDLOG_ALL_HEADERS})
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_SHARED_LIB)
|
||||
if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
|
||||
target_compile_options(spdlog PUBLIC $<$<AND:$<CXX_COMPILER_ID:MSVC>,$<NOT:$<COMPILE_LANGUAGE:CUDA>>>:/wd4251
|
||||
/wd4275>)
|
||||
endif ()
|
||||
if (NOT SPDLOG_USE_STD_FORMAT AND NOT SPDLOG_FMT_EXTERNAL AND NOT SPDLOG_FMT_EXTERNAL_HO)
|
||||
target_compile_definitions(spdlog PRIVATE FMT_LIB_EXPORT PUBLIC FMT_SHARED)
|
||||
endif ()
|
||||
else ()
|
||||
add_library(spdlog STATIC ${SPDLOG_SRCS} ${SPDLOG_ALL_HEADERS})
|
||||
endif ()
|
||||
|
||||
add_library(spdlog::spdlog ALIAS spdlog)
|
||||
|
||||
set(SPDLOG_INCLUDES_LEVEL "")
|
||||
if (SPDLOG_SYSTEM_INCLUDES)
|
||||
set(SPDLOG_INCLUDES_LEVEL "SYSTEM")
|
||||
endif ()
|
||||
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB)
|
||||
target_include_directories(spdlog ${SPDLOG_INCLUDES_LEVEL} PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>"
|
||||
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
target_link_libraries(spdlog PUBLIC Threads::Threads)
|
||||
spdlog_enable_warnings(spdlog)
|
||||
|
||||
set_target_properties(spdlog PROPERTIES VERSION ${SPDLOG_VERSION} SOVERSION
|
||||
${SPDLOG_VERSION_MAJOR}.${SPDLOG_VERSION_MINOR})
|
||||
set_target_properties(spdlog PROPERTIES DEBUG_POSTFIX d)
|
||||
|
||||
if (COMMAND target_precompile_headers AND SPDLOG_ENABLE_PCH)
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/pch.h.in ${PROJECT_BINARY_DIR}/spdlog_pch.h @ONLY)
|
||||
target_precompile_headers(spdlog PRIVATE ${PROJECT_BINARY_DIR}/spdlog_pch.h)
|
||||
endif ()
|
||||
|
||||
# sanitizer support
|
||||
if (SPDLOG_SANITIZE_ADDRESS)
|
||||
spdlog_enable_addr_sanitizer(spdlog)
|
||||
elseif (SPDLOG_SANITIZE_THREAD)
|
||||
spdlog_enable_thread_sanitizer(spdlog)
|
||||
endif ()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Header only version
|
||||
# ---------------------------------------------------------------------------------------
|
||||
add_library(spdlog_header_only INTERFACE)
|
||||
add_library(spdlog::spdlog_header_only ALIAS spdlog_header_only)
|
||||
|
||||
target_include_directories(
|
||||
spdlog_header_only ${SPDLOG_INCLUDES_LEVEL} INTERFACE "$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>"
|
||||
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
target_link_libraries(spdlog_header_only INTERFACE Threads::Threads)
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Use fmt package if using external fmt
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if (SPDLOG_FMT_EXTERNAL OR SPDLOG_FMT_EXTERNAL_HO)
|
||||
if (NOT TARGET fmt::fmt)
|
||||
find_package(fmt CONFIG REQUIRED)
|
||||
endif ()
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_FMT_EXTERNAL)
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_FMT_EXTERNAL)
|
||||
|
||||
# use external fmt-header-only
|
||||
if (SPDLOG_FMT_EXTERNAL_HO)
|
||||
target_link_libraries(spdlog PUBLIC fmt::fmt-header-only)
|
||||
target_link_libraries(spdlog_header_only INTERFACE fmt::fmt-header-only)
|
||||
else () # use external compile fmt
|
||||
target_link_libraries(spdlog PUBLIC fmt::fmt)
|
||||
target_link_libraries(spdlog_header_only INTERFACE fmt::fmt)
|
||||
endif ()
|
||||
|
||||
set(PKG_CONFIG_REQUIRES fmt) # add dependency to pkg-config
|
||||
endif ()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Check if fwrite_unlocked/_fwrite_nolock is available
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if (SPDLOG_FWRITE_UNLOCKED)
|
||||
include(CheckSymbolExists)
|
||||
if (WIN32)
|
||||
check_symbol_exists(_fwrite_nolock "stdio.h" HAVE_FWRITE_UNLOCKED)
|
||||
else ()
|
||||
check_symbol_exists(fwrite_unlocked "stdio.h" HAVE_FWRITE_UNLOCKED)
|
||||
endif ()
|
||||
if (HAVE_FWRITE_UNLOCKED)
|
||||
target_compile_definitions(spdlog PRIVATE SPDLOG_FWRITE_UNLOCKED)
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_FWRITE_UNLOCKED)
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Add required libraries for Android CMake build
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if (ANDROID)
|
||||
target_link_libraries(spdlog PUBLIC log)
|
||||
target_link_libraries(spdlog_header_only INTERFACE log)
|
||||
endif ()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Misc definitions according to tweak options
|
||||
# ---------------------------------------------------------------------------------------
|
||||
set(SPDLOG_WCHAR_TO_UTF8_SUPPORT ${SPDLOG_WCHAR_SUPPORT})
|
||||
set(SPDLOG_UTF8_TO_WCHAR_CONSOLE ${SPDLOG_WCHAR_CONSOLE})
|
||||
foreach (
|
||||
SPDLOG_OPTION
|
||||
SPDLOG_WCHAR_TO_UTF8_SUPPORT
|
||||
SPDLOG_UTF8_TO_WCHAR_CONSOLE
|
||||
SPDLOG_WCHAR_FILENAMES
|
||||
SPDLOG_NO_EXCEPTIONS
|
||||
SPDLOG_CLOCK_COARSE
|
||||
SPDLOG_PREVENT_CHILD_FD
|
||||
SPDLOG_NO_THREAD_ID
|
||||
SPDLOG_NO_TLS
|
||||
SPDLOG_NO_ATOMIC_LEVELS
|
||||
SPDLOG_DISABLE_DEFAULT_LOGGER
|
||||
SPDLOG_USE_STD_FORMAT)
|
||||
if (${SPDLOG_OPTION})
|
||||
target_compile_definitions(spdlog PUBLIC ${SPDLOG_OPTION})
|
||||
target_compile_definitions(spdlog_header_only INTERFACE ${SPDLOG_OPTION})
|
||||
endif ()
|
||||
endforeach ()
|
||||
|
||||
if (MSVC)
|
||||
target_compile_options(spdlog PRIVATE "/Zc:__cplusplus")
|
||||
target_compile_options(spdlog_header_only INTERFACE "/Zc:__cplusplus")
|
||||
if (SPDLOG_MSVC_UTF8)
|
||||
# fmtlib requires the /utf-8 flag when building with msvc.
|
||||
# see https://github.com/fmtlib/fmt/pull/4159 on the purpose of the additional
|
||||
# "$<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CXX_COMPILER_ID:MSVC>>"
|
||||
target_compile_options(spdlog PUBLIC $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CXX_COMPILER_ID:MSVC>>:/utf-8>)
|
||||
target_compile_options(spdlog_header_only INTERFACE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CXX_COMPILER_ID:MSVC>>:/utf-8>)
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# If exceptions are disabled, disable them in the bundled fmt as well
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if (SPDLOG_NO_EXCEPTIONS)
|
||||
if (NOT SPDLOG_FMT_EXTERNAL AND NOT SPDLOG_FMT_EXTERNAL_HO)
|
||||
target_compile_definitions(spdlog PUBLIC FMT_USE_EXCEPTIONS=0)
|
||||
endif ()
|
||||
if (NOT MSVC)
|
||||
target_compile_options(spdlog PRIVATE -fno-exceptions)
|
||||
else ()
|
||||
target_compile_options(spdlog PRIVATE /EHs-c-)
|
||||
target_compile_definitions(spdlog PRIVATE _HAS_EXCEPTIONS=0)
|
||||
endif ()
|
||||
endif ()
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Build binaries
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if (SPDLOG_BUILD_EXAMPLE OR SPDLOG_BUILD_EXAMPLE_HO OR SPDLOG_BUILD_ALL)
|
||||
message(STATUS "Generating example(s)")
|
||||
add_subdirectory(example)
|
||||
spdlog_enable_warnings(example)
|
||||
if (SPDLOG_BUILD_EXAMPLE_HO)
|
||||
spdlog_enable_warnings(example_header_only)
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
if (SPDLOG_BUILD_TESTS OR SPDLOG_BUILD_TESTS_HO OR SPDLOG_BUILD_ALL)
|
||||
message(STATUS "Generating tests")
|
||||
enable_testing()
|
||||
add_subdirectory(tests)
|
||||
endif ()
|
||||
|
||||
if (SPDLOG_BUILD_BENCH OR SPDLOG_BUILD_ALL)
|
||||
message(STATUS "Generating benchmarks")
|
||||
add_subdirectory(bench)
|
||||
endif ()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Install
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if (SPDLOG_INSTALL)
|
||||
message(STATUS "Generating install")
|
||||
set(project_config_in "${CMAKE_CURRENT_LIST_DIR}/cmake/spdlogConfig.cmake.in")
|
||||
set(project_config_out "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfig.cmake")
|
||||
set(config_targets_file "spdlogConfigTargets.cmake")
|
||||
set(version_config_file "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfigVersion.cmake")
|
||||
set(export_dest_dir "${CMAKE_INSTALL_LIBDIR}/cmake/spdlog")
|
||||
set(pkgconfig_install_dir "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
|
||||
set(pkg_config "${CMAKE_BINARY_DIR}/${PROJECT_NAME}.pc")
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Include files
|
||||
# ---------------------------------------------------------------------------------------
|
||||
install(DIRECTORY include/ DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" PATTERN "fmt/bundled" EXCLUDE)
|
||||
install(
|
||||
TARGETS spdlog spdlog_header_only
|
||||
EXPORT spdlog
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
|
||||
if (NOT SPDLOG_USE_STD_FORMAT AND NOT SPDLOG_FMT_EXTERNAL AND NOT SPDLOG_FMT_EXTERNAL_HO)
|
||||
install(DIRECTORY include/${PROJECT_NAME}/fmt/bundled/
|
||||
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/fmt/bundled/")
|
||||
endif ()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Install pkg-config file
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if (IS_ABSOLUTE "${CMAKE_INSTALL_INCLUDEDIR}")
|
||||
set(PKG_CONFIG_INCLUDEDIR "${CMAKE_INSTALL_INCLUDEDIR}")
|
||||
else ()
|
||||
set(PKG_CONFIG_INCLUDEDIR "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}")
|
||||
endif ()
|
||||
if (IS_ABSOLUTE "${CMAKE_INSTALL_LIBDIR}")
|
||||
set(PKG_CONFIG_LIBDIR "${CMAKE_INSTALL_LIBDIR}")
|
||||
else ()
|
||||
set(PKG_CONFIG_LIBDIR "\${exec_prefix}/${CMAKE_INSTALL_LIBDIR}")
|
||||
endif ()
|
||||
get_target_property(PKG_CONFIG_DEFINES spdlog INTERFACE_COMPILE_DEFINITIONS)
|
||||
string(REPLACE ";" " -D" PKG_CONFIG_DEFINES "${PKG_CONFIG_DEFINES}")
|
||||
string(CONCAT PKG_CONFIG_DEFINES "-D" "${PKG_CONFIG_DEFINES}")
|
||||
configure_file("cmake/${PROJECT_NAME}.pc.in" "${pkg_config}" @ONLY)
|
||||
install(FILES "${pkg_config}" DESTINATION "${pkgconfig_install_dir}")
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Install CMake config files
|
||||
# ---------------------------------------------------------------------------------------
|
||||
export(TARGETS spdlog spdlog_header_only NAMESPACE spdlog::
|
||||
FILE "${CMAKE_CURRENT_BINARY_DIR}/${config_targets_file}")
|
||||
install(EXPORT spdlog DESTINATION ${export_dest_dir} NAMESPACE spdlog:: FILE ${config_targets_file})
|
||||
|
||||
include(CMakePackageConfigHelpers)
|
||||
configure_package_config_file("${project_config_in}" "${project_config_out}" INSTALL_DESTINATION ${export_dest_dir})
|
||||
|
||||
write_basic_package_version_file("${version_config_file}" COMPATIBILITY SameMajorVersion)
|
||||
install(FILES "${project_config_out}" "${version_config_file}" DESTINATION "${export_dest_dir}")
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Support creation of installable packages
|
||||
# ---------------------------------------------------------------------------------------
|
||||
include(cmake/spdlogCPack.cmake)
|
||||
endif ()
|
||||
#
|
||||
# Copyright(c) 2015 Ruslan Baratov.
|
||||
# Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
#
|
||||
|
||||
cmake_minimum_required(VERSION 3.1)
|
||||
project(spdlog VERSION 1.0.0)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 11)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
add_library(spdlog INTERFACE)
|
||||
|
||||
option(SPDLOG_BUILD_EXAMPLES "Build examples" OFF)
|
||||
option(SPDLOG_BUILD_TESTS "Build tests" OFF)
|
||||
|
||||
target_include_directories(
|
||||
spdlog
|
||||
INTERFACE
|
||||
"$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>"
|
||||
"$<INSTALL_INTERFACE:include>"
|
||||
)
|
||||
|
||||
set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
|
||||
include(CTest)
|
||||
if(SPDLOG_BUILD_EXAMPLES)
|
||||
add_subdirectory(example)
|
||||
endif()
|
||||
|
||||
if(SPDLOG_BUILD_TESTS)
|
||||
add_subdirectory(tests)
|
||||
endif()
|
||||
|
||||
### Install ###
|
||||
# * https://github.com/forexample/package-example
|
||||
set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
||||
|
||||
set(config_install_dir "lib/cmake/${PROJECT_NAME}")
|
||||
set(include_install_dir "include")
|
||||
set(pkgconfig_install_dir "lib/pkgconfig")
|
||||
|
||||
set(version_config "${generated_dir}/${PROJECT_NAME}ConfigVersion.cmake")
|
||||
set(project_config "${generated_dir}/${PROJECT_NAME}Config.cmake")
|
||||
set(pkg_config "${generated_dir}/${PROJECT_NAME}.pc")
|
||||
set(targets_export_name "${PROJECT_NAME}Targets")
|
||||
set(namespace "${PROJECT_NAME}::")
|
||||
|
||||
include(CMakePackageConfigHelpers)
|
||||
write_basic_package_version_file(
|
||||
"${version_config}" COMPATIBILITY SameMajorVersion
|
||||
)
|
||||
|
||||
# Note: use 'targets_export_name'
|
||||
configure_file("cmake/Config.cmake.in" "${project_config}" @ONLY)
|
||||
configure_file("cmake/spdlog.pc.in" "${pkg_config}" @ONLY)
|
||||
|
||||
install(
|
||||
TARGETS spdlog
|
||||
EXPORT "${targets_export_name}"
|
||||
INCLUDES DESTINATION "${include_install_dir}"
|
||||
)
|
||||
|
||||
install(DIRECTORY "include/spdlog" DESTINATION "${include_install_dir}")
|
||||
|
||||
install(
|
||||
FILES "${project_config}" "${version_config}"
|
||||
DESTINATION "${config_install_dir}"
|
||||
)
|
||||
|
||||
install(
|
||||
FILES "${pkg_config}"
|
||||
DESTINATION "${pkgconfig_install_dir}"
|
||||
)
|
||||
|
||||
install(
|
||||
EXPORT "${targets_export_name}"
|
||||
NAMESPACE "${namespace}"
|
||||
DESTINATION "${config_install_dir}"
|
||||
)
|
||||
|
34
INSTALL
34
INSTALL
@ -1,27 +1,13 @@
|
||||
Header Only Version
|
||||
==================================================================
|
||||
Just copy the files to your build tree and use a C++11 compiler.
|
||||
Or use CMake:
|
||||
```
|
||||
add_executable(example_header_only example.cpp)
|
||||
target_link_libraries(example_header_only spdlog::spdlog_header_only)
|
||||
```
|
||||
spdlog is header only library.
|
||||
Just copy the files to your build tree and use a C++11 compiler
|
||||
|
||||
Compiled Library Version
|
||||
==================================================================
|
||||
CMake:
|
||||
```
|
||||
add_executable(example example.cpp)
|
||||
target_link_libraries(example spdlog::spdlog)
|
||||
```
|
||||
|
||||
Or copy files src/*.cpp to your build tree and pass the -DSPDLOG_COMPILED_LIB to the compiler.
|
||||
|
||||
Important Information for Compilation:
|
||||
==================================================================
|
||||
* If you encounter compilation errors with gcc 4.8.x, please note that gcc 4.8.x does not fully support C++11. In such cases, consider upgrading your compiler or using a different version that fully supports C++11 standards
|
||||
|
||||
Tested on:
|
||||
Tested on:
|
||||
gcc 4.8.1 and above
|
||||
clang 3.5
|
||||
Visual Studio 2013
|
||||
Visual Studio 2013
|
||||
|
||||
gcc 4.8 flags: --std==c++11 -pthread -O3 -flto -Wl,--no-as-needed
|
||||
gcc 4.9 flags: --std=c++11 -pthread -O3 -flto
|
||||
|
||||
|
||||
see the makefile in the example folder
|
||||
|
4
LICENSE
4
LICENSE
@ -20,7 +20,3 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
-- NOTE: Third party dependency used by this software --
|
||||
This software depends on the fmt lib (MIT License),
|
||||
and users must comply to its license: https://raw.githubusercontent.com/fmtlib/fmt/master/LICENSE
|
||||
|
||||
|
685
README.md
685
README.md
@ -1,529 +1,200 @@
|
||||
# spdlog
|
||||
|
||||
|
||||
[](https://github.com/gabime/spdlog/actions/workflows/linux.yml)
|
||||
[](https://github.com/gabime/spdlog/actions/workflows/windows.yml)
|
||||
[](https://github.com/gabime/spdlog/actions/workflows/macos.yml)
|
||||
[](https://ci.appveyor.com/project/gabime/spdlog) [](https://github.com/gabime/spdlog/releases/latest)
|
||||
|
||||
Fast C++ logging library
|
||||
Very fast, header only, C++ logging library. [](https://travis-ci.org/gabime/spdlog) [](https://ci.appveyor.com/project/gabime/spdlog)
|
||||
|
||||
|
||||
## Install
|
||||
#### Header-only version
|
||||
Copy the include [folder](include/spdlog) to your build tree and use a C++11 compiler.
|
||||
|
||||
#### Compiled version (recommended - much faster compile times)
|
||||
```console
|
||||
$ git clone https://github.com/gabime/spdlog.git
|
||||
$ cd spdlog && mkdir build && cd build
|
||||
$ cmake .. && cmake --build .
|
||||
```
|
||||
see example [CMakeLists.txt](example/CMakeLists.txt) on how to use.
|
||||
Just copy the source [folder](https://github.com/gabime/spdlog/tree/master/include/spdlog) to your build tree and use a C++11 compiler
|
||||
|
||||
## Platforms
|
||||
* Linux, FreeBSD, OpenBSD, Solaris, AIX
|
||||
* Windows (msvc 2013+, cygwin)
|
||||
* macOS (clang 3.5+)
|
||||
* Android
|
||||
* Linux (gcc 4.8.1+, clang 3.5+)
|
||||
* Windows (visual studio 2013+, cygwin/mingw with g++ 4.9.1+)
|
||||
* Mac OSX (clang 3.5+)
|
||||
* Solaris (gcc 5.2.0+)
|
||||
* Android
|
||||
|
||||
## Package managers:
|
||||
* Debian: `sudo apt install libspdlog-dev`
|
||||
* Homebrew: `brew install spdlog`
|
||||
* MacPorts: `sudo port install spdlog`
|
||||
* FreeBSD: `pkg install spdlog`
|
||||
* Fedora: `dnf install spdlog`
|
||||
* Gentoo: `emerge dev-libs/spdlog`
|
||||
* Arch Linux: `pacman -S spdlog`
|
||||
* openSUSE: `sudo zypper in spdlog-devel`
|
||||
* ALT Linux: `apt-get install libspdlog-devel`
|
||||
* vcpkg: `vcpkg install spdlog`
|
||||
* conan: `conan install --requires=spdlog/[*]`
|
||||
* conda: `conda install -c conda-forge spdlog`
|
||||
* build2: ```depends: spdlog ^1.8.2```
|
||||
|
||||
|
||||
## Features
|
||||
* Very fast (see [benchmarks](#benchmarks) below).
|
||||
* Headers only or compiled
|
||||
* Feature-rich formatting, using the excellent [fmt](https://github.com/fmtlib/fmt) library.
|
||||
* Asynchronous mode (optional)
|
||||
* [Custom](https://github.com/gabime/spdlog/wiki/Custom-formatting) formatting.
|
||||
##Features
|
||||
* Very fast - performance is the primary goal (see [benchmarks](#benchmarks) below).
|
||||
* Headers only, just copy and use.
|
||||
* Feature rich [call style](#usage-example) using the excellent [fmt](https://github.com/fmtlib/fmt) library.
|
||||
* Extremely fast asynchronous mode (optional) - using lockfree queues and other tricks to reach millions of calls/sec.
|
||||
* [Custom](https://github.com/gabime/spdlog/wiki/3.-Custom-formatting) formatting.
|
||||
* Multi/Single threaded loggers.
|
||||
* Various log targets:
|
||||
* Rotating log files.
|
||||
* Daily log files.
|
||||
* Console logging (colors supported).
|
||||
* syslog.
|
||||
* Windows event log.
|
||||
* Windows debugger (```OutputDebugString(..)```).
|
||||
* Log to Qt widgets ([example](#log-to-qt-with-nice-colors)).
|
||||
* Easily [extendable](https://github.com/gabime/spdlog/wiki/Sinks#implementing-your-own-sink) with custom log targets.
|
||||
* Log filtering - log levels can be modified at runtime as well as compile time.
|
||||
* Support for loading log levels from argv or environment var.
|
||||
* [Backtrace](#backtrace-support) support - store debug messages in a ring buffer and display them later on demand.
|
||||
|
||||
## Usage samples
|
||||
|
||||
#### Basic usage
|
||||
```c++
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
int main()
|
||||
{
|
||||
spdlog::info("Welcome to spdlog!");
|
||||
spdlog::error("Some error message with arg: {}", 1);
|
||||
|
||||
spdlog::warn("Easy padding in numbers like {:08d}", 12);
|
||||
spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
|
||||
spdlog::info("Support for floats {:03.2f}", 1.23456);
|
||||
spdlog::info("Positional args are {1} {0}..", "too", "supported");
|
||||
spdlog::info("{:<30}", "left aligned");
|
||||
|
||||
spdlog::set_level(spdlog::level::debug); // Set global log level to debug
|
||||
spdlog::debug("This message should be displayed..");
|
||||
|
||||
// change log pattern
|
||||
spdlog::set_pattern("[%H:%M:%S %z] [%n] [%^---%L---%$] [thread %t] %v");
|
||||
|
||||
// Compile time log levels
|
||||
// Note that this does not change the current log level, it will only
|
||||
// remove (depending on SPDLOG_ACTIVE_LEVEL) the call on the release code.
|
||||
SPDLOG_TRACE("Some trace message with param {}", 42);
|
||||
SPDLOG_DEBUG("Some debug message");
|
||||
}
|
||||
|
||||
```
|
||||
---
|
||||
#### Create stdout/stderr logger object
|
||||
```c++
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/sinks/stdout_color_sinks.h"
|
||||
void stdout_example()
|
||||
{
|
||||
// create a color multi-threaded logger
|
||||
auto console = spdlog::stdout_color_mt("console");
|
||||
auto err_logger = spdlog::stderr_color_mt("stderr");
|
||||
spdlog::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name)");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### Basic file logger
|
||||
```c++
|
||||
#include "spdlog/sinks/basic_file_sink.h"
|
||||
void basic_logfile_example()
|
||||
{
|
||||
try
|
||||
{
|
||||
auto logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt");
|
||||
}
|
||||
catch (const spdlog::spdlog_ex &ex)
|
||||
{
|
||||
std::cout << "Log init failed: " << ex.what() << std::endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
---
|
||||
#### Rotating files
|
||||
```c++
|
||||
#include "spdlog/sinks/rotating_file_sink.h"
|
||||
void rotating_example()
|
||||
{
|
||||
// Create a file rotating logger with 5 MB size max and 3 rotated files
|
||||
auto max_size = 1048576 * 5;
|
||||
auto max_files = 3;
|
||||
auto logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", max_size, max_files);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### Daily files
|
||||
```c++
|
||||
|
||||
#include "spdlog/sinks/daily_file_sink.h"
|
||||
void daily_example()
|
||||
{
|
||||
// Create a daily logger - a new file is created every day at 2:30 am
|
||||
auto logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
#### Backtrace support
|
||||
```c++
|
||||
// Debug messages can be stored in a ring buffer instead of being logged immediately.
|
||||
// This is useful to display debug logs only when needed (e.g. when an error happens).
|
||||
// When needed, call dump_backtrace() to dump them to your log.
|
||||
|
||||
spdlog::enable_backtrace(32); // Store the latest 32 messages in a buffer.
|
||||
// or my_logger->enable_backtrace(32)..
|
||||
for(int i = 0; i < 100; i++)
|
||||
{
|
||||
spdlog::debug("Backtrace message {}", i); // not logged yet..
|
||||
}
|
||||
// e.g. if some error happened:
|
||||
spdlog::dump_backtrace(); // log them now! show the last 32 messages
|
||||
// or my_logger->dump_backtrace(32)..
|
||||
```
|
||||
|
||||
---
|
||||
#### Periodic flush
|
||||
```c++
|
||||
// periodically flush all *registered* loggers every 3 seconds:
|
||||
// warning: only use if all your loggers are thread-safe ("_mt" loggers)
|
||||
spdlog::flush_every(std::chrono::seconds(3));
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
#### Stopwatch
|
||||
```c++
|
||||
// Stopwatch support for spdlog
|
||||
#include "spdlog/stopwatch.h"
|
||||
void stopwatch_example()
|
||||
{
|
||||
spdlog::stopwatch sw;
|
||||
spdlog::debug("Elapsed {}", sw);
|
||||
spdlog::debug("Elapsed {:.3}", sw);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
#### Log binary data in hex
|
||||
```c++
|
||||
// many types of std::container<char> types can be used.
|
||||
// ranges are supported too.
|
||||
// format flags:
|
||||
// {:X} - print in uppercase.
|
||||
// {:s} - don't separate each byte with space.
|
||||
// {:p} - don't print the position on each line start.
|
||||
// {:n} - don't split the output into lines.
|
||||
// {:a} - show ASCII if :n is not set.
|
||||
|
||||
#include "spdlog/fmt/bin_to_hex.h"
|
||||
|
||||
void binary_example()
|
||||
{
|
||||
auto console = spdlog::get("console");
|
||||
std::array<char, 80> buf;
|
||||
console->info("Binary example: {}", spdlog::to_hex(buf));
|
||||
console->info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
|
||||
// more examples:
|
||||
// logger->info("uppercase: {:X}", spdlog::to_hex(buf));
|
||||
// logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
|
||||
// logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
#### Logger with multi sinks - each with a different format and log level
|
||||
```c++
|
||||
|
||||
// create a logger with 2 targets, with different log levels and formats.
|
||||
// The console will show only warnings or errors, while the file will log all.
|
||||
void multi_sink_example()
|
||||
{
|
||||
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
|
||||
console_sink->set_level(spdlog::level::warn);
|
||||
console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v");
|
||||
|
||||
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/multisink.txt", true);
|
||||
file_sink->set_level(spdlog::level::trace);
|
||||
|
||||
spdlog::logger logger("multi_sink", {console_sink, file_sink});
|
||||
logger.set_level(spdlog::level::debug);
|
||||
logger.warn("this should appear in both console and file");
|
||||
logger.info("this message should not appear in the console, only in the file");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### User-defined callbacks about log events
|
||||
```c++
|
||||
|
||||
// create a logger with a lambda function callback, the callback will be called
|
||||
// each time something is logged to the logger
|
||||
void callback_example()
|
||||
{
|
||||
auto callback_sink = std::make_shared<spdlog::sinks::callback_sink_mt>([](const spdlog::details::log_msg &msg) {
|
||||
// for example you can be notified by sending an email to yourself
|
||||
});
|
||||
callback_sink->set_level(spdlog::level::err);
|
||||
|
||||
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
|
||||
spdlog::logger logger("custom_callback_logger", {console_sink, callback_sink});
|
||||
|
||||
logger.info("some info log");
|
||||
logger.error("critical issue"); // will notify you
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### Asynchronous logging
|
||||
```c++
|
||||
#include "spdlog/async.h"
|
||||
#include "spdlog/sinks/basic_file_sink.h"
|
||||
void async_example()
|
||||
{
|
||||
// default thread pool settings can be modified *before* creating the async logger:
|
||||
// spdlog::init_thread_pool(8192, 1); // queue with 8k items and 1 backing thread.
|
||||
auto async_file = spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt");
|
||||
// alternatively:
|
||||
// auto async_file = spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("async_file_logger", "logs/async_log.txt");
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
#### Asynchronous logger with multi sinks
|
||||
```c++
|
||||
#include "spdlog/async.h"
|
||||
#include "spdlog/sinks/stdout_color_sinks.h"
|
||||
#include "spdlog/sinks/rotating_file_sink.h"
|
||||
|
||||
void multi_sink_example2()
|
||||
{
|
||||
spdlog::init_thread_pool(8192, 1);
|
||||
auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt >();
|
||||
auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("mylog.txt", 1024*1024*10, 3);
|
||||
std::vector<spdlog::sink_ptr> sinks {stdout_sink, rotating_sink};
|
||||
auto logger = std::make_shared<spdlog::async_logger>("loggername", sinks.begin(), sinks.end(), spdlog::thread_pool(), spdlog::async_overflow_policy::block);
|
||||
spdlog::register_logger(logger);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### User-defined types
|
||||
```c++
|
||||
template<>
|
||||
struct fmt::formatter<my_type> : fmt::formatter<std::string>
|
||||
{
|
||||
auto format(my_type my, format_context &ctx) const -> decltype(ctx.out())
|
||||
{
|
||||
return fmt::format_to(ctx.out(), "[my_type i={}]", my.i);
|
||||
}
|
||||
};
|
||||
|
||||
void user_defined_example()
|
||||
{
|
||||
spdlog::info("user defined type: {}", my_type(14));
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
#### User-defined flags in the log pattern
|
||||
```c++
|
||||
// Log patterns can contain custom flags.
|
||||
// the following example will add new flag '%*' - which will be bound to a <my_formatter_flag> instance.
|
||||
#include "spdlog/pattern_formatter.h"
|
||||
class my_formatter_flag : public spdlog::custom_flag_formatter
|
||||
{
|
||||
public:
|
||||
void format(const spdlog::details::log_msg &, const std::tm &, spdlog::memory_buf_t &dest) override
|
||||
{
|
||||
std::string some_txt = "custom-flag";
|
||||
dest.append(some_txt.data(), some_txt.data() + some_txt.size());
|
||||
}
|
||||
|
||||
std::unique_ptr<custom_flag_formatter> clone() const override
|
||||
{
|
||||
return spdlog::details::make_unique<my_formatter_flag>();
|
||||
}
|
||||
};
|
||||
|
||||
void custom_flags_example()
|
||||
{
|
||||
auto formatter = std::make_unique<spdlog::pattern_formatter>();
|
||||
formatter->add_flag<my_formatter_flag>('*').set_pattern("[%n] [%*] [%^%l%$] %v");
|
||||
spdlog::set_formatter(std::move(formatter));
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
#### Custom error handler
|
||||
```c++
|
||||
void err_handler_example()
|
||||
{
|
||||
// can be set globally or per logger(logger->set_error_handler(..))
|
||||
spdlog::set_error_handler([](const std::string &msg) { spdlog::get("console")->error("*** LOGGER ERROR ***: {}", msg); });
|
||||
spdlog::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
#### syslog
|
||||
```c++
|
||||
#include "spdlog/sinks/syslog_sink.h"
|
||||
void syslog_example()
|
||||
{
|
||||
std::string ident = "spdlog-example";
|
||||
auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID);
|
||||
syslog_logger->warn("This is warning that will end up in syslog.");
|
||||
}
|
||||
```
|
||||
---
|
||||
#### Android example
|
||||
```c++
|
||||
#include "spdlog/sinks/android_sink.h"
|
||||
void android_example()
|
||||
{
|
||||
std::string tag = "spdlog-android";
|
||||
auto android_logger = spdlog::android_logger_mt("android", tag);
|
||||
android_logger->critical("Use \"adb shell logcat\" to view this message.");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### Load log levels from the env variable or argv
|
||||
|
||||
```c++
|
||||
#include "spdlog/cfg/env.h"
|
||||
int main (int argc, char *argv[])
|
||||
{
|
||||
spdlog::cfg::load_env_levels();
|
||||
// or specify the env variable name:
|
||||
// MYAPP_LEVEL=info,mylogger=trace && ./example
|
||||
// spdlog::cfg::load_env_levels("MYAPP_LEVEL");
|
||||
// or from the command line:
|
||||
// ./example SPDLOG_LEVEL=info,mylogger=trace
|
||||
// #include "spdlog/cfg/argv.h" // for loading levels from argv
|
||||
// spdlog::cfg::load_argv_levels(argc, argv);
|
||||
}
|
||||
```
|
||||
So then you can:
|
||||
|
||||
```console
|
||||
$ export SPDLOG_LEVEL=info,mylogger=trace
|
||||
$ ./example
|
||||
```
|
||||
* Rotating log files.
|
||||
* Daily log files.
|
||||
* Console logging (colors supported).
|
||||
* syslog.
|
||||
* Easily extendable with custom log targets (just implement a single function in the [sink](include/spdlog/sinks/sink.h) interface).
|
||||
* Severity based filtering - threshold levels can be modified in runtime as well as in compile time.
|
||||
|
||||
|
||||
---
|
||||
#### Log file open/close event handlers
|
||||
```c++
|
||||
// You can get callbacks from spdlog before/after a log file has been opened or closed.
|
||||
// This is useful for cleanup procedures or for adding something to the start/end of the log file.
|
||||
void file_events_example()
|
||||
{
|
||||
// pass the spdlog::file_event_handlers to file sinks for open/close log file notifications
|
||||
spdlog::file_event_handlers handlers;
|
||||
handlers.before_open = [](spdlog::filename_t filename) { spdlog::info("Before opening {}", filename); };
|
||||
handlers.after_open = [](spdlog::filename_t filename, std::FILE *fstream) { fputs("After opening\n", fstream); };
|
||||
handlers.before_close = [](spdlog::filename_t filename, std::FILE *fstream) { fputs("Before closing\n", fstream); };
|
||||
handlers.after_close = [](spdlog::filename_t filename) { spdlog::info("After closing {}", filename); };
|
||||
auto my_logger = spdlog::basic_logger_st("some_logger", "logs/events-sample.txt", true, handlers);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### Replace the Default Logger
|
||||
```c++
|
||||
void replace_default_logger_example()
|
||||
{
|
||||
auto new_logger = spdlog::basic_logger_mt("new_default_logger", "logs/new-default-log.txt", true);
|
||||
spdlog::set_default_logger(new_logger);
|
||||
spdlog::info("new logger log message");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### Log to Qt with nice colors
|
||||
```c++
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/sinks/qt_sinks.h"
|
||||
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
|
||||
{
|
||||
setMinimumSize(640, 480);
|
||||
auto log_widget = new QTextEdit(this);
|
||||
setCentralWidget(log_widget);
|
||||
int max_lines = 500; // keep the text widget to max 500 lines. remove old lines if needed.
|
||||
auto logger = spdlog::qt_color_logger_mt("qt_logger", log_widget, max_lines);
|
||||
logger->info("Some info message");
|
||||
}
|
||||
```
|
||||
---
|
||||
|
||||
#### Mapped Diagnostic Context
|
||||
```c++
|
||||
// Mapped Diagnostic Context (MDC) is a map that stores key-value pairs (string values) in thread local storage.
|
||||
// Each thread maintains its own MDC, which loggers use to append diagnostic information to log outputs.
|
||||
// Note: it is not supported in asynchronous mode due to its reliance on thread-local storage.
|
||||
#include "spdlog/mdc.h"
|
||||
void mdc_example()
|
||||
{
|
||||
spdlog::mdc::put("key1", "value1");
|
||||
spdlog::mdc::put("key2", "value2");
|
||||
// if not using the default format, use the %& formatter to print mdc data
|
||||
// spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [%&] %v");
|
||||
}
|
||||
```
|
||||
---
|
||||
## Benchmarks
|
||||
|
||||
Below are some [benchmarks](bench/bench.cpp) done in Ubuntu 64 bit, Intel i7-4770 CPU @ 3.40GHz
|
||||
Below are some [benchmarks](bench) comparing popular log libraries under Ubuntu 64 bit, Intel i7-4770 CPU @ 3.40GHz
|
||||
|
||||
#### Synchronous mode
|
||||
```
|
||||
[info] **************************************************************
|
||||
[info] Single thread, 1,000,000 iterations
|
||||
[info] **************************************************************
|
||||
[info] basic_st Elapsed: 0.17 secs 5,777,626/sec
|
||||
[info] rotating_st Elapsed: 0.18 secs 5,475,894/sec
|
||||
[info] daily_st Elapsed: 0.20 secs 5,062,659/sec
|
||||
[info] empty_logger Elapsed: 0.07 secs 14,127,300/sec
|
||||
[info] **************************************************************
|
||||
[info] C-string (400 bytes). Single thread, 1,000,000 iterations
|
||||
[info] **************************************************************
|
||||
[info] basic_st Elapsed: 0.41 secs 2,412,483/sec
|
||||
[info] rotating_st Elapsed: 0.72 secs 1,389,196/sec
|
||||
[info] daily_st Elapsed: 0.42 secs 2,393,298/sec
|
||||
[info] null_st Elapsed: 0.04 secs 27,446,957/sec
|
||||
[info] **************************************************************
|
||||
[info] 10 threads, competing over the same logger object, 1,000,000 iterations
|
||||
[info] **************************************************************
|
||||
[info] basic_mt Elapsed: 0.60 secs 1,659,613/sec
|
||||
[info] rotating_mt Elapsed: 0.62 secs 1,612,493/sec
|
||||
[info] daily_mt Elapsed: 0.61 secs 1,638,305/sec
|
||||
[info] null_mt Elapsed: 0.16 secs 6,272,758/sec
|
||||
```
|
||||
Time needed to log 1,000,000 lines in synchronous mode (in seconds, the best of 3 runs):
|
||||
|
||||
|threads|boost log 1.54|glog |easylogging |spdlog|
|
||||
|-------|:-------:|:-----:|----------:|------:|
|
||||
|1| 4.169s |1.066s |0.975s |0.302s|
|
||||
|10| 6.180s |3.032s |2.857s |0.968s|
|
||||
|100| 5.981s |1.139s |4.512s |0.497s|
|
||||
|
||||
|
||||
#### Asynchronous mode
|
||||
```
|
||||
[info] -------------------------------------------------
|
||||
[info] Messages : 1,000,000
|
||||
[info] Threads : 10
|
||||
[info] Queue : 8,192 slots
|
||||
[info] Queue memory : 8,192 x 272 = 2,176 KB
|
||||
[info] -------------------------------------------------
|
||||
[info]
|
||||
[info] *********************************
|
||||
[info] Queue Overflow Policy: block
|
||||
[info] *********************************
|
||||
[info] Elapsed: 1.70784 secs 585,535/sec
|
||||
[info] Elapsed: 1.69805 secs 588,910/sec
|
||||
[info] Elapsed: 1.7026 secs 587,337/sec
|
||||
[info]
|
||||
[info] *********************************
|
||||
[info] Queue Overflow Policy: overrun
|
||||
[info] *********************************
|
||||
[info] Elapsed: 0.372816 secs 2,682,285/sec
|
||||
[info] Elapsed: 0.379758 secs 2,633,255/sec
|
||||
[info] Elapsed: 0.373532 secs 2,677,147/sec
|
||||
Time needed to log 1,000,000 lines in asynchronous mode, i.e. the time it takes to put them in the async queue (in seconds, the best of 3 runs):
|
||||
|
||||
|threads|g2log <sup>async logger</sup> |spdlog <sup>async mode</sup>|
|
||||
|:-------|:-----:|-------------------------:|
|
||||
|1| 1.850s |0.216s |
|
||||
|10| 0.943s |0.173s|
|
||||
|100| 0.959s |0.202s|
|
||||
|
||||
|
||||
|
||||
|
||||
## Usage Example
|
||||
```c++
|
||||
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
void async_example();
|
||||
void syslog_example();
|
||||
void user_defined_example();
|
||||
void err_handler_example();
|
||||
|
||||
namespace spd = spdlog;
|
||||
int main(int, char*[])
|
||||
{
|
||||
try
|
||||
{
|
||||
// Multithreaded color console
|
||||
auto console = spd::stdout_logger_mt("console", true);
|
||||
console->info("Welcome to spdlog!");
|
||||
console->info("An info message example {}..", 1);
|
||||
|
||||
// Formatting examples
|
||||
console->warn("Easy padding in numbers like {:08d}", 12);
|
||||
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
|
||||
console->info("Support for floats {:03.2f}", 1.23456);
|
||||
console->info("Positional args are {1} {0}..", "too", "supported");
|
||||
|
||||
console->info("{:<30}", "left aligned");
|
||||
console->info("{:>30}", "right aligned");
|
||||
console->info("{:^30}", "centered");
|
||||
|
||||
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
|
||||
|
||||
// Runtime log levels
|
||||
spd::set_level(spd::level::info); //Set global log level to info
|
||||
console->debug("This message shold not be displayed!");
|
||||
console->set_level(spd::level::debug); // Set specific logger's log level
|
||||
console->debug("This message shold be displayed..");
|
||||
|
||||
// Create basic file logger (not rotated)
|
||||
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic.txt");
|
||||
my_logger->info("Some log message");
|
||||
|
||||
|
||||
// Create a file rotating logger with 5mb size max and 3 rotated files
|
||||
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/mylogfile", 1048576 * 5, 3);
|
||||
for (int i = 0; i < 10; ++i)
|
||||
rotating_logger->info("{} * {} equals {:>10}", i, i, i*i);
|
||||
|
||||
// Create a daily logger - a new file is created every day on 2:30am
|
||||
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily", 2, 30);
|
||||
daily_logger->info(123.44);
|
||||
|
||||
// Customize msg format for all messages
|
||||
spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
|
||||
rotating_logger->info("This is another message with custom format");
|
||||
|
||||
// Compile time debug or trace macros.
|
||||
// Enabled #ifdef SPDLOG_DEBUG_ON or #ifdef SPDLOG_TRACE_ON
|
||||
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
|
||||
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
|
||||
|
||||
// Asynchronous logging is very fast..
|
||||
// Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
|
||||
async_example();
|
||||
|
||||
// syslog example. linux/osx only..
|
||||
syslog_example();
|
||||
|
||||
// Log user-defined types example..
|
||||
user_defined_example();
|
||||
|
||||
// Change default log error handler
|
||||
err_handler_example();
|
||||
|
||||
// Apply a function on all registered loggers
|
||||
spd::apply_all([&](std::shared_ptr<spdlog::logger> l) {l->info("End of example."); });
|
||||
|
||||
// Release and close all loggers
|
||||
spdlog::drop_all();
|
||||
}
|
||||
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
|
||||
catch (const spd::spdlog_ex& ex)
|
||||
{
|
||||
std::cout << "Log init failed: " << ex.what() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
void async_example()
|
||||
{
|
||||
size_t q_size = 4096; //queue size must be power of 2
|
||||
spdlog::set_async_mode(q_size);
|
||||
auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
|
||||
for (int i = 0; i < 100; ++i)
|
||||
async_file->info("Async message #{}", i);
|
||||
}
|
||||
|
||||
//syslog example
|
||||
void syslog_example()
|
||||
{
|
||||
#ifdef SPDLOG_ENABLE_SYSLOG
|
||||
std::string ident = "spdlog-example";
|
||||
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
|
||||
syslog_logger->warn("This is warning that will end up in syslog..");
|
||||
#endif
|
||||
}
|
||||
|
||||
// user defined types logging by implementing operator<<
|
||||
struct my_type
|
||||
{
|
||||
int i;
|
||||
template<typename OStream>
|
||||
friend OStream& operator<<(OStream& os, const my_type &c)
|
||||
{
|
||||
return os << "[my_type i="<<c.i << "]";
|
||||
}
|
||||
};
|
||||
|
||||
#include <spdlog/fmt/ostr.h> // must be included
|
||||
void user_defined_example()
|
||||
{
|
||||
spd::get("console")->info("user defined type: {}", my_type { 14 });
|
||||
}
|
||||
|
||||
//
|
||||
//custom error handler
|
||||
//
|
||||
void err_handler_example()
|
||||
{
|
||||
spdlog::set_error_handler([](const std::string& msg) {
|
||||
std::cerr << "my err handler: " << msg << std::endl;
|
||||
});
|
||||
// (or logger->set_error_handler(..) to set for specific logger)
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Documentation can be found in the [wiki](https://github.com/gabime/spdlog/wiki) pages.
|
||||
|
||||
---
|
||||
|
||||
Thanks to [JetBrains](https://www.jetbrains.com/?from=spdlog) for donating product licenses to help develop **spdlog** <a href="https://www.jetbrains.com/?from=spdlog"><img src="logos/jetbrains-variant-4.svg" width="94" align="center" /></a>
|
||||
|
||||
|
||||
Documentation can be found in the [wiki](https://github.com/gabime/spdlog/wiki/1.-QuickStart) pages.
|
||||
|
89
appveyor.yml
89
appveyor.yml
@ -1,89 +0,0 @@
|
||||
version: 1.0.{build}
|
||||
image: Visual Studio 2017
|
||||
environment:
|
||||
matrix:
|
||||
- GENERATOR: '"Visual Studio 15 2017 Win64"'
|
||||
BUILD_TYPE: Debug
|
||||
BUILD_SHARED: 'OFF'
|
||||
FATAL_ERRORS: 'OFF'
|
||||
WCHAR: 'ON'
|
||||
WCHAR_FILES: 'OFF'
|
||||
BUILD_EXAMPLE: 'ON'
|
||||
USE_STD_FORMAT: 'OFF'
|
||||
CXX_STANDARD: 11
|
||||
- GENERATOR: '"Visual Studio 15 2017 Win64"'
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'OFF'
|
||||
FATAL_ERRORS: 'OFF'
|
||||
WCHAR: 'OFF'
|
||||
WCHAR_FILES: 'OFF'
|
||||
BUILD_EXAMPLE: 'ON'
|
||||
USE_STD_FORMAT: 'OFF'
|
||||
CXX_STANDARD: 11
|
||||
- GENERATOR: '"Visual Studio 15 2017 Win64"'
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'ON'
|
||||
FATAL_ERRORS: 'OFF'
|
||||
WCHAR: 'OFF'
|
||||
WCHAR_FILES: 'OFF'
|
||||
BUILD_EXAMPLE: 'ON'
|
||||
USE_STD_FORMAT: 'OFF'
|
||||
CXX_STANDARD: 11
|
||||
- GENERATOR: '"Visual Studio 15 2017 Win64"'
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'ON'
|
||||
FATAL_ERRORS: 'OFF'
|
||||
WCHAR: 'ON'
|
||||
WCHAR_FILES: 'ON'
|
||||
BUILD_EXAMPLE: 'OFF'
|
||||
USE_STD_FORMAT: 'OFF'
|
||||
CXX_STANDARD: 11
|
||||
- GENERATOR: '"Visual Studio 16 2019" -A x64'
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'ON'
|
||||
FATAL_ERRORS: 'ON'
|
||||
WCHAR: 'OFF'
|
||||
WCHAR_FILES: 'OFF'
|
||||
BUILD_EXAMPLE: 'OFF'
|
||||
USE_STD_FORMAT: 'OFF'
|
||||
CXX_STANDARD: 17
|
||||
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
|
||||
- GENERATOR: '"Visual Studio 17 2022" -A x64'
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'ON'
|
||||
FATAL_ERRORS: 'ON'
|
||||
WCHAR: 'OFF'
|
||||
WCHAR_FILES: 'OFF'
|
||||
BUILD_EXAMPLE: 'OFF'
|
||||
USE_STD_FORMAT: 'ON'
|
||||
CXX_STANDARD: 20
|
||||
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2022
|
||||
- GENERATOR: '"Visual Studio 17 2022" -A x64'
|
||||
BUILD_TYPE: Release
|
||||
BUILD_SHARED: 'ON'
|
||||
FATAL_ERRORS: 'ON'
|
||||
WCHAR: 'ON'
|
||||
WCHAR_FILES: 'ON'
|
||||
BUILD_EXAMPLE: 'OFF'
|
||||
USE_STD_FORMAT: 'ON'
|
||||
CXX_STANDARD: 20
|
||||
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2022
|
||||
build_script:
|
||||
- cmd: >-
|
||||
set
|
||||
|
||||
mkdir build
|
||||
|
||||
cd build
|
||||
|
||||
set PATH=%PATH%;C:\Program Files\Git\usr\bin
|
||||
|
||||
cmake -G %GENERATOR% -D CMAKE_BUILD_TYPE=%BUILD_TYPE% -D BUILD_SHARED_LIBS=%BUILD_SHARED% -D SPDLOG_WCHAR_SUPPORT=%WCHAR% -D SPDLOG_WCHAR_FILENAMES=%WCHAR_FILES% -D SPDLOG_BUILD_EXAMPLE=%BUILD_EXAMPLE% -D SPDLOG_BUILD_EXAMPLE_HO=%BUILD_EXAMPLE% -D SPDLOG_BUILD_TESTS=ON -D SPDLOG_BUILD_TESTS_HO=OFF -D SPDLOG_BUILD_WARNINGS=%FATAL_ERRORS% -D SPDLOG_USE_STD_FORMAT=%USE_STD_FORMAT% -D CMAKE_CXX_STANDARD=%CXX_STANDARD% ..
|
||||
|
||||
cmake --build . --config %BUILD_TYPE%
|
||||
|
||||
before_test:
|
||||
- set PATH=%PATH%;C:\projects\spdlog\build\_deps\catch2-build\src\%BUILD_TYPE%;C:\projects\spdlog\build\%BUILD_TYPE%
|
||||
|
||||
test_script:
|
||||
- C:\projects\spdlog\build\tests\%BUILD_TYPE%\spdlog-utests.exe
|
5
astyle.sh
Executable file
5
astyle.sh
Executable file
@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
find . -name "*\.h" -o -name "*\.cpp"|xargs dos2unix
|
||||
find . -name "*\.h" -o -name "*\.cpp"|xargs astyle -n -c -A1
|
||||
|
||||
|
@ -1,37 +0,0 @@
|
||||
# Copyright(c) 2019 spdlog authors Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
cmake_minimum_required(VERSION 3.11)
|
||||
project(spdlog_bench CXX)
|
||||
|
||||
if(NOT TARGET spdlog)
|
||||
# Stand-alone build
|
||||
find_package(spdlog CONFIG REQUIRED)
|
||||
endif()
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(benchmark CONFIG)
|
||||
if(NOT benchmark_FOUND)
|
||||
message(STATUS "Using CMake Version ${CMAKE_VERSION}")
|
||||
# User can fetch googlebenchmark
|
||||
message(STATUS "Downloading GoogleBenchmark")
|
||||
include(FetchContent)
|
||||
|
||||
# disable tests
|
||||
set(BENCHMARK_ENABLE_TESTING OFF CACHE INTERNAL "")
|
||||
# Do not build and run googlebenchmark tests
|
||||
FetchContent_Declare(googlebenchmark GIT_REPOSITORY https://github.com/google/benchmark.git GIT_TAG v1.6.0)
|
||||
FetchContent_MakeAvailable(googlebenchmark)
|
||||
endif()
|
||||
|
||||
add_executable(bench bench.cpp)
|
||||
spdlog_enable_warnings(bench)
|
||||
target_link_libraries(bench PRIVATE spdlog::spdlog)
|
||||
|
||||
add_executable(async_bench async_bench.cpp)
|
||||
target_link_libraries(async_bench PRIVATE spdlog::spdlog)
|
||||
|
||||
add_executable(latency latency.cpp)
|
||||
target_link_libraries(latency PRIVATE benchmark::benchmark spdlog::spdlog)
|
||||
|
||||
add_executable(formatter-bench formatter-bench.cpp)
|
||||
target_link_libraries(formatter-bench PRIVATE benchmark::benchmark spdlog::spdlog)
|
62
bench/Makefile
Normal file
62
bench/Makefile
Normal file
@ -0,0 +1,62 @@
|
||||
CXX ?= g++
|
||||
CXXFLAGS = -march=native -Wall -Wextra -pedantic -std=c++11 -pthread -I../include
|
||||
CXX_RELEASE_FLAGS = -O3 -flto -DNDEBUG
|
||||
|
||||
|
||||
binaries=spdlog-bench spdlog-bench-mt spdlog-async spdlog-null-async boost-bench boost-bench-mt glog-bench glog-bench-mt g2log-async easylogging-bench easylogging-bench-mt
|
||||
|
||||
all: $(binaries)
|
||||
|
||||
spdlog-bench: spdlog-bench.cpp
|
||||
$(CXX) spdlog-bench.cpp -o spdlog-bench $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
spdlog-bench-mt: spdlog-bench-mt.cpp
|
||||
$(CXX) spdlog-bench-mt.cpp -o spdlog-bench-mt $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
spdlog-async: spdlog-async.cpp
|
||||
$(CXX) spdlog-async.cpp -o spdlog-async $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
|
||||
spdlog-null-async: spdlog-null-async.cpp
|
||||
$(CXX) spdlog-null-async.cpp -o spdlog-null-async $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
|
||||
|
||||
BOOST_FLAGS = -DBOOST_LOG_DYN_LINK -I/usr/include -lboost_log -lboost_log_setup -lboost_filesystem -lboost_system -lboost_thread -lboost_regex -lboost_date_time -lboost_chrono
|
||||
|
||||
boost-bench: boost-bench.cpp
|
||||
$(CXX) boost-bench.cpp -o boost-bench $(CXXFLAGS) $(BOOST_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
boost-bench-mt: boost-bench-mt.cpp
|
||||
$(CXX) boost-bench-mt.cpp -o boost-bench-mt $(CXXFLAGS) $(BOOST_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
|
||||
GLOG_FLAGS = -lglog
|
||||
glog-bench: glog-bench.cpp
|
||||
$(CXX) glog-bench.cpp -o glog-bench $(CXXFLAGS) $(GLOG_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
glog-bench-mt: glog-bench-mt.cpp
|
||||
$(CXX) glog-bench-mt.cpp -o glog-bench-mt $(CXXFLAGS) $(GLOG_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
|
||||
G2LOG_FLAGS = -I/home/gabi/devel/g2log/g2log/src -L/home/gabi/devel/g2log/g2log -llib_g2logger
|
||||
g2log-async: g2log-async.cpp
|
||||
$(CXX) g2log-async.cpp -o g2log-async $(CXXFLAGS) $(G2LOG_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
|
||||
EASYL_FLAGS = -I../../easylogging/src/
|
||||
easylogging-bench: easylogging-bench.cpp
|
||||
$(CXX) easylogging-bench.cpp -o easylogging-bench $(CXXFLAGS) $(EASYL_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
easylogging-bench-mt: easylogging-bench-mt.cpp
|
||||
$(CXX) easylogging-bench-mt.cpp -o easylogging-bench-mt $(CXXFLAGS) $(EASYL_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
.PHONY: clean
|
||||
|
||||
clean:
|
||||
rm -f *.o logs/* $(binaries)
|
||||
|
||||
|
||||
rebuild: clean all
|
||||
|
||||
|
||||
|
57
bench/Makefile.mingw
Normal file
57
bench/Makefile.mingw
Normal file
@ -0,0 +1,57 @@
|
||||
CXX ?= g++
|
||||
CXXFLAGS = -D_WIN32_WINNT=0x600 -march=native -Wall -Wextra -pedantic -std=c++11 -pthread -Wl,--no-as-needed -I../include
|
||||
CXX_RELEASE_FLAGS = -O3 -flto
|
||||
|
||||
|
||||
binaries=spdlog-bench spdlog-bench-mt spdlog-async boost-bench boost-bench-mt glog-bench glog-bench-mt g2log-async easylogging-bench easylogging-bench-mt
|
||||
|
||||
all: $(binaries)
|
||||
|
||||
spdlog-bench: spdlog-bench.cpp
|
||||
$(CXX) spdlog-bench.cpp -o spdlog-bench $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
spdlog-bench-mt: spdlog-bench-mt.cpp
|
||||
$(CXX) spdlog-bench-mt.cpp -o spdlog-bench-mt $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
spdlog-async: spdlog-async.cpp
|
||||
$(CXX) spdlog-async.cpp -o spdlog-async $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
|
||||
BOOST_FLAGS = -DBOOST_LOG_DYN_LINK -I/home/gabi/devel/boost_1_56_0/ -L/home/gabi/devel/boost_1_56_0/stage/lib -lboost_log -lboost_log_setup -lboost_filesystem -lboost_system -lboost_thread -lboost_regex -lboost_date_time -lboost_chrono
|
||||
|
||||
boost-bench: boost-bench.cpp
|
||||
$(CXX) boost-bench.cpp -o boost-bench $(CXXFLAGS) $(BOOST_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
boost-bench-mt: boost-bench-mt.cpp
|
||||
$(CXX) boost-bench-mt.cpp -o boost-bench-mt $(CXXFLAGS) $(BOOST_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
|
||||
GLOG_FLAGS = -lglog
|
||||
glog-bench: glog-bench.cpp
|
||||
$(CXX) glog-bench.cpp -o glog-bench $(CXXFLAGS) $(GLOG_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
glog-bench-mt: glog-bench-mt.cpp
|
||||
$(CXX) glog-bench-mt.cpp -o glog-bench-mt $(CXXFLAGS) $(GLOG_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
|
||||
G2LOG_FLAGS = -I/home/gabi/devel/g2log/g2log/src -L/home/gabi/devel/g2log/g2log -llib_g2logger
|
||||
g2log-async: g2log-async.cpp
|
||||
$(CXX) g2log-async.cpp -o g2log-async $(CXXFLAGS) $(G2LOG_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
|
||||
EASYL_FLAGS = -I../../easylogging/src/
|
||||
easylogging-bench: easylogging-bench.cpp
|
||||
$(CXX) easylogging-bench.cpp -o easylogging-bench $(CXXFLAGS) $(EASYL_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
easylogging-bench-mt: easylogging-bench-mt.cpp
|
||||
$(CXX) easylogging-bench-mt.cpp -o easylogging-bench-mt $(CXXFLAGS) $(EASYL_FLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
.PHONY: clean
|
||||
|
||||
clean:
|
||||
rm -f *.o logs/* $(binaries)
|
||||
|
||||
|
||||
rebuild: clean all
|
||||
|
||||
|
||||
|
@ -1,168 +0,0 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
//
|
||||
// bench.cpp : spdlog benchmarks
|
||||
//
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/async.h"
|
||||
#include "spdlog/sinks/basic_file_sink.h"
|
||||
|
||||
#if defined(SPDLOG_USE_STD_FORMAT)
|
||||
#include <format>
|
||||
#elif defined(SPDLOG_FMT_EXTERNAL)
|
||||
#include <fmt/format.h>
|
||||
#else
|
||||
#include "spdlog/fmt/bundled/format.h"
|
||||
#endif
|
||||
|
||||
#include "utils.h"
|
||||
#include <atomic>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
using namespace std;
|
||||
using namespace std::chrono;
|
||||
using namespace spdlog;
|
||||
using namespace spdlog::sinks;
|
||||
using namespace utils;
|
||||
|
||||
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4996) // disable fopen warning under msvc
|
||||
#endif // _MSC_VER
|
||||
|
||||
int count_lines(const char *filename) {
|
||||
int counter = 0;
|
||||
auto *infile = fopen(filename, "r");
|
||||
int ch;
|
||||
while (EOF != (ch = getc(infile))) {
|
||||
if ('\n' == ch) counter++;
|
||||
}
|
||||
fclose(infile);
|
||||
|
||||
return counter;
|
||||
}
|
||||
|
||||
void verify_file(const char *filename, int expected_count) {
|
||||
spdlog::info("Verifying {} to contain {} line..", filename, expected_count);
|
||||
auto count = count_lines(filename);
|
||||
if (count != expected_count) {
|
||||
spdlog::error("Test failed. {} has {} lines instead of {}", filename, count,
|
||||
expected_count);
|
||||
exit(1);
|
||||
}
|
||||
spdlog::info("Line count OK ({})\n", count);
|
||||
}
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
int howmany = 1000000;
|
||||
int queue_size = std::min(howmany + 2, 8192);
|
||||
int threads = 10;
|
||||
int iters = 3;
|
||||
|
||||
try {
|
||||
spdlog::set_pattern("[%^%l%$] %v");
|
||||
if (argc == 1) {
|
||||
spdlog::info("Usage: {} <message_count> <threads> <q_size> <iterations>", argv[0]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (argc > 1) howmany = atoi(argv[1]);
|
||||
if (argc > 2) threads = atoi(argv[2]);
|
||||
if (argc > 3) {
|
||||
queue_size = atoi(argv[3]);
|
||||
if (queue_size > 500000) {
|
||||
spdlog::error("Max queue size allowed: 500,000");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (argc > 4) iters = atoi(argv[4]);
|
||||
|
||||
auto slot_size = sizeof(spdlog::details::async_msg);
|
||||
spdlog::info("-------------------------------------------------");
|
||||
spdlog::info("Messages : {:L}", howmany);
|
||||
spdlog::info("Threads : {:L}", threads);
|
||||
spdlog::info("Queue : {:L} slots", queue_size);
|
||||
spdlog::info("Queue memory : {:L} x {:L} = {:L} KB ", queue_size, slot_size,
|
||||
(queue_size * slot_size) / 1024);
|
||||
spdlog::info("Total iters : {:L}", iters);
|
||||
spdlog::info("-------------------------------------------------");
|
||||
|
||||
const char *filename = "logs/basic_async.log";
|
||||
spdlog::info("");
|
||||
spdlog::info("*********************************");
|
||||
spdlog::info("Queue Overflow Policy: block");
|
||||
spdlog::info("*********************************");
|
||||
for (int i = 0; i < iters; i++) {
|
||||
auto tp = std::make_shared<details::thread_pool>(queue_size, 1);
|
||||
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filename, true);
|
||||
auto logger = std::make_shared<async_logger>(
|
||||
"async_logger", std::move(file_sink), std::move(tp), async_overflow_policy::block);
|
||||
bench_mt(howmany, std::move(logger), threads);
|
||||
// verify_file(filename, howmany);
|
||||
}
|
||||
|
||||
spdlog::info("");
|
||||
spdlog::info("*********************************");
|
||||
spdlog::info("Queue Overflow Policy: overrun");
|
||||
spdlog::info("*********************************");
|
||||
// do same test but discard oldest if queue is full instead of blocking
|
||||
filename = "logs/basic_async-overrun.log";
|
||||
for (int i = 0; i < iters; i++) {
|
||||
auto tp = std::make_shared<details::thread_pool>(queue_size, 1);
|
||||
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filename, true);
|
||||
auto logger =
|
||||
std::make_shared<async_logger>("async_logger", std::move(file_sink), std::move(tp),
|
||||
async_overflow_policy::overrun_oldest);
|
||||
bench_mt(howmany, std::move(logger), threads);
|
||||
}
|
||||
spdlog::shutdown();
|
||||
} catch (std::exception &ex) {
|
||||
std::cerr << "Error: " << ex.what() << std::endl;
|
||||
perror("Last error");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void thread_fun(std::shared_ptr<spdlog::logger> logger, int howmany) {
|
||||
for (int i = 0; i < howmany; i++) {
|
||||
logger->info("Hello logger: msg number {}", i);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> logger, int thread_count) {
|
||||
using std::chrono::high_resolution_clock;
|
||||
vector<std::thread> threads;
|
||||
auto start = high_resolution_clock::now();
|
||||
|
||||
int msgs_per_thread = howmany / thread_count;
|
||||
int msgs_per_thread_mod = howmany % thread_count;
|
||||
for (int t = 0; t < thread_count; ++t) {
|
||||
if (t == 0 && msgs_per_thread_mod)
|
||||
threads.push_back(
|
||||
std::thread(thread_fun, logger, msgs_per_thread + msgs_per_thread_mod));
|
||||
else
|
||||
threads.push_back(std::thread(thread_fun, logger, msgs_per_thread));
|
||||
}
|
||||
|
||||
for (auto &t : threads) {
|
||||
t.join();
|
||||
}
|
||||
|
||||
auto delta = high_resolution_clock::now() - start;
|
||||
auto delta_d = duration_cast<duration<double>>(delta).count();
|
||||
spdlog::info("Elapsed: {} secs\t {:L}/sec", delta_d, int(howmany / delta_d));
|
||||
}
|
246
bench/bench.cpp
246
bench/bench.cpp
@ -1,246 +0,0 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
//
|
||||
// bench.cpp : spdlog benchmarks
|
||||
//
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/sinks/basic_file_sink.h"
|
||||
#include "spdlog/sinks/daily_file_sink.h"
|
||||
#include "spdlog/sinks/null_sink.h"
|
||||
#include "spdlog/sinks/rotating_file_sink.h"
|
||||
|
||||
#if defined(SPDLOG_USE_STD_FORMAT)
|
||||
#include <format>
|
||||
#elif defined(SPDLOG_FMT_EXTERNAL)
|
||||
#include <fmt/format.h>
|
||||
#else
|
||||
#include "spdlog/fmt/bundled/format.h"
|
||||
#endif
|
||||
|
||||
#include "utils.h"
|
||||
#include <atomic>
|
||||
#include <cstdlib> // EXIT_FAILURE
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
void bench(int howmany, std::shared_ptr<spdlog::logger> log);
|
||||
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, size_t thread_count);
|
||||
|
||||
// void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log);
|
||||
// void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log);
|
||||
|
||||
static const size_t file_size = 30 * 1024 * 1024;
|
||||
static const size_t rotating_files = 5;
|
||||
static const int max_threads = 1000;
|
||||
|
||||
void bench_threaded_logging(size_t threads, int iters) {
|
||||
spdlog::info("**************************************************************");
|
||||
spdlog::info(spdlog::fmt_lib::format(
|
||||
std::locale("en_US.UTF-8"), "Multi threaded: {:L} threads, {:L} messages", threads, iters));
|
||||
spdlog::info("**************************************************************");
|
||||
|
||||
auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true);
|
||||
bench_mt(iters, std::move(basic_mt), threads);
|
||||
auto basic_mt_tracing =
|
||||
spdlog::basic_logger_mt("basic_mt/backtrace-on", "logs/basic_mt.log", true);
|
||||
basic_mt_tracing->enable_backtrace(32);
|
||||
bench_mt(iters, std::move(basic_mt_tracing), threads);
|
||||
|
||||
spdlog::info("");
|
||||
auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size,
|
||||
rotating_files);
|
||||
bench_mt(iters, std::move(rotating_mt), threads);
|
||||
auto rotating_mt_tracing = spdlog::rotating_logger_mt(
|
||||
"rotating_mt/backtrace-on", "logs/rotating_mt.log", file_size, rotating_files);
|
||||
rotating_mt_tracing->enable_backtrace(32);
|
||||
bench_mt(iters, std::move(rotating_mt_tracing), threads);
|
||||
|
||||
spdlog::info("");
|
||||
auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log");
|
||||
bench_mt(iters, std::move(daily_mt), threads);
|
||||
auto daily_mt_tracing = spdlog::daily_logger_mt("daily_mt/backtrace-on", "logs/daily_mt.log");
|
||||
daily_mt_tracing->enable_backtrace(32);
|
||||
bench_mt(iters, std::move(daily_mt_tracing), threads);
|
||||
|
||||
spdlog::info("");
|
||||
auto empty_logger = std::make_shared<spdlog::logger>("level-off");
|
||||
empty_logger->set_level(spdlog::level::off);
|
||||
bench(iters, empty_logger);
|
||||
auto empty_logger_tracing = std::make_shared<spdlog::logger>("level-off/backtrace-on");
|
||||
empty_logger_tracing->set_level(spdlog::level::off);
|
||||
empty_logger_tracing->enable_backtrace(32);
|
||||
bench(iters, empty_logger_tracing);
|
||||
}
|
||||
|
||||
void bench_single_threaded(int iters) {
|
||||
spdlog::info("**************************************************************");
|
||||
spdlog::info(
|
||||
spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), "Single threaded: {} messages", iters));
|
||||
spdlog::info("**************************************************************");
|
||||
|
||||
auto basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true);
|
||||
bench(iters, std::move(basic_st));
|
||||
|
||||
auto basic_st_tracing =
|
||||
spdlog::basic_logger_st("basic_st/backtrace-on", "logs/basic_st.log", true);
|
||||
bench(iters, std::move(basic_st_tracing));
|
||||
|
||||
spdlog::info("");
|
||||
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size,
|
||||
rotating_files);
|
||||
bench(iters, std::move(rotating_st));
|
||||
auto rotating_st_tracing = spdlog::rotating_logger_st(
|
||||
"rotating_st/backtrace-on", "logs/rotating_st.log", file_size, rotating_files);
|
||||
rotating_st_tracing->enable_backtrace(32);
|
||||
bench(iters, std::move(rotating_st_tracing));
|
||||
|
||||
spdlog::info("");
|
||||
auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log");
|
||||
bench(iters, std::move(daily_st));
|
||||
auto daily_st_tracing = spdlog::daily_logger_st("daily_st/backtrace-on", "logs/daily_st.log");
|
||||
daily_st_tracing->enable_backtrace(32);
|
||||
bench(iters, std::move(daily_st_tracing));
|
||||
|
||||
spdlog::info("");
|
||||
auto empty_logger = std::make_shared<spdlog::logger>("level-off");
|
||||
empty_logger->set_level(spdlog::level::off);
|
||||
bench(iters, empty_logger);
|
||||
|
||||
auto empty_logger_tracing = std::make_shared<spdlog::logger>("level-off/backtrace-on");
|
||||
empty_logger_tracing->set_level(spdlog::level::off);
|
||||
empty_logger_tracing->enable_backtrace(32);
|
||||
bench(iters, empty_logger_tracing);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
spdlog::set_automatic_registration(false);
|
||||
spdlog::default_logger()->set_pattern("[%^%l%$] %v");
|
||||
int iters = 250000;
|
||||
size_t threads = 4;
|
||||
try {
|
||||
if (argc > 1) {
|
||||
iters = std::stoi(argv[1]);
|
||||
}
|
||||
if (argc > 2) {
|
||||
threads = std::stoul(argv[2]);
|
||||
}
|
||||
|
||||
if (threads > max_threads) {
|
||||
throw std::runtime_error(
|
||||
spdlog::fmt_lib::format("Number of threads exceeds maximum({})", max_threads));
|
||||
}
|
||||
|
||||
bench_single_threaded(iters);
|
||||
bench_threaded_logging(1, iters);
|
||||
bench_threaded_logging(threads, iters);
|
||||
} catch (std::exception &ex) {
|
||||
spdlog::error(ex.what());
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
void bench(int howmany, std::shared_ptr<spdlog::logger> log) {
|
||||
using std::chrono::duration;
|
||||
using std::chrono::duration_cast;
|
||||
using std::chrono::high_resolution_clock;
|
||||
|
||||
auto start = high_resolution_clock::now();
|
||||
for (auto i = 0; i < howmany; ++i) {
|
||||
log->info("Hello logger: msg number {}", i);
|
||||
}
|
||||
|
||||
auto delta = high_resolution_clock::now() - start;
|
||||
auto delta_d = duration_cast<duration<double>>(delta).count();
|
||||
|
||||
spdlog::info(spdlog::fmt_lib::format(std::locale("en_US.UTF-8"),
|
||||
"{:<30} Elapsed: {:0.2f} secs {:>16L}/sec", log->name(),
|
||||
delta_d, size_t(howmany / delta_d)));
|
||||
spdlog::drop(log->name());
|
||||
}
|
||||
|
||||
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, size_t thread_count) {
|
||||
using std::chrono::duration;
|
||||
using std::chrono::duration_cast;
|
||||
using std::chrono::high_resolution_clock;
|
||||
|
||||
std::vector<std::thread> threads;
|
||||
threads.reserve(thread_count);
|
||||
auto start = high_resolution_clock::now();
|
||||
for (size_t t = 0; t < thread_count; ++t) {
|
||||
threads.emplace_back([&]() {
|
||||
for (int j = 0; j < howmany / static_cast<int>(thread_count); j++) {
|
||||
log->info("Hello logger: msg number {}", j);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (auto &t : threads) {
|
||||
t.join();
|
||||
}
|
||||
|
||||
auto delta = high_resolution_clock::now() - start;
|
||||
auto delta_d = duration_cast<duration<double>>(delta).count();
|
||||
spdlog::info(spdlog::fmt_lib::format(std::locale("en_US.UTF-8"),
|
||||
"{:<30} Elapsed: {:0.2f} secs {:>16L}/sec", log->name(),
|
||||
delta_d, size_t(howmany / delta_d)));
|
||||
spdlog::drop(log->name());
|
||||
}
|
||||
|
||||
/*
|
||||
void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log)
|
||||
{
|
||||
using std::chrono::high_resolution_clock;
|
||||
using std::chrono::duration;
|
||||
using std::chrono::duration_cast;
|
||||
|
||||
auto orig_default = spdlog::default_logger();
|
||||
spdlog::set_default_logger(log);
|
||||
auto start = high_resolution_clock::now();
|
||||
for (auto i = 0; i < howmany; ++i)
|
||||
{
|
||||
spdlog::info("Hello logger: msg number {}", i);
|
||||
}
|
||||
|
||||
auto delta = high_resolution_clock::now() - start;
|
||||
auto delta_d = duration_cast<duration<double>>(delta).count();
|
||||
spdlog::drop(log->name());
|
||||
spdlog::set_default_logger(std::move(orig_default));
|
||||
spdlog::info("{:<30} Elapsed: {:0.2f} secs {:>16}/sec", log->name(), delta_d, int(howmany /
|
||||
delta_d));
|
||||
}
|
||||
|
||||
void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log)
|
||||
{
|
||||
using std::chrono::high_resolution_clock;
|
||||
using std::chrono::duration;
|
||||
using std::chrono::duration_cast;
|
||||
|
||||
const char *msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra
|
||||
metus cursus " "lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus
|
||||
volutpat mi, eu consequat sem " "libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam
|
||||
non dapibus eros. Donec fringilla dui sed " "augue pretium, nec scelerisque est maximus. Nullam
|
||||
convallis, sem nec blandit maximus, nisi turpis ornare " "nisl, sit amet volutpat neque massa eu
|
||||
odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis.";
|
||||
|
||||
auto orig_default = spdlog::default_logger();
|
||||
spdlog::set_default_logger(log);
|
||||
auto start = high_resolution_clock::now();
|
||||
for (auto i = 0; i < howmany; ++i)
|
||||
{
|
||||
spdlog::log(spdlog::level::info, msg);
|
||||
}
|
||||
|
||||
auto delta = high_resolution_clock::now() - start;
|
||||
auto delta_d = duration_cast<duration<double>>(delta).count();
|
||||
spdlog::drop(log->name());
|
||||
spdlog::set_default_logger(std::move(orig_default));
|
||||
spdlog::info("{:<30} Elapsed: {:0.2f} secs {:>16}/sec", log->name(), delta_d, int(howmany /
|
||||
delta_d));
|
||||
}
|
||||
|
||||
*/
|
84
bench/boost-bench-mt.cpp
Normal file
84
bench/boost-bench-mt.cpp
Normal file
@ -0,0 +1,84 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
|
||||
#include <boost/log/core.hpp>
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <boost/log/expressions.hpp>
|
||||
#include <boost/log/sinks/text_file_backend.hpp>
|
||||
#include <boost/log/utility/setup/file.hpp>
|
||||
#include <boost/log/utility/setup/common_attributes.hpp>
|
||||
#include <boost/log/sources/severity_logger.hpp>
|
||||
#include <boost/log/sources/record_ostream.hpp>
|
||||
|
||||
namespace logging = boost::log;
|
||||
namespace src = boost::log::sources;
|
||||
namespace sinks = boost::log::sinks;
|
||||
namespace keywords = boost::log::keywords;
|
||||
|
||||
void init()
|
||||
{
|
||||
logging::add_file_log
|
||||
(
|
||||
keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/
|
||||
keywords::auto_flush = false,
|
||||
keywords::format = "[%TimeStamp%]: %Message%"
|
||||
);
|
||||
|
||||
logging::core::get()->set_filter
|
||||
(
|
||||
logging::trivial::severity >= logging::trivial::info
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
int thread_count = 10;
|
||||
if(argc > 1)
|
||||
thread_count = atoi(argv[1]);
|
||||
|
||||
int howmany = 1000000;
|
||||
|
||||
|
||||
init();
|
||||
logging::add_common_attributes();
|
||||
|
||||
|
||||
using namespace logging::trivial;
|
||||
|
||||
src::severity_logger_mt< severity_level > lg;
|
||||
|
||||
std::atomic<int > msg_counter {0};
|
||||
vector<thread> threads;
|
||||
|
||||
for (int t = 0; t < thread_count; ++t)
|
||||
{
|
||||
threads.push_back(std::thread([&]()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int counter = ++msg_counter;
|
||||
if (counter > howmany) break;
|
||||
BOOST_LOG_SEV(lg, info) << "boost message #" << counter << ": This is some text for your pleasure";
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
for(auto &t:threads)
|
||||
{
|
||||
t.join();
|
||||
};
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
48
bench/boost-bench.cpp
Normal file
48
bench/boost-bench.cpp
Normal file
@ -0,0 +1,48 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#include <boost/log/core.hpp>
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <boost/log/expressions.hpp>
|
||||
#include <boost/log/sinks/text_file_backend.hpp>
|
||||
#include <boost/log/utility/setup/file.hpp>
|
||||
#include <boost/log/utility/setup/common_attributes.hpp>
|
||||
#include <boost/log/sources/severity_logger.hpp>
|
||||
#include <boost/log/sources/record_ostream.hpp>
|
||||
|
||||
namespace logging = boost::log;
|
||||
namespace src = boost::log::sources;
|
||||
namespace sinks = boost::log::sinks;
|
||||
namespace keywords = boost::log::keywords;
|
||||
|
||||
void init()
|
||||
{
|
||||
logging::add_file_log
|
||||
(
|
||||
keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/
|
||||
keywords::auto_flush = false,
|
||||
keywords::format = "[%TimeStamp%]: %Message%"
|
||||
);
|
||||
|
||||
logging::core::get()->set_filter
|
||||
(
|
||||
logging::trivial::severity >= logging::trivial::info
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char* [])
|
||||
{
|
||||
int howmany = 1000000;
|
||||
init();
|
||||
logging::add_common_attributes();
|
||||
|
||||
using namespace logging::trivial;
|
||||
src::severity_logger_mt< severity_level > lg;
|
||||
for(int i = 0 ; i < howmany; ++i)
|
||||
BOOST_LOG_SEV(lg, info) << "boost message #" << i << ": This is some text for your pleasure";
|
||||
|
||||
return 0;
|
||||
}
|
10
bench/easyl.conf
Normal file
10
bench/easyl.conf
Normal file
@ -0,0 +1,10 @@
|
||||
* GLOBAL:
|
||||
FORMAT = "[%datetime]: %msg"
|
||||
FILENAME = ./logs/easylogging.log
|
||||
ENABLED = true
|
||||
TO_FILE = true
|
||||
TO_STANDARD_OUTPUT = false
|
||||
MILLISECONDS_WIDTH = 3
|
||||
PERFORMANCE_TRACKING = false
|
||||
MAX_LOG_FILE_SIZE = 10485760
|
||||
Log_Flush_Threshold = 10485760
|
52
bench/easylogging-bench-mt.cpp
Normal file
52
bench/easylogging-bench-mt.cpp
Normal file
@ -0,0 +1,52 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
|
||||
#define _ELPP_THREAD_SAFE
|
||||
#include "easylogging++.h"
|
||||
_INITIALIZE_EASYLOGGINGPP
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
|
||||
int thread_count = 10;
|
||||
if(argc > 1)
|
||||
thread_count = atoi(argv[1]);
|
||||
|
||||
int howmany = 1000000;
|
||||
|
||||
// Load configuration from file
|
||||
el::Configurations conf("easyl.conf");
|
||||
el::Loggers::reconfigureLogger("default", conf);
|
||||
|
||||
std::atomic<int > msg_counter {0};
|
||||
vector<thread> threads;
|
||||
|
||||
for (int t = 0; t < thread_count; ++t)
|
||||
{
|
||||
threads.push_back(std::thread([&]()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int counter = ++msg_counter;
|
||||
if (counter > howmany) break;
|
||||
LOG(INFO) << "easylog message #" << counter << ": This is some text for your pleasure";
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
for(auto &t:threads)
|
||||
{
|
||||
t.join();
|
||||
};
|
||||
|
||||
return 0;
|
||||
}
|
22
bench/easylogging-bench.cpp
Normal file
22
bench/easylogging-bench.cpp
Normal file
@ -0,0 +1,22 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
|
||||
#include "easylogging++.h"
|
||||
|
||||
_INITIALIZE_EASYLOGGINGPP
|
||||
|
||||
int main(int, char* [])
|
||||
{
|
||||
int howmany = 1000000;
|
||||
|
||||
// Load configuration from file
|
||||
el::Configurations conf("easyl.conf");
|
||||
el::Loggers::reconfigureLogger("default", conf);
|
||||
|
||||
for(int i = 0 ; i < howmany; ++i)
|
||||
LOG(INFO) << "easylog message #" << i << ": This is some text for your pleasure";
|
||||
return 0;
|
||||
}
|
@ -1,71 +0,0 @@
|
||||
//
|
||||
// Copyright(c) 2018 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#include "benchmark/benchmark.h"
|
||||
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/pattern_formatter.h"
|
||||
|
||||
void bench_formatter(benchmark::State &state, std::string pattern) {
|
||||
auto formatter = spdlog::details::make_unique<spdlog::pattern_formatter>(pattern);
|
||||
spdlog::memory_buf_t dest;
|
||||
std::string logger_name = "logger-name";
|
||||
const char *text =
|
||||
"Hello. This is some message with length of 80 ";
|
||||
|
||||
spdlog::source_loc source_loc{"a/b/c/d/myfile.cpp", 123, "some_func()"};
|
||||
spdlog::details::log_msg msg(source_loc, logger_name, spdlog::level::info, text);
|
||||
|
||||
for (auto _ : state) {
|
||||
dest.clear();
|
||||
formatter->format(msg, dest);
|
||||
benchmark::DoNotOptimize(dest);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_formatters() {
|
||||
// basic patterns(single flag)
|
||||
std::string all_flags = "+vtPnlLaAbBcCYDmdHIMSefFprRTXzEisg@luioO%";
|
||||
std::vector<std::string> basic_patterns;
|
||||
for (auto &flag : all_flags) {
|
||||
auto pattern = std::string("%") + flag;
|
||||
benchmark::RegisterBenchmark(pattern.c_str(), &bench_formatter, pattern);
|
||||
|
||||
// pattern = std::string("%16") + flag;
|
||||
// benchmark::RegisterBenchmark(pattern.c_str(), &bench_formatter, pattern);
|
||||
//
|
||||
// // bench center padding
|
||||
// pattern = std::string("%=16") + flag;
|
||||
// benchmark::RegisterBenchmark(pattern.c_str(), &bench_formatter, pattern);
|
||||
}
|
||||
|
||||
// complex patterns
|
||||
std::vector<std::string> patterns = {
|
||||
"[%D %X] [%l] [%n] %v",
|
||||
"[%Y-%m-%d %H:%M:%S.%e] [%l] [%n] %v",
|
||||
"[%Y-%m-%d %H:%M:%S.%e] [%l] [%n] [%t] %v",
|
||||
};
|
||||
for (auto &pattern : patterns) {
|
||||
benchmark::RegisterBenchmark(pattern.c_str(), &bench_formatter, pattern)
|
||||
->Iterations(2500000);
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
spdlog::set_pattern("[%^%l%$] %v");
|
||||
if (argc != 2) {
|
||||
spdlog::error("Usage: {} <pattern> (or \"all\" to bench all)", argv[0]);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
std::string pattern = argv[1];
|
||||
if (pattern == "all") {
|
||||
bench_formatters();
|
||||
} else {
|
||||
benchmark::RegisterBenchmark(pattern.c_str(), &bench_formatter, pattern);
|
||||
}
|
||||
benchmark::Initialize(&argc, argv);
|
||||
benchmark::RunSpecifiedBenchmarks();
|
||||
}
|
62
bench/g2log-async.cpp
Normal file
62
bench/g2log-async.cpp
Normal file
@ -0,0 +1,62 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
#include <iostream>
|
||||
#include <chrono>
|
||||
|
||||
#include "g2logworker.h"
|
||||
#include "g2log.h"
|
||||
|
||||
using namespace std;
|
||||
template<typename T> std::string format(const T& value);
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
using namespace std::chrono;
|
||||
using clock=steady_clock;
|
||||
int thread_count = 10;
|
||||
|
||||
if(argc > 1)
|
||||
thread_count = atoi(argv[1]);
|
||||
int howmany = 1000000;
|
||||
|
||||
g2LogWorker g2log(argv[0], "logs");
|
||||
g2::initializeLogging(&g2log);
|
||||
|
||||
|
||||
std::atomic<int > msg_counter {0};
|
||||
vector<thread> threads;
|
||||
auto start = clock::now();
|
||||
for (int t = 0; t < thread_count; ++t)
|
||||
{
|
||||
threads.push_back(std::thread([&]()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int counter = ++msg_counter;
|
||||
if (counter > howmany) break;
|
||||
LOG(INFO) << "g2log message #" << counter << ": This is some text for your pleasure";
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
for(auto &t:threads)
|
||||
{
|
||||
t.join();
|
||||
};
|
||||
|
||||
duration<float> delta = clock::now() - start;
|
||||
float deltaf = delta.count();
|
||||
auto rate = howmany/deltaf;
|
||||
|
||||
cout << "Total: " << howmany << std::endl;
|
||||
cout << "Threads: " << thread_count << std::endl;
|
||||
std::cout << "Delta = " << deltaf << " seconds" << std::endl;
|
||||
std::cout << "Rate = " << rate << "/sec" << std::endl;
|
||||
}
|
50
bench/glog-bench-mt.cpp
Normal file
50
bench/glog-bench-mt.cpp
Normal file
@ -0,0 +1,50 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
|
||||
#include "glog/logging.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
|
||||
int thread_count = 10;
|
||||
if(argc > 1)
|
||||
thread_count = atoi(argv[1]);
|
||||
|
||||
int howmany = 1000000;
|
||||
|
||||
FLAGS_logtostderr = 0;
|
||||
FLAGS_log_dir = "logs";
|
||||
google::InitGoogleLogging(argv[0]);
|
||||
|
||||
std::atomic<int > msg_counter {0};
|
||||
vector<thread> threads;
|
||||
|
||||
for (int t = 0; t < thread_count; ++t)
|
||||
{
|
||||
threads.push_back(std::thread([&]()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int counter = ++msg_counter;
|
||||
if (counter > howmany) break;
|
||||
LOG(INFO) << "glog message #" << counter << ": This is some text for your pleasure";
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
for(auto &t:threads)
|
||||
{
|
||||
t.join();
|
||||
};
|
||||
|
||||
return 0;
|
||||
}
|
21
bench/glog-bench.cpp
Normal file
21
bench/glog-bench.cpp
Normal file
@ -0,0 +1,21 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#include "glog/logging.h"
|
||||
|
||||
|
||||
int main(int, char* argv[])
|
||||
{
|
||||
int howmany = 1000000;
|
||||
|
||||
|
||||
FLAGS_logtostderr = 0;
|
||||
FLAGS_log_dir = "logs";
|
||||
google::InitGoogleLogging(argv[0]);
|
||||
for(int i = 0 ; i < howmany; ++i)
|
||||
LOG(INFO) << "glog message # " << i << ": This is some text for your pleasure";
|
||||
|
||||
return 0;
|
||||
}
|
@ -1,220 +0,0 @@
|
||||
//
|
||||
// Copyright(c) 2018 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
//
|
||||
// latency.cpp : spdlog latency benchmarks
|
||||
//
|
||||
|
||||
#include "benchmark/benchmark.h"
|
||||
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/async.h"
|
||||
#include "spdlog/sinks/basic_file_sink.h"
|
||||
#include "spdlog/sinks/daily_file_sink.h"
|
||||
#include "spdlog/sinks/null_sink.h"
|
||||
#include "spdlog/sinks/rotating_file_sink.h"
|
||||
|
||||
void bench_c_string(benchmark::State &state, std::shared_ptr<spdlog::logger> logger) {
|
||||
const char *msg =
|
||||
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus "
|
||||
"lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, "
|
||||
"eu consequat sem "
|
||||
"libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec "
|
||||
"fringilla dui sed "
|
||||
"augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, "
|
||||
"nisi turpis ornare "
|
||||
"nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue "
|
||||
"nibh turpis duis.";
|
||||
|
||||
for (auto _ : state) {
|
||||
logger->info(msg);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_logger(benchmark::State &state, std::shared_ptr<spdlog::logger> logger) {
|
||||
int i = 0;
|
||||
for (auto _ : state) {
|
||||
logger->info("Hello logger: msg number {}...............", ++i);
|
||||
}
|
||||
}
|
||||
void bench_global_logger(benchmark::State &state, std::shared_ptr<spdlog::logger> logger) {
|
||||
spdlog::set_default_logger(std::move(logger));
|
||||
int i = 0;
|
||||
for (auto _ : state) {
|
||||
spdlog::info("Hello logger: msg number {}...............", ++i);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_disabled_macro(benchmark::State &state, std::shared_ptr<spdlog::logger> logger) {
|
||||
int i = 0;
|
||||
benchmark::DoNotOptimize(i); // prevent unused warnings
|
||||
benchmark::DoNotOptimize(logger); // prevent unused warnings
|
||||
for (auto _ : state) {
|
||||
SPDLOG_LOGGER_DEBUG(logger, "Hello logger: msg number {}...............", i++);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_disabled_macro_global_logger(benchmark::State &state,
|
||||
std::shared_ptr<spdlog::logger> logger) {
|
||||
spdlog::set_default_logger(std::move(logger));
|
||||
int i = 0;
|
||||
benchmark::DoNotOptimize(i); // prevent unused warnings
|
||||
benchmark::DoNotOptimize(logger); // prevent unused warnings
|
||||
for (auto _ : state) {
|
||||
SPDLOG_DEBUG("Hello logger: msg number {}...............", i++);
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef __linux__
|
||||
void bench_dev_null() {
|
||||
auto dev_null_st = spdlog::basic_logger_st("/dev/null_st", "/dev/null");
|
||||
benchmark::RegisterBenchmark("/dev/null_st", bench_logger, std::move(dev_null_st))
|
||||
->UseRealTime();
|
||||
spdlog::drop("/dev/null_st");
|
||||
|
||||
auto dev_null_mt = spdlog::basic_logger_mt("/dev/null_mt", "/dev/null");
|
||||
benchmark::RegisterBenchmark("/dev/null_mt", bench_logger, std::move(dev_null_mt))
|
||||
->UseRealTime();
|
||||
spdlog::drop("/dev/null_mt");
|
||||
}
|
||||
#endif // __linux__
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
using spdlog::sinks::null_sink_mt;
|
||||
using spdlog::sinks::null_sink_st;
|
||||
|
||||
size_t file_size = 30 * 1024 * 1024;
|
||||
size_t rotating_files = 5;
|
||||
int n_threads = benchmark::CPUInfo::Get().num_cpus;
|
||||
|
||||
auto full_bench = argc > 1 && std::string(argv[1]) == "full";
|
||||
|
||||
// disabled loggers
|
||||
auto disabled_logger =
|
||||
std::make_shared<spdlog::logger>("bench", std::make_shared<null_sink_mt>());
|
||||
disabled_logger->set_level(spdlog::level::off);
|
||||
benchmark::RegisterBenchmark("disabled-at-compile-time", bench_disabled_macro, disabled_logger);
|
||||
benchmark::RegisterBenchmark("disabled-at-compile-time (global logger)",
|
||||
bench_disabled_macro_global_logger, disabled_logger);
|
||||
benchmark::RegisterBenchmark("disabled-at-runtime", bench_logger, disabled_logger);
|
||||
benchmark::RegisterBenchmark("disabled-at-runtime (global logger)", bench_global_logger,
|
||||
disabled_logger);
|
||||
// with backtrace of 64
|
||||
auto tracing_disabled_logger =
|
||||
std::make_shared<spdlog::logger>("bench", std::make_shared<null_sink_mt>());
|
||||
tracing_disabled_logger->enable_backtrace(64);
|
||||
benchmark::RegisterBenchmark("disabled-at-runtime/backtrace", bench_logger,
|
||||
tracing_disabled_logger);
|
||||
|
||||
auto null_logger_st =
|
||||
std::make_shared<spdlog::logger>("bench", std::make_shared<null_sink_st>());
|
||||
benchmark::RegisterBenchmark("null_sink_st (500_bytes c_str)", bench_c_string,
|
||||
std::move(null_logger_st));
|
||||
benchmark::RegisterBenchmark("null_sink_st", bench_logger, null_logger_st);
|
||||
benchmark::RegisterBenchmark("null_sink_st (global logger)", bench_global_logger,
|
||||
null_logger_st);
|
||||
// with backtrace of 64
|
||||
auto tracing_null_logger_st =
|
||||
std::make_shared<spdlog::logger>("bench", std::make_shared<null_sink_st>());
|
||||
tracing_null_logger_st->enable_backtrace(64);
|
||||
benchmark::RegisterBenchmark("null_sink_st/backtrace", bench_logger, tracing_null_logger_st);
|
||||
|
||||
#ifdef __linux__
|
||||
bench_dev_null();
|
||||
#endif // __linux__
|
||||
|
||||
if (full_bench) {
|
||||
// basic_st
|
||||
auto basic_st = spdlog::basic_logger_st("basic_st", "latency_logs/basic_st.log", true);
|
||||
benchmark::RegisterBenchmark("basic_st", bench_logger, std::move(basic_st))->UseRealTime();
|
||||
spdlog::drop("basic_st");
|
||||
// with backtrace of 64
|
||||
auto tracing_basic_st =
|
||||
spdlog::basic_logger_st("tracing_basic_st", "latency_logs/tracing_basic_st.log", true);
|
||||
tracing_basic_st->enable_backtrace(64);
|
||||
benchmark::RegisterBenchmark("basic_st/backtrace", bench_logger,
|
||||
std::move(tracing_basic_st))
|
||||
->UseRealTime();
|
||||
spdlog::drop("tracing_basic_st");
|
||||
|
||||
// rotating st
|
||||
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "latency_logs/rotating_st.log",
|
||||
file_size, rotating_files);
|
||||
benchmark::RegisterBenchmark("rotating_st", bench_logger, std::move(rotating_st))
|
||||
->UseRealTime();
|
||||
spdlog::drop("rotating_st");
|
||||
// with backtrace of 64
|
||||
auto tracing_rotating_st = spdlog::rotating_logger_st(
|
||||
"tracing_rotating_st", "latency_logs/tracing_rotating_st.log", file_size,
|
||||
rotating_files);
|
||||
benchmark::RegisterBenchmark("rotating_st/backtrace", bench_logger,
|
||||
std::move(tracing_rotating_st))
|
||||
->UseRealTime();
|
||||
spdlog::drop("tracing_rotating_st");
|
||||
|
||||
// daily st
|
||||
auto daily_st = spdlog::daily_logger_mt("daily_st", "latency_logs/daily_st.log");
|
||||
benchmark::RegisterBenchmark("daily_st", bench_logger, std::move(daily_st))->UseRealTime();
|
||||
spdlog::drop("daily_st");
|
||||
auto tracing_daily_st =
|
||||
spdlog::daily_logger_mt("tracing_daily_st", "latency_logs/daily_st.log");
|
||||
benchmark::RegisterBenchmark("daily_st/backtrace", bench_logger,
|
||||
std::move(tracing_daily_st))
|
||||
->UseRealTime();
|
||||
spdlog::drop("tracing_daily_st");
|
||||
|
||||
//
|
||||
// Multi threaded bench, 10 loggers using same logger concurrently
|
||||
//
|
||||
auto null_logger_mt =
|
||||
std::make_shared<spdlog::logger>("bench", std::make_shared<null_sink_mt>());
|
||||
benchmark::RegisterBenchmark("null_sink_mt", bench_logger, null_logger_mt)
|
||||
->Threads(n_threads)
|
||||
->UseRealTime();
|
||||
|
||||
// basic_mt
|
||||
auto basic_mt = spdlog::basic_logger_mt("basic_mt", "latency_logs/basic_mt.log", true);
|
||||
benchmark::RegisterBenchmark("basic_mt", bench_logger, std::move(basic_mt))
|
||||
->Threads(n_threads)
|
||||
->UseRealTime();
|
||||
spdlog::drop("basic_mt");
|
||||
|
||||
// rotating mt
|
||||
auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "latency_logs/rotating_mt.log",
|
||||
file_size, rotating_files);
|
||||
benchmark::RegisterBenchmark("rotating_mt", bench_logger, std::move(rotating_mt))
|
||||
->Threads(n_threads)
|
||||
->UseRealTime();
|
||||
spdlog::drop("rotating_mt");
|
||||
|
||||
// daily mt
|
||||
auto daily_mt = spdlog::daily_logger_mt("daily_mt", "latency_logs/daily_mt.log");
|
||||
benchmark::RegisterBenchmark("daily_mt", bench_logger, std::move(daily_mt))
|
||||
->Threads(n_threads)
|
||||
->UseRealTime();
|
||||
spdlog::drop("daily_mt");
|
||||
}
|
||||
|
||||
// async
|
||||
auto queue_size = 1024 * 1024 * 3;
|
||||
auto tp = std::make_shared<spdlog::details::thread_pool>(queue_size, 1);
|
||||
auto async_logger = std::make_shared<spdlog::async_logger>(
|
||||
"async_logger", std::make_shared<null_sink_mt>(), std::move(tp),
|
||||
spdlog::async_overflow_policy::overrun_oldest);
|
||||
benchmark::RegisterBenchmark("async_logger", bench_logger, async_logger)
|
||||
->Threads(n_threads)
|
||||
->UseRealTime();
|
||||
|
||||
auto async_logger_tracing = std::make_shared<spdlog::async_logger>(
|
||||
"async_logger_tracing", std::make_shared<null_sink_mt>(), std::move(tp),
|
||||
spdlog::async_overflow_policy::overrun_oldest);
|
||||
async_logger_tracing->enable_backtrace(32);
|
||||
benchmark::RegisterBenchmark("async_logger/tracing", bench_logger, async_logger_tracing)
|
||||
->Threads(n_threads)
|
||||
->UseRealTime();
|
||||
|
||||
benchmark::Initialize(&argc, argv);
|
||||
benchmark::RunSpecifiedBenchmarks();
|
||||
}
|
4
bench/logs/.gitignore
vendored
Normal file
4
bench/logs/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
# Ignore everything in this directory
|
||||
*
|
||||
# Except this file
|
||||
!.gitignore
|
62
bench/spdlog-async.cpp
Normal file
62
bench/spdlog-async.cpp
Normal file
@ -0,0 +1,62 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
#include <iostream>
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
|
||||
using namespace std::chrono;
|
||||
using clock=steady_clock;
|
||||
namespace spd = spdlog;
|
||||
|
||||
int thread_count = 10;
|
||||
if(argc > 1)
|
||||
thread_count = ::atoi(argv[1]);
|
||||
int howmany = 1000000;
|
||||
|
||||
spd::set_async_mode(1048576);
|
||||
auto logger = spdlog::create<spd::sinks::simple_file_sink_mt>("file_logger", "logs/spd-bench-async.txt", false);
|
||||
logger->set_pattern("[%Y-%b-%d %T.%e]: %v");
|
||||
|
||||
|
||||
std::atomic<int > msg_counter {0};
|
||||
vector<thread> threads;
|
||||
auto start = clock::now();
|
||||
for (int t = 0; t < thread_count; ++t)
|
||||
{
|
||||
threads.push_back(std::thread([&]()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int counter = ++msg_counter;
|
||||
if (counter > howmany) break;
|
||||
logger->info("spdlog message #{}: This is some text for your pleasure", counter);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
for(auto &t:threads)
|
||||
{
|
||||
t.join();
|
||||
};
|
||||
|
||||
duration<float> delta = clock::now() - start;
|
||||
float deltaf = delta.count();
|
||||
auto rate = howmany/deltaf;
|
||||
|
||||
cout << "Total: " << howmany << std::endl;
|
||||
cout << "Threads: " << thread_count << std::endl;
|
||||
std::cout << "Delta = " << deltaf << " seconds" << std::endl;
|
||||
std::cout << "Rate = " << rate << "/sec" << std::endl;
|
||||
}
|
55
bench/spdlog-bench-mt.cpp
Normal file
55
bench/spdlog-bench-mt.cpp
Normal file
@ -0,0 +1,55 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
#include <cstdlib>
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
|
||||
int thread_count = 10;
|
||||
if(argc > 1)
|
||||
thread_count = std::atoi(argv[1]);
|
||||
|
||||
int howmany = 1000000;
|
||||
|
||||
namespace spd = spdlog;
|
||||
|
||||
auto logger = spdlog::create<spd::sinks::simple_file_sink_mt>("file_logger", "logs/spd-bench-mt.txt", false);
|
||||
|
||||
logger->set_pattern("[%Y-%b-%d %T.%e]: %v");
|
||||
|
||||
std::atomic<int > msg_counter {0};
|
||||
std::vector<thread> threads;
|
||||
|
||||
for (int t = 0; t < thread_count; ++t)
|
||||
{
|
||||
threads.push_back(std::thread([&]()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int counter = ++msg_counter;
|
||||
if (counter > howmany) break;
|
||||
logger->info("spdlog message #{}: This is some text for your pleasure", counter);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
for(auto &t:threads)
|
||||
{
|
||||
t.join();
|
||||
};
|
||||
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
20
bench/spdlog-bench.cpp
Normal file
20
bench/spdlog-bench.cpp
Normal file
@ -0,0 +1,20 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
|
||||
int main(int, char* [])
|
||||
{
|
||||
int howmany = 1000000;
|
||||
namespace spd = spdlog;
|
||||
///Create a file rotating logger with 5mb size max and 3 rotated files
|
||||
auto logger = spdlog::create<spd::sinks::simple_file_sink_st>("file_logger", "logs/spd-bench-st.txt", false);
|
||||
|
||||
logger->set_pattern("[%Y-%b-%d %T.%e]: %v");
|
||||
for(int i = 0 ; i < howmany; ++i)
|
||||
logger->info("spdlog message #{} : This is some text for your pleasure", i);
|
||||
return 0;
|
||||
}
|
112
bench/spdlog-null-async.cpp
Normal file
112
bench/spdlog-null-async.cpp
Normal file
@ -0,0 +1,112 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
//
|
||||
// bench.cpp : spdlog benchmarks
|
||||
//
|
||||
#include <atomic>
|
||||
#include <cstdlib> // EXIT_FAILURE
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/async_logger.h"
|
||||
#include "spdlog/sinks/null_sink.h"
|
||||
#include "utils.h"
|
||||
|
||||
|
||||
using namespace std;
|
||||
using namespace std::chrono;
|
||||
using namespace spdlog;
|
||||
using namespace spdlog::sinks;
|
||||
using namespace utils;
|
||||
|
||||
|
||||
|
||||
size_t bench_as(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
|
||||
int queue_size = 1048576;
|
||||
int howmany = 1000000;
|
||||
int threads = 10;
|
||||
int iters = 10;
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
if(argc > 1)
|
||||
howmany = atoi(argv[1]);
|
||||
if (argc > 2)
|
||||
threads = atoi(argv[2]);
|
||||
if (argc > 3)
|
||||
queue_size = atoi(argv[3]);
|
||||
|
||||
|
||||
cout << "\n*******************************************************************************\n";
|
||||
cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " messages " << endl;
|
||||
cout << "*******************************************************************************\n";
|
||||
|
||||
spdlog::set_async_mode(queue_size);
|
||||
|
||||
size_t total_rate = 0;
|
||||
|
||||
for(int i = 0; i < iters; ++i)
|
||||
{
|
||||
//auto as = spdlog::daily_logger_st("as", "logs/daily_async");
|
||||
auto as = spdlog::create<null_sink_st>("async(null-sink)");
|
||||
total_rate+= bench_as(howmany, as, threads);
|
||||
spdlog::drop("async(null-sink)");
|
||||
}
|
||||
std::cout << endl;
|
||||
std::cout << "Avg rate: " << format(total_rate/iters) << "/sec" <<std::endl;
|
||||
|
||||
}
|
||||
catch (std::exception &ex)
|
||||
{
|
||||
std::cerr << "Error: " << ex.what() << std::endl;
|
||||
perror("Last error");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//return rate/sec
|
||||
size_t bench_as(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)
|
||||
{
|
||||
cout << log->name() << "...\t\t" << flush;
|
||||
std::atomic<int > msg_counter {0};
|
||||
vector<thread> threads;
|
||||
auto start = system_clock::now();
|
||||
for (int t = 0; t < thread_count; ++t)
|
||||
{
|
||||
threads.push_back(std::thread([&]()
|
||||
{
|
||||
for(;;)
|
||||
{
|
||||
int counter = ++msg_counter;
|
||||
if (counter > howmany) break;
|
||||
log->info("Hello logger: msg number {}", counter);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
for(auto &t:threads)
|
||||
{
|
||||
t.join();
|
||||
};
|
||||
|
||||
|
||||
auto delta = system_clock::now() - start;
|
||||
auto delta_d = duration_cast<duration<double>> (delta).count();
|
||||
auto per_sec = size_t(howmany / delta_d);
|
||||
cout << format(per_sec) << "/sec" << endl;
|
||||
return per_sec;
|
||||
}
|
@ -5,14 +5,16 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <sstream>
|
||||
#include <iomanip>
|
||||
#include <locale>
|
||||
#include <sstream>
|
||||
|
||||
namespace utils {
|
||||
namespace utils
|
||||
{
|
||||
|
||||
template <typename T>
|
||||
inline std::string format(const T &value) {
|
||||
template<typename T>
|
||||
inline std::string format(const T& value)
|
||||
{
|
||||
static std::locale loc("");
|
||||
std::stringstream ss;
|
||||
ss.imbue(loc);
|
||||
@ -20,8 +22,9 @@ inline std::string format(const T &value) {
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
template <>
|
||||
inline std::string format(const double &value) {
|
||||
template<>
|
||||
inline std::string format(const double & value)
|
||||
{
|
||||
static std::locale loc("");
|
||||
std::stringstream ss;
|
||||
ss.imbue(loc);
|
||||
@ -29,4 +32,4 @@ inline std::string format(const double &value) {
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
} // namespace utils
|
||||
}
|
||||
|
24
cmake/Config.cmake.in
Normal file
24
cmake/Config.cmake.in
Normal file
@ -0,0 +1,24 @@
|
||||
# *************************************************************************/
|
||||
# * Copyright (c) 2015 Ruslan Baratov. */
|
||||
# * */
|
||||
# * Permission is hereby granted, free of charge, to any person obtaining */
|
||||
# * a copy of this software and associated documentation files (the */
|
||||
# * "Software"), to deal in the Software without restriction, including */
|
||||
# * without limitation the rights to use, copy, modify, merge, publish, */
|
||||
# * distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
# * permit persons to whom the Software is furnished to do so, subject to */
|
||||
# * the following conditions: */
|
||||
# * */
|
||||
# * The above copyright notice and this permission notice shall be */
|
||||
# * included in all copies or substantial portions of the Software. */
|
||||
# * */
|
||||
# * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
# * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
# * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
|
||||
# * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
# * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
# * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
# * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
# *************************************************************************/
|
||||
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake")
|
@ -1,18 +0,0 @@
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# IDE support for headers
|
||||
# ---------------------------------------------------------------------------------------
|
||||
set(SPDLOG_HEADERS_DIR "${CMAKE_CURRENT_LIST_DIR}/../include")
|
||||
|
||||
file(GLOB SPDLOG_TOP_HEADERS "${SPDLOG_HEADERS_DIR}/spdlog/*.h")
|
||||
file(GLOB SPDLOG_DETAILS_HEADERS "${SPDLOG_HEADERS_DIR}/spdlog/details/*.h")
|
||||
file(GLOB SPDLOG_SINKS_HEADERS "${SPDLOG_HEADERS_DIR}/spdlog/sinks/*.h")
|
||||
file(GLOB SPDLOG_FMT_HEADERS "${SPDLOG_HEADERS_DIR}/spdlog/fmt/*.h")
|
||||
file(GLOB SPDLOG_FMT_BUNDELED_HEADERS "${SPDLOG_HEADERS_DIR}/spdlog/fmt/bundled/*.h")
|
||||
set(SPDLOG_ALL_HEADERS ${SPDLOG_TOP_HEADERS} ${SPDLOG_DETAILS_HEADERS} ${SPDLOG_SINKS_HEADERS} ${SPDLOG_FMT_HEADERS}
|
||||
${SPDLOG_FMT_BUNDELED_HEADERS})
|
||||
|
||||
source_group("Header Files\\spdlog" FILES ${SPDLOG_TOP_HEADERS})
|
||||
source_group("Header Files\\spdlog\\details" FILES ${SPDLOG_DETAILS_HEADERS})
|
||||
source_group("Header Files\\spdlog\\sinks" FILES ${SPDLOG_SINKS_HEADERS})
|
||||
source_group("Header Files\\spdlog\\fmt" FILES ${SPDLOG_FMT_HEADERS})
|
||||
source_group("Header Files\\spdlog\\fmt\\bundled\\" FILES ${SPDLOG_FMT_BUNDELED_HEADERS})
|
258
cmake/pch.h.in
258
cmake/pch.h.in
@ -1,258 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
// details/pattern_formatter-inl.h
|
||||
// fmt/bin_to_hex.h
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <cctype>
|
||||
|
||||
// details/file_helper-inl.h
|
||||
// details/os-inl.h
|
||||
// fmt/bundled/core.h
|
||||
// fmt/bundled/posix.h
|
||||
// logger-inl.h
|
||||
// sinks/daily_file_sink.h
|
||||
// sinks/stdout_sinks.h
|
||||
#include <cstdio>
|
||||
|
||||
// details/os-inl.h
|
||||
// fmt/bundled/posix.h
|
||||
#include <cstdlib>
|
||||
|
||||
// details/os-inl.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// fmt/bundled/core.h
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <cstring>
|
||||
|
||||
// details/os-inl.h
|
||||
// details/os.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/pattern_formatter.h
|
||||
// fmt/bundled/chrono.h
|
||||
// sinks/daily_file_sink.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
#include <ctime>
|
||||
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <climits>
|
||||
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <cwchar>
|
||||
|
||||
// fmt/bundled/format-inl.h
|
||||
// fmt/bundled/format.h
|
||||
#include <cmath>
|
||||
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <cstdarg>
|
||||
|
||||
// details/file_helper-inl.h
|
||||
// fmt/bundled/format.h
|
||||
// fmt/bundled/posix.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
#include <cerrno>
|
||||
|
||||
// details/circular_q.h
|
||||
// details/thread_pool-inl.h
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <cassert>
|
||||
|
||||
// async_logger-inl.h
|
||||
// cfg/helpers-inl.h
|
||||
// log_levels.h
|
||||
// common.h
|
||||
// details/file_helper-inl.h
|
||||
// details/log_msg.h
|
||||
// details/os-inl.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/pattern_formatter.h
|
||||
// details/registry-inl.h
|
||||
// details/registry.h
|
||||
// details/tcp_client-windows.h
|
||||
// details/tcp_client.h
|
||||
// fmt/bundled/core.h
|
||||
// sinks/android_sink.h
|
||||
// sinks/ansicolor_sink.h
|
||||
// sinks/basic_file_sink.h
|
||||
// sinks/daily_file_sink.h
|
||||
// sinks/dup_filter_sink.h
|
||||
// sinks/msvc_sink.h
|
||||
// sinks/ringbuffer_sink.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
// sinks/rotating_file_sink.h
|
||||
// sinks/syslog_sink.h
|
||||
// sinks/tcp_sink.h
|
||||
// sinks/win_eventlog_sink.h
|
||||
// sinks/wincolor_sink.h
|
||||
// spdlog.h:
|
||||
#include <string>
|
||||
|
||||
// cfg/helpers-inl.h
|
||||
// fmt/bundled/chrono.h
|
||||
#include <sstream>
|
||||
|
||||
// fmt/bundled/ostream.h
|
||||
// sinks/ostream_sink.h
|
||||
#include <ostream>
|
||||
|
||||
// cfg/log_levels.h
|
||||
// details/registry-inl.h
|
||||
// details/registry.h
|
||||
#include <unordered_map>
|
||||
|
||||
// details/circular_q.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/pattern_formatter.h
|
||||
// details/thread_pool.h
|
||||
// fmt/bundled/compile.h
|
||||
// logger.h
|
||||
// sinks/dist_sink.h
|
||||
// sinks/ringbuffer_sink.h
|
||||
// sinks/win_eventlog_sink.h
|
||||
#include <vector>
|
||||
|
||||
// details/os-inl.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// sinks/ansicolor_sink.h
|
||||
// sinks/syslog_sink.h
|
||||
// sinks/systemd_sink.h
|
||||
// sinks/wincolor_sink.h
|
||||
#include <array>
|
||||
|
||||
// details/file_helper-inl.h
|
||||
// details/file_helper.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
#include <tuple>
|
||||
|
||||
// details/os-inl.h
|
||||
// fmt/bundled/format.h
|
||||
// fmt/bundled/printf.h
|
||||
#include <limits>
|
||||
|
||||
// common.h
|
||||
// details/backtracer.h
|
||||
// details/null_mutex.h
|
||||
#include <atomic>
|
||||
|
||||
// common.h
|
||||
// details/backtracer.h
|
||||
// details/null_mutex.h
|
||||
#include <locale>
|
||||
|
||||
// common.h
|
||||
#include <initializer_list>
|
||||
|
||||
// common.h
|
||||
#include <exception>
|
||||
|
||||
// common.h
|
||||
// details/fmt_helper.h
|
||||
// fmt/bundled/core.h
|
||||
// fmt/bundled/ranges.h
|
||||
#include <type_traits>
|
||||
|
||||
// cfg/helpers-inl.h
|
||||
// details/null_mutex.h
|
||||
// details/pattern_formatter-inl.h
|
||||
#include <utility>
|
||||
|
||||
// async.h
|
||||
// async_logger-inl.h
|
||||
// common.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/pattern_formatter.h
|
||||
// details/registry-inl.h
|
||||
// details/registry.h
|
||||
// details/thread_pool.h
|
||||
// fmt/bundled/format.h
|
||||
// sinks/ansicolor_sink.h
|
||||
// sinks/base_sink-inl.h
|
||||
// sinks/dist_sink.h
|
||||
// sinks/stdout_sinks-inl.h
|
||||
// sinks/wincolor_sink.h
|
||||
// spdlog.h
|
||||
#include <memory>
|
||||
|
||||
// async.h
|
||||
// common.h
|
||||
// details/backtracer.h
|
||||
// details/periodic_worker.h
|
||||
// details/registry-inl.h
|
||||
// details/registry.h
|
||||
// details/thread_pool.h
|
||||
// sinks/tcp_sink.h
|
||||
// spdlog.h
|
||||
#include <functional>
|
||||
|
||||
// details/mpmc_blocking_q.h
|
||||
// details/periodic_worker.h
|
||||
#include <condition_variable>
|
||||
|
||||
// details/os-inl.h
|
||||
// fmt/bundled/format.h
|
||||
// fmt/bundled/printf.h
|
||||
// sinks/dist_sink.h
|
||||
#include <algorithm>
|
||||
|
||||
// common.h
|
||||
// details/file_helper-inl.h
|
||||
// details/fmt_helper.h
|
||||
// details/os-inl.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/pattern_formatter.h
|
||||
// details/periodic_worker.h
|
||||
// details/registry-inl.h
|
||||
// details/registry.h
|
||||
// details/thread_pool.h
|
||||
// fmt/bundled/chrono.h
|
||||
// sinks/android_sink.h
|
||||
// sinks/daily_file_sink.h
|
||||
// sinks/dup_filter_sink.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
// sinks/rotating_file_sink.h
|
||||
// sinks/tcp_sink.h
|
||||
// spdlog.h
|
||||
#include <chrono>
|
||||
|
||||
// details/file_helper-inl.h
|
||||
// details/os-inl.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/periodic_worker.h
|
||||
// details/thread_pool.h
|
||||
// sinks/android_sink.h
|
||||
#include <thread>
|
||||
|
||||
// async.h
|
||||
// details/backtracer.h
|
||||
// details/console_globals.h
|
||||
// details/mpmc_blocking_q.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/periodic_worker.h
|
||||
// details/registry.h
|
||||
// sinks/android_sink.h
|
||||
// sinks/ansicolor_sink.h
|
||||
// sinks/basic_file_sink.h
|
||||
// sinks/daily_file_sink.h
|
||||
// sinks/dist_sink.h
|
||||
// sinks/dup_filter_sink.h
|
||||
// sinks/msvc_sink.h
|
||||
// sinks/null_sink.h
|
||||
// sinks/ostream_sink.h
|
||||
// sinks/ringbuffer_sink.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
// sinks/rotating_file_sink.h
|
||||
// sinks/tcp_sink.h
|
||||
// sinks/win_eventlog_sink.h
|
||||
// sinks/wincolor_sink.h
|
||||
//
|
||||
// color_sinks.cpp
|
||||
// file_sinks.cpp
|
||||
// spdlog.cpp
|
||||
// stdout_sinks.cpp
|
||||
#include <mutex>
|
||||
|
||||
// spdlog
|
||||
#include <spdlog/common.h>
|
@ -1,13 +1,6 @@
|
||||
prefix=@CMAKE_INSTALL_PREFIX@
|
||||
exec_prefix=${prefix}
|
||||
includedir=@PKG_CONFIG_INCLUDEDIR@
|
||||
libdir=@PKG_CONFIG_LIBDIR@
|
||||
|
||||
Name: lib@PROJECT_NAME@
|
||||
Description: Fast C++ logging library.
|
||||
URL: https://github.com/gabime/@PROJECT_NAME@
|
||||
Version: @SPDLOG_VERSION@
|
||||
CFlags: -I${includedir} @PKG_CONFIG_DEFINES@
|
||||
Libs: -L${libdir} -lspdlog -pthread
|
||||
Requires: @PKG_CONFIG_REQUIRES@
|
||||
|
||||
prefix=@CMAKE_INSTALL_PREFIX@
|
||||
includedir=${prefix}/include
|
||||
|
||||
Name: @PROJECT_NAME@
|
||||
Description: Super fast C++ logging library.
|
||||
Version: @PROJECT_VERSION@
|
||||
|
@ -1,60 +0,0 @@
|
||||
set(CPACK_GENERATOR "TGZ;ZIP" CACHE STRING "Semicolon separated list of generators")
|
||||
|
||||
set(CPACK_INCLUDE_TOPLEVEL_DIRECTORY 0)
|
||||
set(CPACK_INSTALL_CMAKE_PROJECTS "${CMAKE_BINARY_DIR}" "${PROJECT_NAME}" ALL .)
|
||||
|
||||
set(CPACK_PROJECT_URL "https://github.com/gabime/spdlog")
|
||||
set(CPACK_PACKAGE_VENDOR "Gabi Melman")
|
||||
set(CPACK_PACKAGE_CONTACT "Gabi Melman <gmelman1@gmail.com>")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Fast C++ logging library")
|
||||
set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR})
|
||||
set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR})
|
||||
set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH})
|
||||
set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH})
|
||||
if(PROJECT_VERSION_TWEAK)
|
||||
set(CPACK_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION}.${PROJECT_VERSION_TWEAK})
|
||||
endif()
|
||||
set(CPACK_PACKAGE_RELOCATABLE ON CACHE BOOL "Build relocatable package")
|
||||
|
||||
set(CPACK_RPM_PACKAGE_LICENSE "MIT")
|
||||
set(CPACK_RPM_PACKAGE_GROUP "Development/Libraries")
|
||||
set(CPACK_DEBIAN_PACKAGE_SECTION "libs")
|
||||
set(CPACK_RPM_PACKAGE_URL ${CPACK_PROJECT_URL})
|
||||
set(CPACK_DEBIAN_PACKAGE_HOMEPAGE ${CPACK_PROJECT_URL})
|
||||
set(CPACK_RPM_PACKAGE_DESCRIPTION "Very fast, header-only/compiled, C++ logging library.")
|
||||
set(CPACK_DEBIAN_PACKAGE_DESCRIPTION "Very fast, header-only/compiled, C++ logging library.")
|
||||
|
||||
if(CPACK_PACKAGE_NAME)
|
||||
set(CPACK_RPM_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}")
|
||||
set(CPACK_DEBIAN_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}")
|
||||
else()
|
||||
set(CPACK_RPM_FILE_NAME "${PROJECT_NAME}-${CPACK_PACKAGE_VERSION}")
|
||||
set(CPACK_DEBIAN_FILE_NAME "${PROJECT_NAME}-${CPACK_PACKAGE_VERSION}")
|
||||
set(CPACK_RPM_PACKAGE_NAME "${PROJECT_NAME}")
|
||||
set(CPACK_DEBIAN_PACKAGE_NAME "${PROJECT_NAME}")
|
||||
endif()
|
||||
|
||||
if(CPACK_RPM_PACKAGE_RELEASE)
|
||||
set(CPACK_RPM_FILE_NAME "${CPACK_RPM_FILE_NAME}-${CPACK_RPM_PACKAGE_RELEASE}")
|
||||
endif()
|
||||
if(CPACK_DEBIAN_PACKAGE_RELEASE)
|
||||
set(CPACK_DEBIAN_FILE_NAME "${CPACK_DEBIAN_FILE_NAME}-${CPACK_DEBIAN_PACKAGE_RELEASE}")
|
||||
endif()
|
||||
|
||||
if(CPACK_RPM_PACKAGE_ARCHITECTURE)
|
||||
set(CPACK_RPM_FILE_NAME "${CPACK_RPM_FILE_NAME}.${CPACK_RPM_PACKAGE_ARCHITECTURE}")
|
||||
endif()
|
||||
if(CPACK_DEBIAN_PACKAGE_ARCHITECTURE)
|
||||
set(CPACK_DEBIAN_FILE_NAME "${CPACK_DEBIAN_FILE_NAME}.${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}")
|
||||
endif()
|
||||
set(CPACK_RPM_FILE_NAME "${CPACK_RPM_FILE_NAME}.rpm")
|
||||
set(CPACK_DEBIAN_FILE_NAME "${CPACK_DEBIAN_FILE_NAME}.deb")
|
||||
|
||||
if(NOT CPACK_PACKAGE_RELOCATABLE)
|
||||
# Depend on pkgconfig rpm to create the system pkgconfig folder
|
||||
set(CPACK_RPM_PACKAGE_REQUIRES pkgconfig)
|
||||
set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION
|
||||
"${CPACK_PACKAGING_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/pkgconfig")
|
||||
endif()
|
||||
|
||||
include(CPack)
|
@ -1,20 +0,0 @@
|
||||
# Copyright(c) 2019 spdlog authors
|
||||
# Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
@PACKAGE_INIT@
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
set(SPDLOG_FMT_EXTERNAL @SPDLOG_FMT_EXTERNAL@)
|
||||
set(SPDLOG_FMT_EXTERNAL_HO @SPDLOG_FMT_EXTERNAL_HO@)
|
||||
set(config_targets_file @config_targets_file@)
|
||||
|
||||
if(SPDLOG_FMT_EXTERNAL OR SPDLOG_FMT_EXTERNAL_HO)
|
||||
include(CMakeFindDependencyMacro)
|
||||
find_dependency(fmt CONFIG)
|
||||
endif()
|
||||
|
||||
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/${config_targets_file}")
|
||||
|
||||
check_required_components(spdlog)
|
@ -1,73 +0,0 @@
|
||||
# Get spdlog version from include/spdlog/version.h and put it in SPDLOG_VERSION
|
||||
function(spdlog_extract_version)
|
||||
file(READ "${CMAKE_CURRENT_LIST_DIR}/include/spdlog/version.h" file_contents)
|
||||
string(REGEX MATCH "SPDLOG_VER_MAJOR ([0-9]+)" _ "${file_contents}")
|
||||
if(NOT CMAKE_MATCH_COUNT EQUAL 1)
|
||||
message(FATAL_ERROR "Could not extract major version number from spdlog/version.h")
|
||||
endif()
|
||||
set(ver_major ${CMAKE_MATCH_1})
|
||||
|
||||
string(REGEX MATCH "SPDLOG_VER_MINOR ([0-9]+)" _ "${file_contents}")
|
||||
if(NOT CMAKE_MATCH_COUNT EQUAL 1)
|
||||
message(FATAL_ERROR "Could not extract minor version number from spdlog/version.h")
|
||||
endif()
|
||||
|
||||
set(ver_minor ${CMAKE_MATCH_1})
|
||||
string(REGEX MATCH "SPDLOG_VER_PATCH ([0-9]+)" _ "${file_contents}")
|
||||
if(NOT CMAKE_MATCH_COUNT EQUAL 1)
|
||||
message(FATAL_ERROR "Could not extract patch version number from spdlog/version.h")
|
||||
endif()
|
||||
set(ver_patch ${CMAKE_MATCH_1})
|
||||
|
||||
set(SPDLOG_VERSION_MAJOR ${ver_major} PARENT_SCOPE)
|
||||
set(SPDLOG_VERSION_MINOR ${ver_minor} PARENT_SCOPE)
|
||||
set(SPDLOG_VERSION_PATCH ${ver_patch} PARENT_SCOPE)
|
||||
set(SPDLOG_VERSION "${ver_major}.${ver_minor}.${ver_patch}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
# Turn on warnings on the given target
|
||||
function(spdlog_enable_warnings target_name)
|
||||
if(SPDLOG_BUILD_WARNINGS)
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
|
||||
list(APPEND MSVC_OPTIONS "/W3")
|
||||
if(MSVC_VERSION GREATER 1900) # Allow non fatal security warnings for msvc 2015
|
||||
list(APPEND MSVC_OPTIONS "/WX")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
target_compile_options(
|
||||
${target_name}
|
||||
PRIVATE $<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>,$<CXX_COMPILER_ID:GNU>>:
|
||||
-Wall
|
||||
-Wextra
|
||||
-Wconversion
|
||||
-pedantic
|
||||
-Werror
|
||||
-Wfatal-errors>
|
||||
$<$<CXX_COMPILER_ID:MSVC>:${MSVC_OPTIONS}>)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Enable address sanitizer (gcc/clang only)
|
||||
function(spdlog_enable_addr_sanitizer target_name)
|
||||
if(NOT CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
message(FATAL_ERROR "Sanitizer supported only for gcc/clang")
|
||||
endif()
|
||||
message(STATUS "Address sanitizer enabled")
|
||||
target_compile_options(${target_name} PRIVATE -fsanitize=address,undefined)
|
||||
target_compile_options(${target_name} PRIVATE -fno-sanitize=signed-integer-overflow)
|
||||
target_compile_options(${target_name} PRIVATE -fno-sanitize-recover=all)
|
||||
target_compile_options(${target_name} PRIVATE -fno-omit-frame-pointer)
|
||||
target_link_libraries(${target_name} PRIVATE -fsanitize=address,undefined)
|
||||
endfunction()
|
||||
|
||||
# Enable thread sanitizer (gcc/clang only)
|
||||
function(spdlog_enable_thread_sanitizer target_name)
|
||||
if(NOT CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
message(FATAL_ERROR "Sanitizer supported only for gcc/clang")
|
||||
endif()
|
||||
message(STATUS "Thread sanitizer enabled")
|
||||
target_compile_options(${target_name} PRIVATE -fsanitize=thread)
|
||||
target_compile_options(${target_name} PRIVATE -fno-omit-frame-pointer)
|
||||
target_link_libraries(${target_name} PRIVATE -fsanitize=thread)
|
||||
endfunction()
|
@ -1,42 +0,0 @@
|
||||
#define APSTUDIO_READONLY_SYMBOLS
|
||||
#include <windows.h>
|
||||
#undef APSTUDIO_READONLY_SYMBOLS
|
||||
|
||||
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
|
||||
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION @SPDLOG_VERSION_MAJOR@,@SPDLOG_VERSION_MINOR@,@SPDLOG_VERSION_PATCH@,0
|
||||
PRODUCTVERSION @SPDLOG_VERSION_MAJOR@,@SPDLOG_VERSION_MINOR@,@SPDLOG_VERSION_PATCH@,0
|
||||
FILEFLAGSMASK 0x3fL
|
||||
#ifdef _DEBUG
|
||||
FILEFLAGS 0x1L
|
||||
#else
|
||||
FILEFLAGS 0x0L
|
||||
#endif
|
||||
FILEOS 0x40004L
|
||||
FILETYPE 0x2L
|
||||
FILESUBTYPE 0x0L
|
||||
BEGIN
|
||||
BLOCK "StringFileInfo"
|
||||
BEGIN
|
||||
BLOCK "040904b0"
|
||||
BEGIN
|
||||
VALUE "FileDescription", "spdlog dll\0"
|
||||
VALUE "FileVersion", "@SPDLOG_VERSION@.0\0"
|
||||
VALUE "InternalName", "spdlog.dll\0"
|
||||
VALUE "LegalCopyright", "Copyright (C) spdlog\0"
|
||||
VALUE "ProductName", "spdlog\0"
|
||||
VALUE "ProductVersion", "@SPDLOG_VERSION@.0\0"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
BEGIN
|
||||
VALUE "Translation", 0x409, 1200
|
||||
END
|
||||
END
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -1,23 +1,49 @@
|
||||
# Copyright(c) 2019 spdlog authors Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
cmake_minimum_required(VERSION 3.11)
|
||||
project(spdlog_examples CXX)
|
||||
|
||||
if(NOT TARGET spdlog)
|
||||
# Stand-alone build
|
||||
find_package(spdlog REQUIRED)
|
||||
endif()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Example of using pre-compiled library
|
||||
# ---------------------------------------------------------------------------------------
|
||||
add_executable(example example.cpp)
|
||||
target_link_libraries(example PRIVATE spdlog::spdlog $<$<BOOL:${MINGW}>:ws2_32>)
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Example of using header-only library
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if(SPDLOG_BUILD_EXAMPLE_HO)
|
||||
add_executable(example_header_only example.cpp)
|
||||
target_link_libraries(example_header_only PRIVATE spdlog::spdlog_header_only)
|
||||
endif()
|
||||
# *************************************************************************/
|
||||
# * Copyright (c) 2015 Ruslan Baratov. */
|
||||
# * */
|
||||
# * Permission is hereby granted, free of charge, to any person obtaining */
|
||||
# * a copy of this software and associated documentation files (the */
|
||||
# * "Software"), to deal in the Software without restriction, including */
|
||||
# * without limitation the rights to use, copy, modify, merge, publish, */
|
||||
# * distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
# * permit persons to whom the Software is furnished to do so, subject to */
|
||||
# * the following conditions: */
|
||||
# * */
|
||||
# * The above copyright notice and this permission notice shall be */
|
||||
# * included in all copies or substantial portions of the Software. */
|
||||
# * */
|
||||
# * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
# * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
# * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
|
||||
# * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
# * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
# * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
# * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
# *************************************************************************/
|
||||
|
||||
cmake_minimum_required(VERSION 3.0)
|
||||
project(SpdlogExamples)
|
||||
|
||||
if(TARGET spdlog)
|
||||
# Part of the main project
|
||||
add_library(spdlog::spdlog ALIAS spdlog)
|
||||
else()
|
||||
# Stand-alone build
|
||||
find_package(spdlog CONFIG REQUIRED)
|
||||
endif()
|
||||
|
||||
find_package(Threads)
|
||||
|
||||
add_executable(example example.cpp)
|
||||
target_link_libraries(example spdlog::spdlog ${CMAKE_THREAD_LIBS_INIT})
|
||||
|
||||
add_executable(benchmark bench.cpp)
|
||||
target_link_libraries(benchmark spdlog::spdlog ${CMAKE_THREAD_LIBS_INIT})
|
||||
|
||||
add_executable(multisink multisink.cpp)
|
||||
target_link_libraries(multisink spdlog::spdlog ${CMAKE_THREAD_LIBS_INIT})
|
||||
|
||||
enable_testing()
|
||||
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs")
|
||||
add_test(NAME RunExample COMMAND example)
|
||||
add_test(NAME RunBenchmark COMMAND benchmark)
|
||||
|
29
example/Makefile
Normal file
29
example/Makefile
Normal file
@ -0,0 +1,29 @@
|
||||
CXX ?= g++
|
||||
CXXFLAGS =
|
||||
CXX_FLAGS = -Wall -Wshadow -Wextra -pedantic -std=c++11 -pthread -I../include
|
||||
CXX_RELEASE_FLAGS = -O3 -march=native
|
||||
CXX_DEBUG_FLAGS= -g
|
||||
|
||||
|
||||
all: example bench
|
||||
debug: example-debug bench-debug
|
||||
|
||||
example: example.cpp
|
||||
$(CXX) example.cpp -o example $(CXX_FLAGS) $(CXX_RELEASE_FLAGS) $(CXXFLAGS)
|
||||
|
||||
bench: bench.cpp
|
||||
$(CXX) bench.cpp -o bench $(CXX_FLAGS) $(CXX_RELEASE_FLAGS) $(CXXFLAGS)
|
||||
|
||||
|
||||
example-debug: example.cpp
|
||||
$(CXX) example.cpp -o example-debug $(CXX_FLAGS) $(CXX_DEBUG_FLAGS) $(CXXFLAGS)
|
||||
|
||||
bench-debug: bench.cpp
|
||||
$(CXX) bench.cpp -o bench-debug $(CXX_FLAGS) $(CXX_DEBUG_FLAGS) $(CXXFLAGS)
|
||||
|
||||
clean:
|
||||
rm -f *.o logs/*.txt example example-debug bench bench-debug
|
||||
|
||||
|
||||
rebuild: clean all
|
||||
rebuild-debug: clean debug
|
32
example/Makefile.clang
Normal file
32
example/Makefile.clang
Normal file
@ -0,0 +1,32 @@
|
||||
CXX ?= clang++
|
||||
CXXFLAGS = -march=native -Wall -Wextra -Wshadow -pedantic -std=c++11 -pthread -I../include
|
||||
CXX_RELEASE_FLAGS = -O2
|
||||
CXX_DEBUG_FLAGS= -g
|
||||
|
||||
|
||||
all: example bench
|
||||
debug: example-debug bench-debug
|
||||
|
||||
example: example.cpp
|
||||
$(CXX) example.cpp -o example-clang $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
bench: bench.cpp
|
||||
$(CXX) bench.cpp -o bench-clang $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
|
||||
example-debug: example.cpp
|
||||
$(CXX) example.cpp -o example-clang-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS)
|
||||
|
||||
bench-debug: bench.cpp
|
||||
$(CXX) bench.cpp -o bench-clang-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS)
|
||||
|
||||
|
||||
|
||||
clean:
|
||||
rm -f *.o logs/*.txt example-clang example-clang-debug bench-clang bench-clang-debug
|
||||
|
||||
|
||||
rebuild: clean all
|
||||
rebuild-debug: clean debug
|
||||
|
||||
|
32
example/Makefile.mingw
Normal file
32
example/Makefile.mingw
Normal file
@ -0,0 +1,32 @@
|
||||
CXX ?= g++
|
||||
CXXFLAGS = -D_WIN32_WINNT=0x600 -march=native -Wall -Wextra -Wshadow -pedantic -std=c++11 -pthread -Wl,--no-as-needed -I../include
|
||||
CXX_RELEASE_FLAGS = -O3
|
||||
CXX_DEBUG_FLAGS= -g
|
||||
|
||||
|
||||
all: example bench
|
||||
debug: example-debug bench-debug
|
||||
|
||||
example: example.cpp
|
||||
$(CXX) example.cpp -o example $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
bench: bench.cpp
|
||||
$(CXX) bench.cpp -o bench $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
|
||||
|
||||
|
||||
example-debug: example.cpp
|
||||
$(CXX) example.cpp -o example-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS)
|
||||
|
||||
bench-debug: bench.cpp
|
||||
$(CXX) bench.cpp -o bench-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS)
|
||||
|
||||
|
||||
|
||||
clean:
|
||||
rm -f *.o logs/*.txt example example-debug bench bench-debug
|
||||
|
||||
|
||||
rebuild: clean all
|
||||
rebuild-debug: clean debug
|
||||
|
||||
|
144
example/bench.cpp
Normal file
144
example/bench.cpp
Normal file
@ -0,0 +1,144 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
//
|
||||
// bench.cpp : spdlog benchmarks
|
||||
//
|
||||
#include <atomic>
|
||||
#include <cstdlib> // EXIT_FAILURE
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/async_logger.h"
|
||||
#include "spdlog/sinks/file_sinks.h"
|
||||
#include "spdlog/sinks/null_sink.h"
|
||||
#include "utils.h"
|
||||
|
||||
|
||||
using namespace std;
|
||||
using namespace std::chrono;
|
||||
using namespace spdlog;
|
||||
using namespace spdlog::sinks;
|
||||
using namespace utils;
|
||||
|
||||
|
||||
void bench(int howmany, std::shared_ptr<spdlog::logger> log);
|
||||
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
|
||||
int queue_size = 1048576;
|
||||
int howmany = 1000000;
|
||||
int threads = 10;
|
||||
int file_size = 30 * 1024 * 1024;
|
||||
int rotating_files = 5;
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
if(argc > 1)
|
||||
howmany = atoi(argv[1]);
|
||||
if (argc > 2)
|
||||
threads = atoi(argv[2]);
|
||||
if (argc > 3)
|
||||
queue_size = atoi(argv[3]);
|
||||
|
||||
|
||||
cout << "*******************************************************************************\n";
|
||||
cout << "Single thread, " << format(howmany) << " iterations" << endl;
|
||||
cout << "*******************************************************************************\n";
|
||||
|
||||
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st", file_size, rotating_files);
|
||||
bench(howmany, rotating_st);
|
||||
auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st");
|
||||
bench(howmany, daily_st);
|
||||
bench(howmany, spdlog::create<null_sink_st>("null_st"));
|
||||
|
||||
cout << "\n*******************************************************************************\n";
|
||||
cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl;
|
||||
cout << "*******************************************************************************\n";
|
||||
|
||||
auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt", file_size, rotating_files);
|
||||
bench_mt(howmany, rotating_mt, threads);
|
||||
|
||||
|
||||
auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt");
|
||||
bench_mt(howmany, daily_mt, threads);
|
||||
bench(howmany, spdlog::create<null_sink_st>("null_mt"));
|
||||
|
||||
cout << "\n*******************************************************************************\n";
|
||||
cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " iterations " << endl;
|
||||
cout << "*******************************************************************************\n";
|
||||
|
||||
|
||||
spdlog::set_async_mode(queue_size);
|
||||
|
||||
for(int i = 0; i < 3; ++i)
|
||||
{
|
||||
auto as = spdlog::daily_logger_st("as", "logs/daily_async");
|
||||
bench_mt(howmany, as, threads);
|
||||
spdlog::drop("as");
|
||||
}
|
||||
}
|
||||
catch (std::exception &ex)
|
||||
{
|
||||
std::cerr << "Error: " << ex.what() << std::endl;
|
||||
perror("Last error");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
void bench(int howmany, std::shared_ptr<spdlog::logger> log)
|
||||
{
|
||||
cout << log->name() << "...\t\t" << flush;
|
||||
auto start = system_clock::now();
|
||||
for (auto i = 0; i < howmany; ++i)
|
||||
{
|
||||
log->info("Hello logger: msg number {}", i);
|
||||
}
|
||||
|
||||
|
||||
auto delta = system_clock::now() - start;
|
||||
auto delta_d = duration_cast<duration<double>> (delta).count();
|
||||
cout << format(int(howmany / delta_d)) << "/sec" << endl;
|
||||
}
|
||||
|
||||
|
||||
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)
|
||||
{
|
||||
|
||||
cout << log->name() << "...\t\t" << flush;
|
||||
std::atomic<int > msg_counter {0};
|
||||
vector<thread> threads;
|
||||
auto start = system_clock::now();
|
||||
for (int t = 0; t < thread_count; ++t)
|
||||
{
|
||||
threads.push_back(std::thread([&]()
|
||||
{
|
||||
for(;;)
|
||||
{
|
||||
int counter = ++msg_counter;
|
||||
if (counter > howmany) break;
|
||||
log->info("Hello logger: msg number {}", counter);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
for(auto &t:threads)
|
||||
{
|
||||
t.join();
|
||||
};
|
||||
|
||||
|
||||
auto delta = system_clock::now() - start;
|
||||
auto delta_d = duration_cast<duration<double>> (delta).count();
|
||||
cout << format(int(howmany / delta_d)) << "/sec" << endl;
|
||||
}
|
@ -1,403 +1,163 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
//
|
||||
//
|
||||
// spdlog usage example
|
||||
//
|
||||
//
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
void load_levels_example();
|
||||
void stdout_logger_example();
|
||||
void basic_example();
|
||||
void rotating_example();
|
||||
void daily_example();
|
||||
void callback_example();
|
||||
void async_example();
|
||||
void binary_example();
|
||||
void vector_example();
|
||||
void stopwatch_example();
|
||||
void trace_example();
|
||||
void multi_sink_example();
|
||||
void syslog_example();
|
||||
void android_example();
|
||||
void user_defined_example();
|
||||
void err_handler_example();
|
||||
void syslog_example();
|
||||
void udp_example();
|
||||
void custom_flags_example();
|
||||
void file_events_example();
|
||||
void replace_default_logger_example();
|
||||
void mdc_example();
|
||||
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/cfg/env.h" // support for loading levels from the environment variable
|
||||
#include "spdlog/fmt/ostr.h" // support for user defined types
|
||||
namespace spd = spdlog;
|
||||
int main(int, char*[])
|
||||
{
|
||||
try
|
||||
{
|
||||
// Multithreaded color console
|
||||
auto console = spd::stdout_logger_mt("console", true);
|
||||
console->info("Welcome to spdlog!");
|
||||
console->error("An error message example {}..", 1);
|
||||
|
||||
int main(int, char *[]) {
|
||||
// Log levels can be loaded from argv/env using "SPDLOG_LEVEL"
|
||||
load_levels_example();
|
||||
// Formatting examples
|
||||
console->warn("Easy padding in numbers like {:08d}", 12);
|
||||
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
|
||||
console->info("Support for floats {:03.2f}", 1.23456);
|
||||
console->info("Positional args are {1} {0}..", "too", "supported");
|
||||
|
||||
spdlog::info("Welcome to spdlog version {}.{}.{} !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR,
|
||||
SPDLOG_VER_PATCH);
|
||||
console->info("{:<30}", "left aligned");
|
||||
console->info("{:>30}", "right aligned");
|
||||
console->info("{:^30}", "centered");
|
||||
|
||||
spdlog::warn("Easy padding in numbers like {:08d}", 12);
|
||||
spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
|
||||
spdlog::info("Support for floats {:03.2f}", 1.23456);
|
||||
spdlog::info("Positional args are {1} {0}..", "too", "supported");
|
||||
spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left");
|
||||
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
|
||||
|
||||
// Runtime log levels
|
||||
spdlog::set_level(spdlog::level::info); // Set global log level to info
|
||||
spdlog::debug("This message should not be displayed!");
|
||||
spdlog::set_level(spdlog::level::trace); // Set specific logger's log level
|
||||
spdlog::debug("This message should be displayed..");
|
||||
// Runtime log levels
|
||||
spd::set_level(spd::level::info); //Set global log level to info
|
||||
console->debug("This message shold not be displayed!");
|
||||
console->set_level(spd::level::debug); // Set specific logger's log level
|
||||
console->debug("This message shold be displayed..");
|
||||
|
||||
// Customize msg format for all loggers
|
||||
spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v");
|
||||
spdlog::info("This an info message with custom format");
|
||||
spdlog::set_pattern("%+"); // back to default format
|
||||
spdlog::set_level(spdlog::level::info);
|
||||
// Create basic file logger (not rotated)
|
||||
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic.txt");
|
||||
my_logger->info("Some log message");
|
||||
|
||||
// Backtrace support
|
||||
// Loggers can store in a ring buffer all messages (including debug/trace) for later inspection.
|
||||
// When needed, call dump_backtrace() to see what happened:
|
||||
spdlog::enable_backtrace(10); // create ring buffer with capacity of 10 messages
|
||||
for (int i = 0; i < 100; i++) {
|
||||
spdlog::debug("Backtrace message {}", i); // not logged..
|
||||
}
|
||||
// e.g. if some error happened:
|
||||
spdlog::dump_backtrace(); // log them now!
|
||||
// Create a file rotating logger with 5mb size max and 3 rotated files
|
||||
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/mylogfile", 1048576 * 5, 3);
|
||||
for (int i = 0; i < 10; ++i)
|
||||
rotating_logger->info("{} * {} equals {:>10}", i, i, i*i);
|
||||
|
||||
try {
|
||||
stdout_logger_example();
|
||||
basic_example();
|
||||
rotating_example();
|
||||
daily_example();
|
||||
callback_example();
|
||||
// Create a daily logger - a new file is created every day on 2:30am
|
||||
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily", 2, 30);
|
||||
// trigger flush if the log severity is error or higher
|
||||
daily_logger->flush_on(spd::level::err);
|
||||
daily_logger->info(123.44);
|
||||
|
||||
// Customize msg format for all messages
|
||||
spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
|
||||
rotating_logger->info("This is another message with custom format");
|
||||
|
||||
// Compile time debug or trace macros.
|
||||
// Enabled #ifdef SPDLOG_DEBUG_ON or #ifdef SPDLOG_TRACE_ON
|
||||
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
|
||||
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
|
||||
|
||||
// Asynchronous logging is very fast..
|
||||
// Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
|
||||
async_example();
|
||||
binary_example();
|
||||
vector_example();
|
||||
multi_sink_example();
|
||||
|
||||
// syslog example. linux/osx only
|
||||
syslog_example();
|
||||
|
||||
// android example. compile with NDK
|
||||
android_example();
|
||||
|
||||
// Log user-defined types example
|
||||
user_defined_example();
|
||||
|
||||
// Change default log error handler
|
||||
err_handler_example();
|
||||
trace_example();
|
||||
stopwatch_example();
|
||||
udp_example();
|
||||
custom_flags_example();
|
||||
file_events_example();
|
||||
replace_default_logger_example();
|
||||
mdc_example();
|
||||
|
||||
// Flush all *registered* loggers using a worker thread every 3 seconds.
|
||||
// note: registered loggers *must* be thread safe for this to work correctly!
|
||||
spdlog::flush_every(std::chrono::seconds(3));
|
||||
// Apply a function on all registered loggers
|
||||
spd::apply_all([&](std::shared_ptr<spdlog::logger> l)
|
||||
{
|
||||
l->info("End of example.");
|
||||
});
|
||||
|
||||
// Apply some function on all registered loggers
|
||||
spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
|
||||
|
||||
// Release all spdlog resources, and drop all loggers in the registry.
|
||||
// This is optional (only mandatory if using windows + async log).
|
||||
spdlog::shutdown();
|
||||
// Release and close all loggers
|
||||
spdlog::drop_all();
|
||||
}
|
||||
|
||||
// Exceptions will only be thrown upon failed logger or sink construction (not during logging).
|
||||
catch (const spdlog::spdlog_ex &ex) {
|
||||
std::printf("Log initialization failed: %s\n", ex.what());
|
||||
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
|
||||
catch (const spd::spdlog_ex& ex)
|
||||
{
|
||||
std::cout << "Log init failed: " << ex.what() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
#include "spdlog/sinks/stdout_color_sinks.h"
|
||||
// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed.
|
||||
void stdout_logger_example() {
|
||||
// Create color multi threaded logger.
|
||||
auto console = spdlog::stdout_color_mt("console");
|
||||
// or for stderr:
|
||||
// auto console = spdlog::stderr_color_mt("error-logger");
|
||||
}
|
||||
|
||||
#include "spdlog/sinks/basic_file_sink.h"
|
||||
void basic_example() {
|
||||
// Create basic file logger (not rotated).
|
||||
auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt", true);
|
||||
}
|
||||
|
||||
#include "spdlog/sinks/rotating_file_sink.h"
|
||||
void rotating_example() {
|
||||
// Create a file rotating logger with 5mb size max and 3 rotated files.
|
||||
auto rotating_logger =
|
||||
spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
|
||||
}
|
||||
|
||||
#include "spdlog/sinks/daily_file_sink.h"
|
||||
void daily_example() {
|
||||
// Create a daily logger - a new file is created every day on 2:30am.
|
||||
auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
|
||||
}
|
||||
|
||||
#include "spdlog/sinks/callback_sink.h"
|
||||
void callback_example() {
|
||||
// Create the logger
|
||||
auto logger = spdlog::callback_logger_mt("custom_callback_logger",
|
||||
[](const spdlog::details::log_msg & /*msg*/) {
|
||||
// do what you need to do with msg
|
||||
});
|
||||
}
|
||||
|
||||
#include "spdlog/cfg/env.h"
|
||||
void load_levels_example() {
|
||||
// Set the log level to "info" and mylogger to "trace":
|
||||
// SPDLOG_LEVEL=info,mylogger=trace && ./example
|
||||
spdlog::cfg::load_env_levels();
|
||||
// or specify the env variable name:
|
||||
// MYAPP_LEVEL=info,mylogger=trace && ./example
|
||||
// spdlog::cfg::load_env_levels("MYAPP_LEVEL");
|
||||
// or from command line:
|
||||
// ./example SPDLOG_LEVEL=info,mylogger=trace
|
||||
// #include "spdlog/cfg/argv.h" // for loading levels from argv
|
||||
// spdlog::cfg::load_argv_levels(args, argv);
|
||||
}
|
||||
|
||||
#include "spdlog/async.h"
|
||||
void async_example() {
|
||||
// Default thread pool settings can be modified *before* creating the async logger:
|
||||
// spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread.
|
||||
auto async_file =
|
||||
spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt");
|
||||
// alternatively:
|
||||
// auto async_file =
|
||||
// spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("async_file_logger",
|
||||
// "logs/async_log.txt");
|
||||
|
||||
for (int i = 1; i < 101; ++i) {
|
||||
async_file->info("Async message #{}", i);
|
||||
}
|
||||
}
|
||||
|
||||
// Log binary data as hex.
|
||||
// Many types of std::container<char> types can be used.
|
||||
// Iterator ranges are supported too.
|
||||
// Format flags:
|
||||
// {:X} - print in uppercase.
|
||||
// {:s} - don't separate each byte with space.
|
||||
// {:p} - don't print the position on each line start.
|
||||
// {:n} - don't split the output to lines.
|
||||
|
||||
#if !defined SPDLOG_USE_STD_FORMAT || defined(_MSC_VER)
|
||||
#include "spdlog/fmt/bin_to_hex.h"
|
||||
void binary_example() {
|
||||
std::vector<char> buf;
|
||||
for (int i = 0; i < 80; i++) {
|
||||
buf.push_back(static_cast<char>(i & 0xff));
|
||||
}
|
||||
spdlog::info("Binary example: {}", spdlog::to_hex(buf));
|
||||
spdlog::info("Another binary example:{:n}",
|
||||
spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
|
||||
// more examples:
|
||||
// logger->info("uppercase: {:X}", spdlog::to_hex(buf));
|
||||
// logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
|
||||
// logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
|
||||
// logger->info("hexdump style: {:a}", spdlog::to_hex(buf));
|
||||
// logger->info("hexdump style, 20 chars per line {:a}", spdlog::to_hex(buf, 20));
|
||||
}
|
||||
#else
|
||||
void binary_example() {
|
||||
// not supported with std::format yet
|
||||
}
|
||||
#endif
|
||||
|
||||
// Log a vector of numbers
|
||||
#ifndef SPDLOG_USE_STD_FORMAT
|
||||
#include "spdlog/fmt/ranges.h"
|
||||
void vector_example() {
|
||||
std::vector<int> vec = {1, 2, 3};
|
||||
spdlog::info("Vector example: {}", vec);
|
||||
}
|
||||
|
||||
#else
|
||||
void vector_example() {}
|
||||
#endif
|
||||
|
||||
// ! DSPDLOG_USE_STD_FORMAT
|
||||
|
||||
// Compile time log levels.
|
||||
// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE)
|
||||
void trace_example() {
|
||||
// trace from default logger
|
||||
SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23);
|
||||
// debug from default logger
|
||||
SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23);
|
||||
|
||||
// trace from logger object
|
||||
auto logger = spdlog::get("file_logger");
|
||||
SPDLOG_LOGGER_TRACE(logger, "another trace message");
|
||||
}
|
||||
|
||||
// stopwatch example
|
||||
#include "spdlog/stopwatch.h"
|
||||
#include <thread>
|
||||
void stopwatch_example() {
|
||||
spdlog::stopwatch sw;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(123));
|
||||
spdlog::info("Stopwatch: {} seconds", sw);
|
||||
}
|
||||
|
||||
#include "spdlog/sinks/udp_sink.h"
|
||||
void udp_example() {
|
||||
spdlog::sinks::udp_sink_config cfg("127.0.0.1", 11091);
|
||||
auto my_logger = spdlog::udp_logger_mt("udplog", cfg);
|
||||
my_logger->set_level(spdlog::level::debug);
|
||||
my_logger->info("hello world");
|
||||
}
|
||||
|
||||
// A logger with multiple sinks (stdout and file) - each with a different format and log level.
|
||||
void multi_sink_example() {
|
||||
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
|
||||
console_sink->set_level(spdlog::level::warn);
|
||||
console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v");
|
||||
|
||||
auto file_sink =
|
||||
std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/multisink.txt", true);
|
||||
file_sink->set_level(spdlog::level::trace);
|
||||
|
||||
spdlog::logger logger("multi_sink", {console_sink, file_sink});
|
||||
logger.set_level(spdlog::level::debug);
|
||||
logger.warn("this should appear in both console and file");
|
||||
logger.info("this message should not appear in the console, only in the file");
|
||||
}
|
||||
|
||||
// User defined types logging
|
||||
struct my_type {
|
||||
int i = 0;
|
||||
explicit my_type(int i)
|
||||
: i(i){}
|
||||
};
|
||||
|
||||
#ifndef SPDLOG_USE_STD_FORMAT // when using fmtlib
|
||||
template <>
|
||||
struct fmt::formatter<my_type> : fmt::formatter<std::string> {
|
||||
auto format(my_type my, format_context &ctx) const -> decltype(ctx.out()) {
|
||||
return fmt::format_to(ctx.out(), "[my_type i={}]", my.i);
|
||||
}
|
||||
};
|
||||
|
||||
#else // when using std::format
|
||||
template <>
|
||||
struct std::formatter<my_type> : std::formatter<std::string> {
|
||||
auto format(my_type my, format_context &ctx) const -> decltype(ctx.out()) {
|
||||
return std::format_to(ctx.out(), "[my_type i={}]", my.i);
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
void user_defined_example() { spdlog::info("user defined type: {}", my_type(14)); }
|
||||
|
||||
// Custom error handler. Will be triggered on log failure.
|
||||
void err_handler_example() {
|
||||
// can be set globally or per logger(logger->set_error_handler(..))
|
||||
spdlog::set_error_handler([](const std::string &msg) {
|
||||
printf("*** Custom log error handler: %s ***\n", msg.c_str());
|
||||
});
|
||||
}
|
||||
|
||||
// syslog example (linux/osx/freebsd)
|
||||
#ifndef _WIN32
|
||||
#include "spdlog/sinks/syslog_sink.h"
|
||||
void syslog_example() {
|
||||
std::string ident = "spdlog-example";
|
||||
auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID);
|
||||
syslog_logger->warn("This is warning that will end up in syslog.");
|
||||
}
|
||||
#endif
|
||||
|
||||
// Android example.
|
||||
#if defined(__ANDROID__)
|
||||
#include "spdlog/sinks/android_sink.h"
|
||||
void android_example() {
|
||||
std::string tag = "spdlog-android";
|
||||
auto android_logger = spdlog::android_logger_mt("android", tag);
|
||||
android_logger->critical("Use \"adb shell logcat\" to view this message.");
|
||||
}
|
||||
#endif
|
||||
|
||||
// Log patterns can contain custom flags.
|
||||
// this will add custom flag '%*' which will be bound to a <my_formatter_flag> instance
|
||||
#include "spdlog/pattern_formatter.h"
|
||||
class my_formatter_flag : public spdlog::custom_flag_formatter {
|
||||
public:
|
||||
void format(const spdlog::details::log_msg &,
|
||||
const std::tm &,
|
||||
spdlog::memory_buf_t &dest) override {
|
||||
std::string some_txt = "custom-flag";
|
||||
dest.append(some_txt.data(), some_txt.data() + some_txt.size());
|
||||
}
|
||||
|
||||
std::unique_ptr<custom_flag_formatter> clone() const override {
|
||||
return spdlog::details::make_unique<my_formatter_flag>();
|
||||
}
|
||||
};
|
||||
|
||||
void custom_flags_example() {
|
||||
using spdlog::details::make_unique; // for pre c++14
|
||||
auto formatter = make_unique<spdlog::pattern_formatter>();
|
||||
formatter->add_flag<my_formatter_flag>('*').set_pattern("[%n] [%*] [%^%l%$] %v");
|
||||
// set the new formatter using spdlog::set_formatter(formatter) or
|
||||
// logger->set_formatter(formatter) spdlog::set_formatter(std::move(formatter));
|
||||
}
|
||||
|
||||
void file_events_example() {
|
||||
// pass the spdlog::file_event_handlers to file sinks for open/close log file notifications
|
||||
spdlog::file_event_handlers handlers;
|
||||
handlers.before_open = [](spdlog::filename_t filename) {
|
||||
spdlog::info("Before opening {}", filename);
|
||||
};
|
||||
handlers.after_open = [](spdlog::filename_t filename, std::FILE *fstream) {
|
||||
spdlog::info("After opening {}", filename);
|
||||
fputs("After opening\n", fstream);
|
||||
};
|
||||
handlers.before_close = [](spdlog::filename_t filename, std::FILE *fstream) {
|
||||
spdlog::info("Before closing {}", filename);
|
||||
fputs("Before closing\n", fstream);
|
||||
};
|
||||
handlers.after_close = [](spdlog::filename_t filename) {
|
||||
spdlog::info("After closing {}", filename);
|
||||
};
|
||||
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/events-sample.txt",
|
||||
true, handlers);
|
||||
spdlog::logger my_logger("some_logger", file_sink);
|
||||
my_logger.info("Some log line");
|
||||
}
|
||||
|
||||
void replace_default_logger_example() {
|
||||
// store the old logger so we don't break other examples.
|
||||
auto old_logger = spdlog::default_logger();
|
||||
|
||||
auto new_logger =
|
||||
spdlog::basic_logger_mt("new_default_logger", "logs/new-default-log.txt", true);
|
||||
spdlog::set_default_logger(new_logger);
|
||||
spdlog::set_level(spdlog::level::info);
|
||||
spdlog::debug("This message should not be displayed!");
|
||||
spdlog::set_level(spdlog::level::trace);
|
||||
spdlog::debug("This message should be displayed..");
|
||||
|
||||
spdlog::set_default_logger(old_logger);
|
||||
}
|
||||
|
||||
// Mapped Diagnostic Context (MDC) is a map that stores key-value pairs (string values) in thread local storage.
|
||||
// Each thread maintains its own MDC, which loggers use to append diagnostic information to log outputs.
|
||||
// Note: it is not supported in asynchronous mode due to its reliance on thread-local storage.
|
||||
|
||||
#ifndef SPDLOG_NO_TLS
|
||||
#include "spdlog/mdc.h"
|
||||
void mdc_example()
|
||||
void async_example()
|
||||
{
|
||||
spdlog::mdc::put("key1", "value1");
|
||||
spdlog::mdc::put("key2", "value2");
|
||||
// if not using the default format, you can use the %& formatter to print mdc data as well
|
||||
spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [%&] %v");
|
||||
spdlog::info("Some log message with context");
|
||||
}
|
||||
#else
|
||||
void mdc_example() {
|
||||
// if TLS feature is disabled
|
||||
size_t q_size = 4096; //queue size must be power of 2
|
||||
spdlog::set_async_mode(q_size);
|
||||
auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
|
||||
|
||||
for (int i = 0; i < 100; ++i)
|
||||
async_file->info("Async message #{}", i);
|
||||
}
|
||||
|
||||
//syslog example (linux/osx/freebsd)
|
||||
void syslog_example()
|
||||
{
|
||||
#ifdef SPDLOG_ENABLE_SYSLOG
|
||||
std::string ident = "spdlog-example";
|
||||
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
|
||||
syslog_logger->warn("This is warning that will end up in syslog.");
|
||||
#endif
|
||||
}
|
||||
|
||||
// Android example
|
||||
void android_example()
|
||||
{
|
||||
#if defined(__ANDROID__)
|
||||
std::string tag = "spdlog-android";
|
||||
auto android_logger = spd::android_logger("android", tag);
|
||||
android_logger->critical("Use \"adb shell logcat\" to view this message.");
|
||||
#endif
|
||||
}
|
||||
|
||||
// user defined types logging by implementing operator<<
|
||||
struct my_type
|
||||
{
|
||||
int i;
|
||||
template<typename OStream>
|
||||
friend OStream& operator<<(OStream& os, const my_type &c)
|
||||
{
|
||||
return os << "[my_type i="<<c.i << "]";
|
||||
}
|
||||
};
|
||||
|
||||
#include <spdlog/fmt/ostr.h> // must be included
|
||||
void user_defined_example()
|
||||
{
|
||||
spd::get("console")->info("user defined type: {}", my_type { 14 });
|
||||
}
|
||||
|
||||
//
|
||||
//custom error handler
|
||||
//
|
||||
void err_handler_example()
|
||||
{
|
||||
//can be set globaly or per logger(logger->set_error_handler(..))
|
||||
spdlog::set_error_handler([](const std::string& msg)
|
||||
{
|
||||
std::cerr << "my err handler: " << msg << std::endl;
|
||||
});
|
||||
spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
|
||||
}
|
||||
|
26
example/example.sln
Normal file
26
example/example.sln
Normal file
@ -0,0 +1,26 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 14
|
||||
VisualStudioVersion = 14.0.25420.1
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example", "example.vcxproj", "{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Win32 = Debug|Win32
|
||||
Debug|x64 = Debug|x64
|
||||
Release|Win32 = Release|Win32
|
||||
Release|x64 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Debug|x64.ActiveCfg = Debug|Win32
|
||||
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Release|Win32.Build.0 = Release|Win32
|
||||
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Release|x64.ActiveCfg = Release|Win32
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
125
example/example.vcxproj
Normal file
125
example/example.vcxproj
Normal file
@ -0,0 +1,125 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="example.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\include\spdlog\async_logger.h" />
|
||||
<ClInclude Include="..\include\spdlog\common.h" />
|
||||
<ClInclude Include="..\include\spdlog\details\async_logger_impl.h" />
|
||||
<ClInclude Include="..\include\spdlog\details\async_log_helper.h" />
|
||||
<ClInclude Include="..\include\spdlog\details\file_helper.h" />
|
||||
<ClInclude Include="..\include\spdlog\details\logger_impl.h" />
|
||||
<ClInclude Include="..\include\spdlog\details\log_msg.h" />
|
||||
<ClInclude Include="..\include\spdlog\details\mpmc_bounded_q.h" />
|
||||
<ClInclude Include="..\include\spdlog\details\null_mutex.h" />
|
||||
<ClInclude Include="..\include\spdlog\details\os.h" />
|
||||
<ClInclude Include="..\include\spdlog\details\pattern_formatter_impl.h" />
|
||||
<ClInclude Include="..\include\spdlog\details\registry.h" />
|
||||
<ClInclude Include="..\include\spdlog\details\spdlog_impl.h" />
|
||||
<ClInclude Include="..\include\spdlog\fmt\fmt.h" />
|
||||
<ClInclude Include="..\include\spdlog\fmt\ostr.h" />
|
||||
<ClInclude Include="..\include\spdlog\formatter.h" />
|
||||
<ClInclude Include="..\include\spdlog\logger.h" />
|
||||
<ClInclude Include="..\include\spdlog\sinks\android_sink.h" />
|
||||
<ClInclude Include="..\include\spdlog\sinks\ansicolor_sink.h" />
|
||||
<ClInclude Include="..\include\spdlog\sinks\base_sink.h" />
|
||||
<ClInclude Include="..\include\spdlog\sinks\dist_sink.h" />
|
||||
<ClInclude Include="..\include\spdlog\sinks\file_sinks.h" />
|
||||
<ClInclude Include="..\include\spdlog\sinks\msvc_sink.h" />
|
||||
<ClInclude Include="..\include\spdlog\sinks\null_sink.h" />
|
||||
<ClInclude Include="..\include\spdlog\sinks\ostream_sink.h" />
|
||||
<ClInclude Include="..\include\spdlog\sinks\sink.h" />
|
||||
<ClInclude Include="..\include\spdlog\sinks\stdout_sinks.h" />
|
||||
<ClInclude Include="..\include\spdlog\sinks\syslog_sink.h" />
|
||||
<ClInclude Include="..\include\spdlog\spdlog.h" />
|
||||
<ClInclude Include="..\include\spdlog\tweakme.h" />
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}</ProjectGuid>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
<RootNamespace>.</RootNamespace>
|
||||
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PrecompiledHeaderFile />
|
||||
<PrecompiledHeaderOutputFile />
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PrecompiledHeaderFile />
|
||||
<PrecompiledHeaderOutputFile />
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
15
example/jni/Android.mk
Normal file
15
example/jni/Android.mk
Normal file
@ -0,0 +1,15 @@
|
||||
# Setup a project
|
||||
LOCAL_PATH := $(call my-dir)
|
||||
include $(CLEAR_VARS)
|
||||
|
||||
LOCAL_MODULE := example
|
||||
LOCAL_SRC_FILES := example.cpp
|
||||
LOCAL_CPPFLAGS += -Wall -Wshadow -Wextra -pedantic -std=c++11 -fPIE -pie
|
||||
LOCAL_LDFLAGS += -fPIE -pie
|
||||
|
||||
# Add exception support and set path for spdlog's headers
|
||||
LOCAL_CPPFLAGS += -fexceptions -I../include
|
||||
# Use android's log library
|
||||
LOCAL_LDFLAGS += -llog
|
||||
|
||||
include $(BUILD_EXECUTABLE)
|
2
example/jni/Application.mk
Normal file
2
example/jni/Application.mk
Normal file
@ -0,0 +1,2 @@
|
||||
# Exceptions are used in spdlog. Link to an exception-ready C++ runtime.
|
||||
APP_STL = gnustl_static
|
1
example/jni/example.cpp
Symbolic link
1
example/jni/example.cpp
Symbolic link
@ -0,0 +1 @@
|
||||
../example.cpp
|
1
example/logs/.gitignore
vendored
Normal file
1
example/logs/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
*.txt
|
47
example/multisink.cpp
Normal file
47
example/multisink.cpp
Normal file
@ -0,0 +1,47 @@
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
namespace spd = spdlog;
|
||||
int main(int, char*[])
|
||||
{
|
||||
bool enable_debug = true;
|
||||
try
|
||||
{
|
||||
// This other example use a single logger with multiple sinks.
|
||||
// This means that the same log_msg is forwarded to multiple sinks;
|
||||
// Each sink can have it's own log level and a message will be logged.
|
||||
std::vector<spdlog::sink_ptr> sinks;
|
||||
sinks.push_back( std::make_shared<spdlog::sinks::stdout_sink_mt>() );
|
||||
sinks.push_back( std::make_shared<spdlog::sinks::simple_file_sink_mt>("./log_regular_file.txt") );
|
||||
sinks.push_back( std::make_shared<spdlog::sinks::simple_file_sink_mt>("./log_debug_file.txt") );
|
||||
|
||||
spdlog::logger console_multisink("multisink", sinks.begin(), sinks.end() );
|
||||
console_multisink.set_level( spdlog::level::warn);
|
||||
|
||||
sinks[0]->set_level( spdlog::level::trace); // console. Allow everything. Default value
|
||||
sinks[1]->set_level( spdlog::level::trace); // regular file. Allow everything. Default value
|
||||
sinks[2]->set_level( spdlog::level::off); // regular file. Ignore everything.
|
||||
|
||||
console_multisink.warn("warn: will print only on console and regular file");
|
||||
|
||||
if( enable_debug )
|
||||
{
|
||||
console_multisink.set_level( spdlog::level::debug); // level of the logger
|
||||
sinks[1]->set_level( spdlog::level::debug); // regular file
|
||||
sinks[2]->set_level( spdlog::level::debug); // debug file
|
||||
}
|
||||
console_multisink.debug("Debug: you should see this on console and both files");
|
||||
|
||||
// Release and close all loggers
|
||||
spdlog::drop_all();
|
||||
}
|
||||
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
|
||||
catch (const spd::spdlog_ex& ex)
|
||||
{
|
||||
std::cout << "Log init failed: " << ex.what() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
35
example/utils.h
Normal file
35
example/utils.h
Normal file
@ -0,0 +1,35 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <sstream>
|
||||
#include <iomanip>
|
||||
#include <locale>
|
||||
|
||||
namespace utils
|
||||
{
|
||||
|
||||
template<typename T>
|
||||
inline std::string format(const T& value)
|
||||
{
|
||||
static std::locale loc("");
|
||||
std::stringstream ss;
|
||||
ss.imbue(loc);
|
||||
ss << value;
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
template<>
|
||||
inline std::string format(const double & value)
|
||||
{
|
||||
static std::locale loc("");
|
||||
std::stringstream ss;
|
||||
ss.imbue(loc);
|
||||
ss << std::fixed << std::setprecision(1) << value;
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
}
|
@ -1,100 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
//
|
||||
// Async logging using global thread pool
|
||||
// All loggers created here share same global thread pool.
|
||||
// Each log message is pushed to a queue along with a shared pointer to the
|
||||
// logger.
|
||||
// If a logger deleted while having pending messages in the queue, it's actual
|
||||
// destruction will defer
|
||||
// until all its messages are processed by the thread pool.
|
||||
// This is because each message in the queue holds a shared_ptr to the
|
||||
// originating logger.
|
||||
|
||||
#include <spdlog/async_logger.h>
|
||||
#include <spdlog/details/registry.h>
|
||||
#include <spdlog/details/thread_pool.h>
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
namespace spdlog {
|
||||
|
||||
namespace details {
|
||||
static const size_t default_async_q_size = 8192;
|
||||
}
|
||||
|
||||
// async logger factory - creates async loggers backed with thread pool.
|
||||
// if a global thread pool doesn't already exist, create it with default queue
|
||||
// size of 8192 items and single thread.
|
||||
template <async_overflow_policy OverflowPolicy = async_overflow_policy::block>
|
||||
struct async_factory_impl {
|
||||
template <typename Sink, typename... SinkArgs>
|
||||
static std::shared_ptr<async_logger> create(std::string logger_name, SinkArgs &&...args) {
|
||||
auto ®istry_inst = details::registry::instance();
|
||||
|
||||
// create global thread pool if not already exists..
|
||||
|
||||
auto &mutex = registry_inst.tp_mutex();
|
||||
std::lock_guard<std::recursive_mutex> tp_lock(mutex);
|
||||
auto tp = registry_inst.get_tp();
|
||||
if (tp == nullptr) {
|
||||
tp = std::make_shared<details::thread_pool>(details::default_async_q_size, 1U);
|
||||
registry_inst.set_tp(tp);
|
||||
}
|
||||
|
||||
auto sink = std::make_shared<Sink>(std::forward<SinkArgs>(args)...);
|
||||
auto new_logger = std::make_shared<async_logger>(std::move(logger_name), std::move(sink),
|
||||
std::move(tp), OverflowPolicy);
|
||||
registry_inst.initialize_logger(new_logger);
|
||||
return new_logger;
|
||||
}
|
||||
};
|
||||
|
||||
using async_factory = async_factory_impl<async_overflow_policy::block>;
|
||||
using async_factory_nonblock = async_factory_impl<async_overflow_policy::overrun_oldest>;
|
||||
|
||||
template <typename Sink, typename... SinkArgs>
|
||||
inline std::shared_ptr<spdlog::logger> create_async(std::string logger_name,
|
||||
SinkArgs &&...sink_args) {
|
||||
return async_factory::create<Sink>(std::move(logger_name),
|
||||
std::forward<SinkArgs>(sink_args)...);
|
||||
}
|
||||
|
||||
template <typename Sink, typename... SinkArgs>
|
||||
inline std::shared_ptr<spdlog::logger> create_async_nb(std::string logger_name,
|
||||
SinkArgs &&...sink_args) {
|
||||
return async_factory_nonblock::create<Sink>(std::move(logger_name),
|
||||
std::forward<SinkArgs>(sink_args)...);
|
||||
}
|
||||
|
||||
// set global thread pool.
|
||||
inline void init_thread_pool(size_t q_size,
|
||||
size_t thread_count,
|
||||
std::function<void()> on_thread_start,
|
||||
std::function<void()> on_thread_stop) {
|
||||
auto tp = std::make_shared<details::thread_pool>(q_size, thread_count, on_thread_start,
|
||||
on_thread_stop);
|
||||
details::registry::instance().set_tp(std::move(tp));
|
||||
}
|
||||
|
||||
inline void init_thread_pool(size_t q_size,
|
||||
size_t thread_count,
|
||||
std::function<void()> on_thread_start) {
|
||||
init_thread_pool(q_size, thread_count, on_thread_start, [] {});
|
||||
}
|
||||
|
||||
inline void init_thread_pool(size_t q_size, size_t thread_count) {
|
||||
init_thread_pool(
|
||||
q_size, thread_count, [] {}, [] {});
|
||||
}
|
||||
|
||||
// get the global thread pool.
|
||||
inline std::shared_ptr<spdlog::details::thread_pool> thread_pool() {
|
||||
return details::registry::instance().get_tp();
|
||||
}
|
||||
} // namespace spdlog
|
@ -1,84 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/async_logger.h>
|
||||
#endif
|
||||
|
||||
#include <spdlog/details/thread_pool.h>
|
||||
#include <spdlog/sinks/sink.h>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
SPDLOG_INLINE spdlog::async_logger::async_logger(std::string logger_name,
|
||||
sinks_init_list sinks_list,
|
||||
std::weak_ptr<details::thread_pool> tp,
|
||||
async_overflow_policy overflow_policy)
|
||||
: async_logger(std::move(logger_name),
|
||||
sinks_list.begin(),
|
||||
sinks_list.end(),
|
||||
std::move(tp),
|
||||
overflow_policy) {}
|
||||
|
||||
SPDLOG_INLINE spdlog::async_logger::async_logger(std::string logger_name,
|
||||
sink_ptr single_sink,
|
||||
std::weak_ptr<details::thread_pool> tp,
|
||||
async_overflow_policy overflow_policy)
|
||||
: async_logger(
|
||||
std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy) {}
|
||||
|
||||
// send the log message to the thread pool
|
||||
SPDLOG_INLINE void spdlog::async_logger::sink_it_(const details::log_msg &msg){
|
||||
SPDLOG_TRY{if (auto pool_ptr = thread_pool_.lock()){
|
||||
pool_ptr->post_log(shared_from_this(), msg, overflow_policy_);
|
||||
}
|
||||
else {
|
||||
throw_spdlog_ex("async log: thread pool doesn't exist anymore");
|
||||
}
|
||||
}
|
||||
SPDLOG_LOGGER_CATCH(msg.source)
|
||||
}
|
||||
|
||||
// send flush request to the thread pool
|
||||
SPDLOG_INLINE void spdlog::async_logger::flush_(){
|
||||
SPDLOG_TRY{if (auto pool_ptr = thread_pool_.lock()){
|
||||
pool_ptr->post_flush(shared_from_this(), overflow_policy_);
|
||||
}
|
||||
else {
|
||||
throw_spdlog_ex("async flush: thread pool doesn't exist anymore");
|
||||
}
|
||||
}
|
||||
SPDLOG_LOGGER_CATCH(source_loc())
|
||||
}
|
||||
|
||||
//
|
||||
// backend functions - called from the thread pool to do the actual job
|
||||
//
|
||||
SPDLOG_INLINE void spdlog::async_logger::backend_sink_it_(const details::log_msg &msg) {
|
||||
for (auto &sink : sinks_) {
|
||||
if (sink->should_log(msg.level)) {
|
||||
SPDLOG_TRY { sink->log(msg); }
|
||||
SPDLOG_LOGGER_CATCH(msg.source)
|
||||
}
|
||||
}
|
||||
|
||||
if (should_flush_(msg)) {
|
||||
backend_flush_();
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void spdlog::async_logger::backend_flush_() {
|
||||
for (auto &sink : sinks_) {
|
||||
SPDLOG_TRY { sink->flush(); }
|
||||
SPDLOG_LOGGER_CATCH(source_loc())
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE std::shared_ptr<spdlog::logger> spdlog::async_logger::clone(std::string new_name) {
|
||||
auto cloned = std::make_shared<spdlog::async_logger>(*this);
|
||||
cloned->name_ = std::move(new_name);
|
||||
return cloned;
|
||||
}
|
@ -1,74 +1,77 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
// Fast asynchronous logger.
|
||||
// Uses pre allocated queue.
|
||||
// Very fast asynchronous logger (millions of logs per second on an average desktop)
|
||||
// Uses pre allocated lockfree queue for maximum throughput even under large number of threads.
|
||||
// Creates a single back thread to pop messages from the queue and log them.
|
||||
//
|
||||
// Upon each log write the logger:
|
||||
// 1. Checks if its log level is enough to log the message
|
||||
// 2. Push a new copy of the message to a queue (or block the caller until
|
||||
// space is available in the queue)
|
||||
// Upon destruction, logs all remaining messages in the queue before
|
||||
// destructing..
|
||||
// 2. Push a new copy of the message to a queue (or block the caller until space is available in the queue)
|
||||
// 3. will throw spdlog_ex upon log exceptions
|
||||
// Upon destruction, logs all remaining messages in the queue before destructing..
|
||||
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/logger.h>
|
||||
|
||||
namespace spdlog {
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
// Async overflow policy - block by default.
|
||||
enum class async_overflow_policy {
|
||||
block, // Block until message can be enqueued
|
||||
overrun_oldest, // Discard oldest message in the queue if full when trying to
|
||||
// add new item.
|
||||
discard_new // Discard new message if the queue is full when trying to add new item.
|
||||
};
|
||||
namespace spdlog
|
||||
{
|
||||
|
||||
namespace details {
|
||||
class thread_pool;
|
||||
namespace details
|
||||
{
|
||||
class async_log_helper;
|
||||
}
|
||||
|
||||
class SPDLOG_API async_logger final : public std::enable_shared_from_this<async_logger>,
|
||||
public logger {
|
||||
friend class details::thread_pool;
|
||||
|
||||
class async_logger :public logger
|
||||
{
|
||||
public:
|
||||
template <typename It>
|
||||
async_logger(std::string logger_name,
|
||||
It begin,
|
||||
It end,
|
||||
std::weak_ptr<details::thread_pool> tp,
|
||||
async_overflow_policy overflow_policy = async_overflow_policy::block)
|
||||
: logger(std::move(logger_name), begin, end),
|
||||
thread_pool_(std::move(tp)),
|
||||
overflow_policy_(overflow_policy) {}
|
||||
template<class It>
|
||||
async_logger(const std::string& name,
|
||||
const It& begin,
|
||||
const It& end,
|
||||
size_t queue_size,
|
||||
const async_overflow_policy overflow_policy = async_overflow_policy::block_retry,
|
||||
const std::function<void()>& worker_warmup_cb = nullptr,
|
||||
const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(),
|
||||
const std::function<void()>& worker_teardown_cb = nullptr);
|
||||
|
||||
async_logger(std::string logger_name,
|
||||
sinks_init_list sinks_list,
|
||||
std::weak_ptr<details::thread_pool> tp,
|
||||
async_overflow_policy overflow_policy = async_overflow_policy::block);
|
||||
async_logger(const std::string& logger_name,
|
||||
sinks_init_list sinks,
|
||||
size_t queue_size,
|
||||
const async_overflow_policy overflow_policy = async_overflow_policy::block_retry,
|
||||
const std::function<void()>& worker_warmup_cb = nullptr,
|
||||
const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(),
|
||||
const std::function<void()>& worker_teardown_cb = nullptr);
|
||||
|
||||
async_logger(std::string logger_name,
|
||||
async_logger(const std::string& logger_name,
|
||||
sink_ptr single_sink,
|
||||
std::weak_ptr<details::thread_pool> tp,
|
||||
async_overflow_policy overflow_policy = async_overflow_policy::block);
|
||||
|
||||
std::shared_ptr<logger> clone(std::string new_name) override;
|
||||
size_t queue_size,
|
||||
const async_overflow_policy overflow_policy = async_overflow_policy::block_retry,
|
||||
const std::function<void()>& worker_warmup_cb = nullptr,
|
||||
const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(),
|
||||
const std::function<void()>& worker_teardown_cb = nullptr);
|
||||
|
||||
//Wait for the queue to be empty, and flush synchronously
|
||||
//Warning: this can potentialy last forever as we wait it to complete
|
||||
void flush() override;
|
||||
protected:
|
||||
void sink_it_(const details::log_msg &msg) override;
|
||||
void flush_() override;
|
||||
void backend_sink_it_(const details::log_msg &incoming_log_msg);
|
||||
void backend_flush_();
|
||||
void _sink_it(details::log_msg& msg) override;
|
||||
void _set_formatter(spdlog::formatter_ptr msg_formatter) override;
|
||||
void _set_pattern(const std::string& pattern) override;
|
||||
|
||||
private:
|
||||
std::weak_ptr<details::thread_pool> thread_pool_;
|
||||
async_overflow_policy overflow_policy_;
|
||||
std::unique_ptr<details::async_log_helper> _async_log_helper;
|
||||
};
|
||||
} // namespace spdlog
|
||||
}
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "async_logger-inl.h"
|
||||
#endif
|
||||
|
||||
#include <spdlog/details/async_logger_impl.h>
|
||||
|
@ -1,40 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
#include <spdlog/cfg/helpers.h>
|
||||
#include <spdlog/details/registry.h>
|
||||
|
||||
//
|
||||
// Init log levels using each argv entry that starts with "SPDLOG_LEVEL="
|
||||
//
|
||||
// set all loggers to debug level:
|
||||
// example.exe "SPDLOG_LEVEL=debug"
|
||||
|
||||
// set logger1 to trace level
|
||||
// example.exe "SPDLOG_LEVEL=logger1=trace"
|
||||
|
||||
// turn off all logging except for logger1 and logger2:
|
||||
// example.exe "SPDLOG_LEVEL=off,logger1=debug,logger2=info"
|
||||
|
||||
namespace spdlog {
|
||||
namespace cfg {
|
||||
|
||||
// search for SPDLOG_LEVEL= in the args and use it to init the levels
|
||||
inline void load_argv_levels(int argc, const char **argv) {
|
||||
const std::string spdlog_level_prefix = "SPDLOG_LEVEL=";
|
||||
for (int i = 1; i < argc; i++) {
|
||||
std::string arg = argv[i];
|
||||
if (arg.find(spdlog_level_prefix) == 0) {
|
||||
auto levels_string = arg.substr(spdlog_level_prefix.size());
|
||||
helpers::load_levels(levels_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline void load_argv_levels(int argc, char **argv) {
|
||||
load_argv_levels(argc, const_cast<const char **>(argv));
|
||||
}
|
||||
|
||||
} // namespace cfg
|
||||
} // namespace spdlog
|
@ -1,36 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
#include <spdlog/cfg/helpers.h>
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/details/registry.h>
|
||||
|
||||
//
|
||||
// Init levels and patterns from env variables SPDLOG_LEVEL
|
||||
// Inspired from Rust's "env_logger" crate (https://crates.io/crates/env_logger).
|
||||
// Note - fallback to "info" level on unrecognized levels
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// set global level to debug:
|
||||
// export SPDLOG_LEVEL=debug
|
||||
//
|
||||
// turn off all logging except for logger1:
|
||||
// export SPDLOG_LEVEL="*=off,logger1=debug"
|
||||
//
|
||||
|
||||
// turn off all logging except for logger1 and logger2:
|
||||
// export SPDLOG_LEVEL="off,logger1=debug,logger2=info"
|
||||
|
||||
namespace spdlog {
|
||||
namespace cfg {
|
||||
inline void load_env_levels(const char* var = "SPDLOG_LEVEL") {
|
||||
auto env_val = details::os::getenv(var);
|
||||
if (!env_val.empty()) {
|
||||
helpers::load_levels(env_val);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace cfg
|
||||
} // namespace spdlog
|
@ -1,107 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/cfg/helpers.h>
|
||||
#endif
|
||||
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/details/registry.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace spdlog {
|
||||
namespace cfg {
|
||||
namespace helpers {
|
||||
|
||||
// inplace convert to lowercase
|
||||
inline std::string &to_lower_(std::string &str) {
|
||||
std::transform(str.begin(), str.end(), str.begin(), [](char ch) {
|
||||
return static_cast<char>((ch >= 'A' && ch <= 'Z') ? ch + ('a' - 'A') : ch);
|
||||
});
|
||||
return str;
|
||||
}
|
||||
|
||||
// inplace trim spaces
|
||||
inline std::string &trim_(std::string &str) {
|
||||
const char *spaces = " \n\r\t";
|
||||
str.erase(str.find_last_not_of(spaces) + 1);
|
||||
str.erase(0, str.find_first_not_of(spaces));
|
||||
return str;
|
||||
}
|
||||
|
||||
// return (name,value) trimmed pair from given "name=value" string.
|
||||
// return empty string on missing parts
|
||||
// "key=val" => ("key", "val")
|
||||
// " key = val " => ("key", "val")
|
||||
// "key=" => ("key", "")
|
||||
// "val" => ("", "val")
|
||||
|
||||
inline std::pair<std::string, std::string> extract_kv_(char sep, const std::string &str) {
|
||||
auto n = str.find(sep);
|
||||
std::string k, v;
|
||||
if (n == std::string::npos) {
|
||||
v = str;
|
||||
} else {
|
||||
k = str.substr(0, n);
|
||||
v = str.substr(n + 1);
|
||||
}
|
||||
return std::make_pair(trim_(k), trim_(v));
|
||||
}
|
||||
|
||||
// return vector of key/value pairs from sequence of "K1=V1,K2=V2,.."
|
||||
// "a=AAA,b=BBB,c=CCC,.." => {("a","AAA"),("b","BBB"),("c", "CCC"),...}
|
||||
inline std::unordered_map<std::string, std::string> extract_key_vals_(const std::string &str) {
|
||||
std::string token;
|
||||
std::istringstream token_stream(str);
|
||||
std::unordered_map<std::string, std::string> rv{};
|
||||
while (std::getline(token_stream, token, ',')) {
|
||||
if (token.empty()) {
|
||||
continue;
|
||||
}
|
||||
auto kv = extract_kv_('=', token);
|
||||
rv[kv.first] = kv.second;
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void load_levels(const std::string &input) {
|
||||
if (input.empty() || input.size() > 512) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto key_vals = extract_key_vals_(input);
|
||||
std::unordered_map<std::string, level::level_enum> levels;
|
||||
level::level_enum global_level = level::info;
|
||||
bool global_level_found = false;
|
||||
|
||||
for (auto &name_level : key_vals) {
|
||||
auto &logger_name = name_level.first;
|
||||
auto level_name = to_lower_(name_level.second);
|
||||
auto level = level::from_str(level_name);
|
||||
// ignore unrecognized level names
|
||||
if (level == level::off && level_name != "off") {
|
||||
continue;
|
||||
}
|
||||
if (logger_name.empty()) // no logger name indicate global level
|
||||
{
|
||||
global_level_found = true;
|
||||
global_level = level;
|
||||
} else {
|
||||
levels[logger_name] = level;
|
||||
}
|
||||
}
|
||||
|
||||
details::registry::instance().set_levels(std::move(levels),
|
||||
global_level_found ? &global_level : nullptr);
|
||||
}
|
||||
|
||||
} // namespace helpers
|
||||
} // namespace cfg
|
||||
} // namespace spdlog
|
@ -1,29 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/common.h>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace spdlog {
|
||||
namespace cfg {
|
||||
namespace helpers {
|
||||
//
|
||||
// Init levels from given string
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// set global level to debug: "debug"
|
||||
// turn off all logging except for logger1: "off,logger1=debug"
|
||||
// turn off all logging except for logger1 and logger2: "off,logger1=debug,logger2=info"
|
||||
//
|
||||
SPDLOG_API void load_levels(const std::string &txt);
|
||||
} // namespace helpers
|
||||
|
||||
} // namespace cfg
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "helpers-inl.h"
|
||||
#endif // SPDLOG_HEADER_ONLY
|
@ -1,68 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/common.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <iterator>
|
||||
|
||||
namespace spdlog {
|
||||
namespace level {
|
||||
|
||||
#if __cplusplus >= 201703L
|
||||
constexpr
|
||||
#endif
|
||||
static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES;
|
||||
|
||||
static const char *short_level_names[] SPDLOG_SHORT_LEVEL_NAMES;
|
||||
|
||||
SPDLOG_INLINE const string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT {
|
||||
return level_string_views[l];
|
||||
}
|
||||
|
||||
SPDLOG_INLINE const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT {
|
||||
return short_level_names[l];
|
||||
}
|
||||
|
||||
SPDLOG_INLINE spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT {
|
||||
auto it = std::find(std::begin(level_string_views), std::end(level_string_views), name);
|
||||
if (it != std::end(level_string_views))
|
||||
return static_cast<level::level_enum>(std::distance(std::begin(level_string_views), it));
|
||||
|
||||
// check also for "warn" and "err" before giving up..
|
||||
if (name == "warn") {
|
||||
return level::warn;
|
||||
}
|
||||
if (name == "err") {
|
||||
return level::err;
|
||||
}
|
||||
return level::off;
|
||||
}
|
||||
} // namespace level
|
||||
|
||||
SPDLOG_INLINE spdlog_ex::spdlog_ex(std::string msg)
|
||||
: msg_(std::move(msg)) {}
|
||||
|
||||
SPDLOG_INLINE spdlog_ex::spdlog_ex(const std::string &msg, int last_errno) {
|
||||
#ifdef SPDLOG_USE_STD_FORMAT
|
||||
msg_ = std::system_error(std::error_code(last_errno, std::generic_category()), msg).what();
|
||||
#else
|
||||
memory_buf_t outbuf;
|
||||
fmt::format_system_error(outbuf, last_errno, msg.c_str());
|
||||
msg_ = fmt::to_string(outbuf);
|
||||
#endif
|
||||
}
|
||||
|
||||
SPDLOG_INLINE const char *spdlog_ex::what() const SPDLOG_NOEXCEPT { return msg_.c_str(); }
|
||||
|
||||
SPDLOG_INLINE void throw_spdlog_ex(const std::string &msg, int last_errno) {
|
||||
SPDLOG_THROW(spdlog_ex(msg, last_errno));
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void throw_spdlog_ex(std::string msg) { SPDLOG_THROW(spdlog_ex(std::move(msg))); }
|
||||
|
||||
} // namespace spdlog
|
@ -1,406 +1,143 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/tweakme.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <exception>
|
||||
#include <functional>
|
||||
#include <initializer_list>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <initializer_list>
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <atomic>
|
||||
#include <exception>
|
||||
#include<functional>
|
||||
|
||||
#ifdef SPDLOG_USE_STD_FORMAT
|
||||
#include <version>
|
||||
#if __cpp_lib_format >= 202207L
|
||||
#include <format>
|
||||
#else
|
||||
#include <string_view>
|
||||
#endif
|
||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||
#include <codecvt>
|
||||
#include <locale>
|
||||
#endif
|
||||
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
|
||||
//visual studio upto 2013 does not support noexcept nor constexpr
|
||||
#if defined(_MSC_VER) && (_MSC_VER < 1900)
|
||||
#define SPDLOG_NOEXCEPT throw()
|
||||
#define SPDLOG_CONSTEXPR
|
||||
#else
|
||||
#define SPDLOG_NOEXCEPT noexcept
|
||||
#define SPDLOG_CONSTEXPR constexpr
|
||||
#endif
|
||||
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
#define DEPRECATED __attribute__((deprecated))
|
||||
#elif defined(_MSC_VER)
|
||||
#define DEPRECATED __declspec(deprecated)
|
||||
#else
|
||||
#define DEPRECATED
|
||||
#endif
|
||||
|
||||
#ifdef SPDLOG_COMPILED_LIB
|
||||
#undef SPDLOG_HEADER_ONLY
|
||||
#if defined(SPDLOG_SHARED_LIB)
|
||||
#if defined(_WIN32)
|
||||
#ifdef spdlog_EXPORTS
|
||||
#define SPDLOG_API __declspec(dllexport)
|
||||
#else // !spdlog_EXPORTS
|
||||
#define SPDLOG_API __declspec(dllimport)
|
||||
#endif
|
||||
#else // !defined(_WIN32)
|
||||
#define SPDLOG_API __attribute__((visibility("default")))
|
||||
#endif
|
||||
#else // !defined(SPDLOG_SHARED_LIB)
|
||||
#define SPDLOG_API
|
||||
#endif
|
||||
#define SPDLOG_INLINE
|
||||
#else // !defined(SPDLOG_COMPILED_LIB)
|
||||
#define SPDLOG_API
|
||||
#define SPDLOG_HEADER_ONLY
|
||||
#define SPDLOG_INLINE inline
|
||||
#endif // #ifdef SPDLOG_COMPILED_LIB
|
||||
|
||||
#include <spdlog/fmt/fmt.h>
|
||||
|
||||
#if !defined(SPDLOG_USE_STD_FORMAT) && \
|
||||
FMT_VERSION >= 80000 // backward compatibility with fmt versions older than 8
|
||||
#define SPDLOG_FMT_RUNTIME(format_string) fmt::runtime(format_string)
|
||||
#define SPDLOG_FMT_STRING(format_string) FMT_STRING(format_string)
|
||||
#if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||
#include <spdlog/fmt/xchar.h>
|
||||
#endif
|
||||
#else
|
||||
#define SPDLOG_FMT_RUNTIME(format_string) format_string
|
||||
#define SPDLOG_FMT_STRING(format_string) format_string
|
||||
#endif
|
||||
|
||||
// visual studio up to 2013 does not support noexcept nor constexpr
|
||||
#if defined(_MSC_VER) && (_MSC_VER < 1900)
|
||||
#define SPDLOG_NOEXCEPT _NOEXCEPT
|
||||
#define SPDLOG_CONSTEXPR
|
||||
#else
|
||||
#define SPDLOG_NOEXCEPT noexcept
|
||||
#define SPDLOG_CONSTEXPR constexpr
|
||||
#endif
|
||||
|
||||
// If building with std::format, can just use constexpr, otherwise if building with fmt
|
||||
// SPDLOG_CONSTEXPR_FUNC needs to be set the same as FMT_CONSTEXPR to avoid situations where
|
||||
// a constexpr function in spdlog could end up calling a non-constexpr function in fmt
|
||||
// depending on the compiler
|
||||
// If fmt determines it can't use constexpr, we should inline the function instead
|
||||
#ifdef SPDLOG_USE_STD_FORMAT
|
||||
#define SPDLOG_CONSTEXPR_FUNC constexpr
|
||||
#else // Being built with fmt
|
||||
#if FMT_USE_CONSTEXPR
|
||||
#define SPDLOG_CONSTEXPR_FUNC FMT_CONSTEXPR
|
||||
#else
|
||||
#define SPDLOG_CONSTEXPR_FUNC inline
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
#define SPDLOG_DEPRECATED __attribute__((deprecated))
|
||||
#elif defined(_MSC_VER)
|
||||
#define SPDLOG_DEPRECATED __declspec(deprecated)
|
||||
#else
|
||||
#define SPDLOG_DEPRECATED
|
||||
#endif
|
||||
|
||||
// disable thread local on msvc 2013
|
||||
#ifndef SPDLOG_NO_TLS
|
||||
#if (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt)
|
||||
#define SPDLOG_NO_TLS 1
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef SPDLOG_FUNCTION
|
||||
#define SPDLOG_FUNCTION static_cast<const char *>(__FUNCTION__)
|
||||
#endif
|
||||
|
||||
#ifdef SPDLOG_NO_EXCEPTIONS
|
||||
#define SPDLOG_TRY
|
||||
#define SPDLOG_THROW(ex) \
|
||||
do { \
|
||||
printf("spdlog fatal error: %s\n", ex.what()); \
|
||||
std::abort(); \
|
||||
} while (0)
|
||||
#define SPDLOG_CATCH_STD
|
||||
#else
|
||||
#define SPDLOG_TRY try
|
||||
#define SPDLOG_THROW(ex) throw(ex)
|
||||
#define SPDLOG_CATCH_STD \
|
||||
catch (const std::exception &) { \
|
||||
}
|
||||
#endif
|
||||
|
||||
namespace spdlog {
|
||||
namespace spdlog
|
||||
{
|
||||
|
||||
class formatter;
|
||||
|
||||
namespace sinks {
|
||||
namespace sinks
|
||||
{
|
||||
class sink;
|
||||
}
|
||||
|
||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||
using filename_t = std::wstring;
|
||||
// allow macro expansion to occur in SPDLOG_FILENAME_T
|
||||
#define SPDLOG_FILENAME_T_INNER(s) L##s
|
||||
#define SPDLOG_FILENAME_T(s) SPDLOG_FILENAME_T_INNER(s)
|
||||
#else
|
||||
using filename_t = std::string;
|
||||
#define SPDLOG_FILENAME_T(s) s
|
||||
#endif
|
||||
|
||||
using log_clock = std::chrono::system_clock;
|
||||
using sink_ptr = std::shared_ptr<sinks::sink>;
|
||||
using sinks_init_list = std::initializer_list<sink_ptr>;
|
||||
using err_handler = std::function<void(const std::string &err_msg)>;
|
||||
#ifdef SPDLOG_USE_STD_FORMAT
|
||||
namespace fmt_lib = std;
|
||||
|
||||
using string_view_t = std::string_view;
|
||||
using memory_buf_t = std::string;
|
||||
|
||||
template <typename... Args>
|
||||
#if __cpp_lib_format >= 202207L
|
||||
using format_string_t = std::format_string<Args...>;
|
||||
#else
|
||||
using format_string_t = std::string_view;
|
||||
#endif
|
||||
|
||||
template <class T, class Char = char>
|
||||
struct is_convertible_to_basic_format_string
|
||||
: std::integral_constant<bool, std::is_convertible<T, std::basic_string_view<Char>>::value> {};
|
||||
|
||||
#if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||
using wstring_view_t = std::wstring_view;
|
||||
using wmemory_buf_t = std::wstring;
|
||||
|
||||
template <typename... Args>
|
||||
#if __cpp_lib_format >= 202207L
|
||||
using wformat_string_t = std::wformat_string<Args...>;
|
||||
#else
|
||||
using wformat_string_t = std::wstring_view;
|
||||
#endif
|
||||
#endif
|
||||
#define SPDLOG_BUF_TO_STRING(x) x
|
||||
#else // use fmt lib instead of std::format
|
||||
namespace fmt_lib = fmt;
|
||||
|
||||
using string_view_t = fmt::basic_string_view<char>;
|
||||
using memory_buf_t = fmt::basic_memory_buffer<char, 250>;
|
||||
|
||||
template <typename... Args>
|
||||
using format_string_t = fmt::format_string<Args...>;
|
||||
|
||||
template <class T>
|
||||
using remove_cvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
|
||||
|
||||
template <typename Char>
|
||||
#if FMT_VERSION >= 90101
|
||||
using fmt_runtime_string = fmt::runtime_format_string<Char>;
|
||||
#else
|
||||
using fmt_runtime_string = fmt::basic_runtime<Char>;
|
||||
#endif
|
||||
|
||||
// clang doesn't like SFINAE disabled constructor in std::is_convertible<> so have to repeat the
|
||||
// condition from basic_format_string here, in addition, fmt::basic_runtime<Char> is only
|
||||
// convertible to basic_format_string<Char> but not basic_string_view<Char>
|
||||
template <class T, class Char = char>
|
||||
struct is_convertible_to_basic_format_string
|
||||
: std::integral_constant<bool,
|
||||
std::is_convertible<T, fmt::basic_string_view<Char>>::value ||
|
||||
std::is_same<remove_cvref_t<T>, fmt_runtime_string<Char>>::value> {
|
||||
};
|
||||
|
||||
#if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||
using wstring_view_t = fmt::basic_string_view<wchar_t>;
|
||||
using wmemory_buf_t = fmt::basic_memory_buffer<wchar_t, 250>;
|
||||
|
||||
template <typename... Args>
|
||||
using wformat_string_t = fmt::wformat_string<Args...>;
|
||||
#endif
|
||||
#define SPDLOG_BUF_TO_STRING(x) fmt::to_string(x)
|
||||
#endif
|
||||
|
||||
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
|
||||
#ifndef _WIN32
|
||||
#error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows
|
||||
#endif // _WIN32
|
||||
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
|
||||
|
||||
template <class T>
|
||||
struct is_convertible_to_any_format_string
|
||||
: std::integral_constant<bool,
|
||||
is_convertible_to_basic_format_string<T, char>::value ||
|
||||
is_convertible_to_basic_format_string<T, wchar_t>::value> {};
|
||||
|
||||
using sink_ptr = std::shared_ptr < sinks::sink >;
|
||||
using sinks_init_list = std::initializer_list < sink_ptr >;
|
||||
using formatter_ptr = std::shared_ptr<spdlog::formatter>;
|
||||
#if defined(SPDLOG_NO_ATOMIC_LEVELS)
|
||||
using level_t = details::null_atomic_int;
|
||||
#else
|
||||
using level_t = std::atomic<int>;
|
||||
using level_t = std::atomic_int;
|
||||
#endif
|
||||
|
||||
#define SPDLOG_LEVEL_TRACE 0
|
||||
#define SPDLOG_LEVEL_DEBUG 1
|
||||
#define SPDLOG_LEVEL_INFO 2
|
||||
#define SPDLOG_LEVEL_WARN 3
|
||||
#define SPDLOG_LEVEL_ERROR 4
|
||||
#define SPDLOG_LEVEL_CRITICAL 5
|
||||
#define SPDLOG_LEVEL_OFF 6
|
||||
using log_err_handler = std::function<void(const std::string &err_msg)>;
|
||||
|
||||
#if !defined(SPDLOG_ACTIVE_LEVEL)
|
||||
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_INFO
|
||||
#endif
|
||||
//Log level enum
|
||||
namespace level
|
||||
{
|
||||
typedef enum
|
||||
{
|
||||
trace = 0,
|
||||
debug = 1,
|
||||
info = 2,
|
||||
warn = 3,
|
||||
err = 4,
|
||||
critical = 5,
|
||||
off = 6
|
||||
} level_enum;
|
||||
|
||||
// Log level enum
|
||||
namespace level {
|
||||
enum level_enum : int {
|
||||
trace = SPDLOG_LEVEL_TRACE,
|
||||
debug = SPDLOG_LEVEL_DEBUG,
|
||||
info = SPDLOG_LEVEL_INFO,
|
||||
warn = SPDLOG_LEVEL_WARN,
|
||||
err = SPDLOG_LEVEL_ERROR,
|
||||
critical = SPDLOG_LEVEL_CRITICAL,
|
||||
off = SPDLOG_LEVEL_OFF,
|
||||
n_levels
|
||||
static const char* level_names[] { "trace", "debug", "info", "warning", "error", "critical", "off" };
|
||||
|
||||
static const char* short_level_names[] { "T", "D", "I", "W", "E", "C", "O" };
|
||||
|
||||
inline const char* to_str(spdlog::level::level_enum l)
|
||||
{
|
||||
return level_names[l];
|
||||
}
|
||||
|
||||
inline const char* to_short_str(spdlog::level::level_enum l)
|
||||
{
|
||||
return short_level_names[l];
|
||||
}
|
||||
} //level
|
||||
|
||||
|
||||
//
|
||||
// Async overflow policy - block by default.
|
||||
//
|
||||
enum class async_overflow_policy
|
||||
{
|
||||
block_retry, // Block / yield / sleep until message can be enqueued
|
||||
discard_log_msg // Discard the message it enqueue fails
|
||||
};
|
||||
|
||||
#define SPDLOG_LEVEL_NAME_TRACE spdlog::string_view_t("trace", 5)
|
||||
#define SPDLOG_LEVEL_NAME_DEBUG spdlog::string_view_t("debug", 5)
|
||||
#define SPDLOG_LEVEL_NAME_INFO spdlog::string_view_t("info", 4)
|
||||
#define SPDLOG_LEVEL_NAME_WARNING spdlog::string_view_t("warning", 7)
|
||||
#define SPDLOG_LEVEL_NAME_ERROR spdlog::string_view_t("error", 5)
|
||||
#define SPDLOG_LEVEL_NAME_CRITICAL spdlog::string_view_t("critical", 8)
|
||||
#define SPDLOG_LEVEL_NAME_OFF spdlog::string_view_t("off", 3)
|
||||
|
||||
#if !defined(SPDLOG_LEVEL_NAMES)
|
||||
#define SPDLOG_LEVEL_NAMES \
|
||||
{ \
|
||||
SPDLOG_LEVEL_NAME_TRACE, SPDLOG_LEVEL_NAME_DEBUG, SPDLOG_LEVEL_NAME_INFO, \
|
||||
SPDLOG_LEVEL_NAME_WARNING, SPDLOG_LEVEL_NAME_ERROR, SPDLOG_LEVEL_NAME_CRITICAL, \
|
||||
SPDLOG_LEVEL_NAME_OFF \
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !defined(SPDLOG_SHORT_LEVEL_NAMES)
|
||||
|
||||
#define SPDLOG_SHORT_LEVEL_NAMES \
|
||||
{ "T", "D", "I", "W", "E", "C", "O" }
|
||||
#endif
|
||||
|
||||
SPDLOG_API const string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT;
|
||||
|
||||
} // namespace level
|
||||
|
||||
//
|
||||
// Color mode used by sinks with color support.
|
||||
//
|
||||
enum class color_mode { always, automatic, never };
|
||||
|
||||
//
|
||||
// Pattern time - specific time getting to use for pattern_formatter.
|
||||
// local time by default
|
||||
//
|
||||
enum class pattern_time_type {
|
||||
local, // log localtime
|
||||
utc // log utc
|
||||
};
|
||||
|
||||
//
|
||||
// Log exception
|
||||
//
|
||||
class SPDLOG_API spdlog_ex : public std::exception {
|
||||
namespace details
|
||||
{
|
||||
namespace os
|
||||
{
|
||||
std::string errno_str(int err_num);
|
||||
}
|
||||
}
|
||||
class spdlog_ex: public std::exception
|
||||
{
|
||||
public:
|
||||
explicit spdlog_ex(std::string msg);
|
||||
spdlog_ex(const std::string &msg, int last_errno);
|
||||
const char *what() const SPDLOG_NOEXCEPT override;
|
||||
|
||||
spdlog_ex(const std::string& msg):_msg(msg)
|
||||
{}
|
||||
spdlog_ex(const std::string& msg, int last_errno)
|
||||
{
|
||||
_msg = msg + ": " + details::os::errno_str(last_errno);
|
||||
}
|
||||
const char* what() const SPDLOG_NOEXCEPT override
|
||||
{
|
||||
return _msg.c_str();
|
||||
}
|
||||
private:
|
||||
std::string msg_;
|
||||
std::string _msg;
|
||||
|
||||
};
|
||||
|
||||
[[noreturn]] SPDLOG_API void throw_spdlog_ex(const std::string &msg, int last_errno);
|
||||
[[noreturn]] SPDLOG_API void throw_spdlog_ex(std::string msg);
|
||||
|
||||
struct source_loc {
|
||||
SPDLOG_CONSTEXPR source_loc() = default;
|
||||
SPDLOG_CONSTEXPR source_loc(const char *filename_in, int line_in, const char *funcname_in)
|
||||
: filename{filename_in},
|
||||
line{line_in},
|
||||
funcname{funcname_in} {}
|
||||
|
||||
SPDLOG_CONSTEXPR bool empty() const SPDLOG_NOEXCEPT { return line <= 0; }
|
||||
const char *filename{nullptr};
|
||||
int line{0};
|
||||
const char *funcname{nullptr};
|
||||
};
|
||||
|
||||
struct file_event_handlers {
|
||||
file_event_handlers()
|
||||
: before_open(nullptr),
|
||||
after_open(nullptr),
|
||||
before_close(nullptr),
|
||||
after_close(nullptr) {}
|
||||
|
||||
std::function<void(const filename_t &filename)> before_open;
|
||||
std::function<void(const filename_t &filename, std::FILE *file_stream)> after_open;
|
||||
std::function<void(const filename_t &filename, std::FILE *file_stream)> before_close;
|
||||
std::function<void(const filename_t &filename)> after_close;
|
||||
};
|
||||
|
||||
namespace details {
|
||||
|
||||
// to_string_view
|
||||
|
||||
SPDLOG_CONSTEXPR_FUNC spdlog::string_view_t to_string_view(const memory_buf_t &buf)
|
||||
SPDLOG_NOEXCEPT {
|
||||
return spdlog::string_view_t{buf.data(), buf.size()};
|
||||
}
|
||||
|
||||
SPDLOG_CONSTEXPR_FUNC spdlog::string_view_t to_string_view(spdlog::string_view_t str)
|
||||
SPDLOG_NOEXCEPT {
|
||||
return str;
|
||||
}
|
||||
|
||||
#if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||
SPDLOG_CONSTEXPR_FUNC spdlog::wstring_view_t to_string_view(const wmemory_buf_t &buf)
|
||||
SPDLOG_NOEXCEPT {
|
||||
return spdlog::wstring_view_t{buf.data(), buf.size()};
|
||||
}
|
||||
|
||||
SPDLOG_CONSTEXPR_FUNC spdlog::wstring_view_t to_string_view(spdlog::wstring_view_t str)
|
||||
SPDLOG_NOEXCEPT {
|
||||
return str;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(SPDLOG_USE_STD_FORMAT) && __cpp_lib_format >= 202207L
|
||||
template <typename T, typename... Args>
|
||||
SPDLOG_CONSTEXPR_FUNC std::basic_string_view<T> to_string_view(
|
||||
std::basic_format_string<T, Args...> fmt) SPDLOG_NOEXCEPT {
|
||||
return fmt.get();
|
||||
}
|
||||
#endif
|
||||
|
||||
// make_unique support for pre c++14
|
||||
#if __cplusplus >= 201402L // C++14 and beyond
|
||||
using std::enable_if_t;
|
||||
using std::make_unique;
|
||||
//
|
||||
// wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined)
|
||||
//
|
||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||
using filename_t = std::wstring;
|
||||
#else
|
||||
template <bool B, class T = void>
|
||||
using enable_if_t = typename std::enable_if<B, T>::type;
|
||||
|
||||
template <typename T, typename... Args>
|
||||
std::unique_ptr<T> make_unique(Args &&...args) {
|
||||
static_assert(!std::is_array<T>::value, "arrays not supported");
|
||||
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
|
||||
}
|
||||
using filename_t = std::string;
|
||||
#endif
|
||||
|
||||
// to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324)
|
||||
template <typename T, typename U, enable_if_t<!std::is_same<T, U>::value, int> = 0>
|
||||
constexpr T conditional_static_cast(U value) {
|
||||
return static_cast<T>(value);
|
||||
}
|
||||
|
||||
template <typename T, typename U, enable_if_t<std::is_same<T, U>::value, int> = 0>
|
||||
constexpr T conditional_static_cast(U value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "common-inl.h"
|
||||
#endif
|
||||
} //spdlog
|
||||
|
390
include/spdlog/details/async_log_helper.h
Normal file
390
include/spdlog/details/async_log_helper.h
Normal file
@ -0,0 +1,390 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
// async log helper :
|
||||
// Process logs asynchronously using a back thread.
|
||||
//
|
||||
// If the internal queue of log messages reaches its max size,
|
||||
// then the client call will block until there is more room.
|
||||
//
|
||||
// If the back thread throws during logging, a spdlog::spdlog_ex exception
|
||||
// will be thrown in client's thread when tries to log the next message
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/sinks/sink.h>
|
||||
#include <spdlog/details/mpmc_bounded_q.h>
|
||||
#include <spdlog/details/log_msg.h>
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/formatter.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <exception>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace spdlog
|
||||
{
|
||||
namespace details
|
||||
{
|
||||
|
||||
class async_log_helper
|
||||
{
|
||||
// Async msg to move to/from the queue
|
||||
// Movable only. should never be copied
|
||||
enum class async_msg_type
|
||||
{
|
||||
log,
|
||||
flush,
|
||||
terminate
|
||||
};
|
||||
struct async_msg
|
||||
{
|
||||
std::string logger_name;
|
||||
level::level_enum level;
|
||||
log_clock::time_point time;
|
||||
size_t thread_id;
|
||||
std::string txt;
|
||||
async_msg_type msg_type;
|
||||
|
||||
async_msg() = default;
|
||||
~async_msg() = default;
|
||||
|
||||
|
||||
async_msg(async_msg&& other) SPDLOG_NOEXCEPT:
|
||||
logger_name(std::move(other.logger_name)),
|
||||
level(std::move(other.level)),
|
||||
time(std::move(other.time)),
|
||||
txt(std::move(other.txt)),
|
||||
msg_type(std::move(other.msg_type))
|
||||
{}
|
||||
|
||||
async_msg(async_msg_type m_type) :msg_type(m_type)
|
||||
{};
|
||||
|
||||
async_msg& operator=(async_msg&& other) SPDLOG_NOEXCEPT
|
||||
{
|
||||
logger_name = std::move(other.logger_name);
|
||||
level = other.level;
|
||||
time = std::move(other.time);
|
||||
thread_id = other.thread_id;
|
||||
txt = std::move(other.txt);
|
||||
msg_type = other.msg_type;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// never copy or assign. should only be moved..
|
||||
async_msg(const async_msg&) = delete;
|
||||
async_msg& operator=(async_msg& other) = delete;
|
||||
|
||||
// construct from log_msg
|
||||
async_msg(const details::log_msg& m) :
|
||||
level(m.level),
|
||||
time(m.time),
|
||||
thread_id(m.thread_id),
|
||||
txt(m.raw.data(), m.raw.size()),
|
||||
msg_type(async_msg_type::log)
|
||||
{
|
||||
#ifndef SPDLOG_NO_NAME
|
||||
logger_name = *m.logger_name;
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
// copy into log_msg
|
||||
void fill_log_msg(log_msg &msg)
|
||||
{
|
||||
msg.logger_name = &logger_name;
|
||||
msg.level = level;
|
||||
msg.time = time;
|
||||
msg.thread_id = thread_id;
|
||||
msg.raw << txt;
|
||||
}
|
||||
};
|
||||
|
||||
public:
|
||||
|
||||
using item_type = async_msg;
|
||||
using q_type = details::mpmc_bounded_queue<item_type>;
|
||||
|
||||
using clock = std::chrono::steady_clock;
|
||||
|
||||
|
||||
async_log_helper(formatter_ptr formatter,
|
||||
const std::vector<sink_ptr>& sinks,
|
||||
size_t queue_size,
|
||||
const log_err_handler err_handler,
|
||||
const async_overflow_policy overflow_policy = async_overflow_policy::block_retry,
|
||||
const std::function<void()>& worker_warmup_cb = nullptr,
|
||||
const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(),
|
||||
const std::function<void()>& worker_teardown_cb = nullptr);
|
||||
|
||||
void log(const details::log_msg& msg);
|
||||
|
||||
// stop logging and join the back thread
|
||||
~async_log_helper();
|
||||
|
||||
void set_formatter(formatter_ptr);
|
||||
|
||||
void flush(bool wait_for_q);
|
||||
|
||||
|
||||
private:
|
||||
formatter_ptr _formatter;
|
||||
std::vector<std::shared_ptr<sinks::sink>> _sinks;
|
||||
|
||||
// queue of messages to log
|
||||
q_type _q;
|
||||
|
||||
log_err_handler _err_handler;
|
||||
|
||||
bool _flush_requested;
|
||||
|
||||
bool _terminate_requested;
|
||||
|
||||
|
||||
// overflow policy
|
||||
const async_overflow_policy _overflow_policy;
|
||||
|
||||
// worker thread warmup callback - one can set thread priority, affinity, etc
|
||||
const std::function<void()> _worker_warmup_cb;
|
||||
|
||||
// auto periodic sink flush parameter
|
||||
const std::chrono::milliseconds _flush_interval_ms;
|
||||
|
||||
// worker thread teardown callback
|
||||
const std::function<void()> _worker_teardown_cb;
|
||||
|
||||
// worker thread
|
||||
std::thread _worker_thread;
|
||||
|
||||
void push_msg(async_msg&& new_msg);
|
||||
|
||||
// worker thread main loop
|
||||
void worker_loop();
|
||||
|
||||
// pop next message from the queue and process it. will set the last_pop to the pop time
|
||||
// return false if termination of the queue is required
|
||||
bool process_next_msg(log_clock::time_point& last_pop, log_clock::time_point& last_flush);
|
||||
|
||||
void handle_flush_interval(log_clock::time_point& now, log_clock::time_point& last_flush);
|
||||
|
||||
// sleep,yield or return immediatly using the time passed since last message as a hint
|
||||
static void sleep_or_yield(const spdlog::log_clock::time_point& now, const log_clock::time_point& last_op_time);
|
||||
|
||||
// wait until the queue is empty
|
||||
void wait_empty_q();
|
||||
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// async_sink class implementation
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
inline spdlog::details::async_log_helper::async_log_helper(
|
||||
formatter_ptr formatter,
|
||||
const std::vector<sink_ptr>& sinks,
|
||||
size_t queue_size,
|
||||
log_err_handler err_handler,
|
||||
const async_overflow_policy overflow_policy,
|
||||
const std::function<void()>& worker_warmup_cb,
|
||||
const std::chrono::milliseconds& flush_interval_ms,
|
||||
const std::function<void()>& worker_teardown_cb):
|
||||
_formatter(formatter),
|
||||
_sinks(sinks),
|
||||
_q(queue_size),
|
||||
_err_handler(err_handler),
|
||||
_flush_requested(false),
|
||||
_terminate_requested(false),
|
||||
_overflow_policy(overflow_policy),
|
||||
_worker_warmup_cb(worker_warmup_cb),
|
||||
_flush_interval_ms(flush_interval_ms),
|
||||
_worker_teardown_cb(worker_teardown_cb),
|
||||
_worker_thread(&async_log_helper::worker_loop, this)
|
||||
{}
|
||||
|
||||
// Send to the worker thread termination message(level=off)
|
||||
// and wait for it to finish gracefully
|
||||
inline spdlog::details::async_log_helper::~async_log_helper()
|
||||
{
|
||||
try
|
||||
{
|
||||
push_msg(async_msg(async_msg_type::terminate));
|
||||
_worker_thread.join();
|
||||
}
|
||||
catch (...) // don't crash in destructor
|
||||
{}
|
||||
}
|
||||
|
||||
|
||||
//Try to push and block until succeeded (if the policy is not to discard when the queue is full)
|
||||
inline void spdlog::details::async_log_helper::log(const details::log_msg& msg)
|
||||
{
|
||||
push_msg(async_msg(msg));
|
||||
|
||||
|
||||
}
|
||||
|
||||
inline void spdlog::details::async_log_helper::push_msg(details::async_log_helper::async_msg&& new_msg)
|
||||
{
|
||||
if (!_q.enqueue(std::move(new_msg)) && _overflow_policy != async_overflow_policy::discard_log_msg)
|
||||
{
|
||||
auto last_op_time = details::os::now();
|
||||
auto now = last_op_time;
|
||||
do
|
||||
{
|
||||
now = details::os::now();
|
||||
sleep_or_yield(now, last_op_time);
|
||||
}
|
||||
while (!_q.enqueue(std::move(new_msg)));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// optionally wait for the queue be empty and request flush from the sinks
|
||||
inline void spdlog::details::async_log_helper::flush(bool wait_for_q)
|
||||
{
|
||||
push_msg(async_msg(async_msg_type::flush));
|
||||
if(wait_for_q)
|
||||
wait_empty_q(); //return only make after the above flush message was processed
|
||||
}
|
||||
|
||||
inline void spdlog::details::async_log_helper::worker_loop()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_worker_warmup_cb) _worker_warmup_cb();
|
||||
auto last_pop = details::os::now();
|
||||
auto last_flush = last_pop;
|
||||
while(process_next_msg(last_pop, last_flush));
|
||||
if (_worker_teardown_cb) _worker_teardown_cb();
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
_err_handler(ex.what());
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
_err_handler("Unknown exception");
|
||||
}
|
||||
}
|
||||
|
||||
// process next message in the queue
|
||||
// return true if this thread should still be active (while no terminate msg was received)
|
||||
inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_point& last_pop, log_clock::time_point& last_flush)
|
||||
{
|
||||
|
||||
async_msg incoming_async_msg;
|
||||
|
||||
|
||||
if (_q.dequeue(incoming_async_msg))
|
||||
{
|
||||
last_pop = details::os::now();
|
||||
switch (incoming_async_msg.msg_type)
|
||||
{
|
||||
case async_msg_type::flush:
|
||||
_flush_requested = true;
|
||||
break;
|
||||
|
||||
case async_msg_type::terminate:
|
||||
_flush_requested = true;
|
||||
_terminate_requested = true;
|
||||
break;
|
||||
|
||||
default:
|
||||
log_msg incoming_log_msg;
|
||||
incoming_async_msg.fill_log_msg(incoming_log_msg);
|
||||
_formatter->format(incoming_log_msg);
|
||||
for (auto &s : _sinks)
|
||||
{
|
||||
if(s->should_log( incoming_log_msg.level))
|
||||
{
|
||||
s->log(incoming_log_msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Handle empty queue..
|
||||
// This is the only place where the queue can terminate or flush to avoid losing messages already in the queue
|
||||
else
|
||||
{
|
||||
auto now = details::os::now();
|
||||
handle_flush_interval(now, last_flush);
|
||||
sleep_or_yield(now, last_pop);
|
||||
return !_terminate_requested;
|
||||
}
|
||||
}
|
||||
|
||||
// flush all sinks if _flush_interval_ms has expired
|
||||
inline void spdlog::details::async_log_helper::handle_flush_interval(log_clock::time_point& now, log_clock::time_point& last_flush)
|
||||
{
|
||||
auto should_flush = _flush_requested || (_flush_interval_ms != std::chrono::milliseconds::zero() && now - last_flush >= _flush_interval_ms);
|
||||
if (should_flush)
|
||||
{
|
||||
for (auto &s : _sinks)
|
||||
s->flush();
|
||||
now = last_flush = details::os::now();
|
||||
_flush_requested = false;
|
||||
}
|
||||
}
|
||||
|
||||
inline void spdlog::details::async_log_helper::set_formatter(formatter_ptr msg_formatter)
|
||||
{
|
||||
_formatter = msg_formatter;
|
||||
}
|
||||
|
||||
|
||||
// spin, yield or sleep. use the time passed since last message as a hint
|
||||
inline void spdlog::details::async_log_helper::sleep_or_yield(const spdlog::log_clock::time_point& now, const spdlog::log_clock::time_point& last_op_time)
|
||||
{
|
||||
using namespace std::this_thread;
|
||||
using std::chrono::milliseconds;
|
||||
using std::chrono::microseconds;
|
||||
|
||||
auto time_since_op = now - last_op_time;
|
||||
|
||||
// spin upto 50 micros
|
||||
if (time_since_op <= microseconds(50))
|
||||
return;
|
||||
|
||||
// yield upto 150 micros
|
||||
if (time_since_op <= microseconds(100))
|
||||
return yield();
|
||||
|
||||
|
||||
// sleep for 20 ms upto 200 ms
|
||||
if (time_since_op <= milliseconds(200))
|
||||
return sleep_for(milliseconds(20));
|
||||
|
||||
// sleep for 200 ms
|
||||
return sleep_for(milliseconds(200));
|
||||
}
|
||||
|
||||
// wait for the queue to be empty
|
||||
inline void spdlog::details::async_log_helper::wait_empty_q()
|
||||
{
|
||||
auto last_op = details::os::now();
|
||||
while (_q.approx_size() > 0)
|
||||
{
|
||||
sleep_or_yield(details::os::now(), last_op);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
89
include/spdlog/details/async_logger_impl.h
Normal file
89
include/spdlog/details/async_logger_impl.h
Normal file
@ -0,0 +1,89 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
// Async Logger implementation
|
||||
// Use an async_sink (queue per logger) to perform the logging in a worker thread
|
||||
|
||||
#include <spdlog/details/async_log_helper.h>
|
||||
#include <spdlog/async_logger.h>
|
||||
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
|
||||
template<class It>
|
||||
inline spdlog::async_logger::async_logger(const std::string& logger_name,
|
||||
const It& begin,
|
||||
const It& end,
|
||||
size_t queue_size,
|
||||
const async_overflow_policy overflow_policy,
|
||||
const std::function<void()>& worker_warmup_cb,
|
||||
const std::chrono::milliseconds& flush_interval_ms,
|
||||
const std::function<void()>& worker_teardown_cb) :
|
||||
logger(logger_name, begin, end),
|
||||
_async_log_helper(new details::async_log_helper(_formatter, _sinks, queue_size, _err_handler, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb))
|
||||
{
|
||||
}
|
||||
|
||||
inline spdlog::async_logger::async_logger(const std::string& logger_name,
|
||||
sinks_init_list sinks,
|
||||
size_t queue_size,
|
||||
const async_overflow_policy overflow_policy,
|
||||
const std::function<void()>& worker_warmup_cb,
|
||||
const std::chrono::milliseconds& flush_interval_ms,
|
||||
const std::function<void()>& worker_teardown_cb) :
|
||||
async_logger(logger_name, sinks.begin(), sinks.end(), queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) {}
|
||||
|
||||
inline spdlog::async_logger::async_logger(const std::string& logger_name,
|
||||
sink_ptr single_sink,
|
||||
size_t queue_size,
|
||||
const async_overflow_policy overflow_policy,
|
||||
const std::function<void()>& worker_warmup_cb,
|
||||
const std::chrono::milliseconds& flush_interval_ms,
|
||||
const std::function<void()>& worker_teardown_cb) :
|
||||
async_logger(logger_name,
|
||||
{
|
||||
single_sink
|
||||
}, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) {}
|
||||
|
||||
|
||||
inline void spdlog::async_logger::flush()
|
||||
{
|
||||
_async_log_helper->flush(true);
|
||||
}
|
||||
|
||||
inline void spdlog::async_logger::_set_formatter(spdlog::formatter_ptr msg_formatter)
|
||||
{
|
||||
_formatter = msg_formatter;
|
||||
_async_log_helper->set_formatter(_formatter);
|
||||
}
|
||||
|
||||
inline void spdlog::async_logger::_set_pattern(const std::string& pattern)
|
||||
{
|
||||
_formatter = std::make_shared<pattern_formatter>(pattern);
|
||||
_async_log_helper->set_formatter(_formatter);
|
||||
}
|
||||
|
||||
|
||||
inline void spdlog::async_logger::_sink_it(details::log_msg& msg)
|
||||
{
|
||||
try
|
||||
{
|
||||
_async_log_helper->log(msg);
|
||||
if (_should_flush_on(msg))
|
||||
_async_log_helper->flush(false); // do async flush
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
_err_handler(ex.what());
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
_err_handler("Unknown exception");
|
||||
}
|
||||
}
|
@ -1,63 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/details/backtracer.h>
|
||||
#endif
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
SPDLOG_INLINE backtracer::backtracer(const backtracer &other) {
|
||||
std::lock_guard<std::mutex> lock(other.mutex_);
|
||||
enabled_ = other.enabled();
|
||||
messages_ = other.messages_;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE backtracer::backtracer(backtracer &&other) SPDLOG_NOEXCEPT {
|
||||
std::lock_guard<std::mutex> lock(other.mutex_);
|
||||
enabled_ = other.enabled();
|
||||
messages_ = std::move(other.messages_);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE backtracer &backtracer::operator=(backtracer other) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
enabled_ = other.enabled();
|
||||
messages_ = std::move(other.messages_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void backtracer::enable(size_t size) {
|
||||
std::lock_guard<std::mutex> lock{mutex_};
|
||||
enabled_.store(true, std::memory_order_relaxed);
|
||||
messages_ = circular_q<log_msg_buffer>{size};
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void backtracer::disable() {
|
||||
std::lock_guard<std::mutex> lock{mutex_};
|
||||
enabled_.store(false, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE bool backtracer::enabled() const { return enabled_.load(std::memory_order_relaxed); }
|
||||
|
||||
SPDLOG_INLINE void backtracer::push_back(const log_msg &msg) {
|
||||
std::lock_guard<std::mutex> lock{mutex_};
|
||||
messages_.push_back(log_msg_buffer{msg});
|
||||
}
|
||||
|
||||
SPDLOG_INLINE bool backtracer::empty() const {
|
||||
std::lock_guard<std::mutex> lock{mutex_};
|
||||
return messages_.empty();
|
||||
}
|
||||
|
||||
// pop all items in the q and apply the given fun on each of them.
|
||||
SPDLOG_INLINE void backtracer::foreach_pop(std::function<void(const details::log_msg &)> fun) {
|
||||
std::lock_guard<std::mutex> lock{mutex_};
|
||||
while (!messages_.empty()) {
|
||||
auto &front_msg = messages_.front();
|
||||
fun(front_msg);
|
||||
messages_.pop_front();
|
||||
}
|
||||
}
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,45 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/details/circular_q.h>
|
||||
#include <spdlog/details/log_msg_buffer.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
|
||||
// Store log messages in circular buffer.
|
||||
// Useful for storing debug data in case of error/warning happens.
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
class SPDLOG_API backtracer {
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<bool> enabled_{false};
|
||||
circular_q<log_msg_buffer> messages_;
|
||||
|
||||
public:
|
||||
backtracer() = default;
|
||||
backtracer(const backtracer &other);
|
||||
|
||||
backtracer(backtracer &&other) SPDLOG_NOEXCEPT;
|
||||
backtracer &operator=(backtracer other);
|
||||
|
||||
void enable(size_t size);
|
||||
void disable();
|
||||
bool enabled() const;
|
||||
void push_back(const log_msg &msg);
|
||||
bool empty() const;
|
||||
|
||||
// pop all items in the q and apply the given fun on each of them.
|
||||
void foreach_pop(std::function<void(const details::log_msg &)> fun);
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "backtracer-inl.h"
|
||||
#endif
|
@ -1,115 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
// circular q view of std::vector.
|
||||
#pragma once
|
||||
|
||||
#include <cassert>
|
||||
#include <vector>
|
||||
|
||||
#include "spdlog/common.h"
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
template <typename T>
|
||||
class circular_q {
|
||||
size_t max_items_ = 0;
|
||||
typename std::vector<T>::size_type head_ = 0;
|
||||
typename std::vector<T>::size_type tail_ = 0;
|
||||
size_t overrun_counter_ = 0;
|
||||
std::vector<T> v_;
|
||||
|
||||
public:
|
||||
using value_type = T;
|
||||
|
||||
// empty ctor - create a disabled queue with no elements allocated at all
|
||||
circular_q() = default;
|
||||
|
||||
explicit circular_q(size_t max_items)
|
||||
: max_items_(max_items + 1) // one item is reserved as marker for full q
|
||||
,
|
||||
v_(max_items_) {}
|
||||
|
||||
circular_q(const circular_q &) = default;
|
||||
circular_q &operator=(const circular_q &) = default;
|
||||
|
||||
// move cannot be default,
|
||||
// since we need to reset head_, tail_, etc to zero in the moved object
|
||||
circular_q(circular_q &&other) SPDLOG_NOEXCEPT { copy_moveable(std::move(other)); }
|
||||
|
||||
circular_q &operator=(circular_q &&other) SPDLOG_NOEXCEPT {
|
||||
copy_moveable(std::move(other));
|
||||
return *this;
|
||||
}
|
||||
|
||||
// push back, overrun (oldest) item if no room left
|
||||
void push_back(T &&item) {
|
||||
if (max_items_ > 0) {
|
||||
v_[tail_] = std::move(item);
|
||||
tail_ = (tail_ + 1) % max_items_;
|
||||
|
||||
if (tail_ == head_) // overrun last item if full
|
||||
{
|
||||
head_ = (head_ + 1) % max_items_;
|
||||
++overrun_counter_;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return reference to the front item.
|
||||
// If there are no elements in the container, the behavior is undefined.
|
||||
const T &front() const { return v_[head_]; }
|
||||
|
||||
T &front() { return v_[head_]; }
|
||||
|
||||
// Return number of elements actually stored
|
||||
size_t size() const {
|
||||
if (tail_ >= head_) {
|
||||
return tail_ - head_;
|
||||
} else {
|
||||
return max_items_ - (head_ - tail_);
|
||||
}
|
||||
}
|
||||
|
||||
// Return const reference to item by index.
|
||||
// If index is out of range 0…size()-1, the behavior is undefined.
|
||||
const T &at(size_t i) const {
|
||||
assert(i < size());
|
||||
return v_[(head_ + i) % max_items_];
|
||||
}
|
||||
|
||||
// Pop item from front.
|
||||
// If there are no elements in the container, the behavior is undefined.
|
||||
void pop_front() { head_ = (head_ + 1) % max_items_; }
|
||||
|
||||
bool empty() const { return tail_ == head_; }
|
||||
|
||||
bool full() const {
|
||||
// head is ahead of the tail by 1
|
||||
if (max_items_ > 0) {
|
||||
return ((tail_ + 1) % max_items_) == head_;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
size_t overrun_counter() const { return overrun_counter_; }
|
||||
|
||||
void reset_overrun_counter() { overrun_counter_ = 0; }
|
||||
|
||||
private:
|
||||
// copy from other&& and reset it to disabled state
|
||||
void copy_moveable(circular_q &&other) SPDLOG_NOEXCEPT {
|
||||
max_items_ = other.max_items_;
|
||||
head_ = other.head_;
|
||||
tail_ = other.tail_;
|
||||
overrun_counter_ = other.overrun_counter_;
|
||||
v_ = std::move(other.v_);
|
||||
|
||||
// put &&other in disabled, but valid state
|
||||
other.max_items_ = 0;
|
||||
other.head_ = other.tail_ = 0;
|
||||
other.overrun_counter_ = 0;
|
||||
}
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,28 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <mutex>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
struct console_mutex {
|
||||
using mutex_t = std::mutex;
|
||||
static mutex_t &mutex() {
|
||||
static mutex_t s_mutex;
|
||||
return s_mutex;
|
||||
}
|
||||
};
|
||||
|
||||
struct console_nullmutex {
|
||||
using mutex_t = null_mutex;
|
||||
static mutex_t &mutex() {
|
||||
static mutex_t s_mutex;
|
||||
return s_mutex;
|
||||
}
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,153 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/details/file_helper.h>
|
||||
#endif
|
||||
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <tuple>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
SPDLOG_INLINE file_helper::file_helper(const file_event_handlers &event_handlers)
|
||||
: event_handlers_(event_handlers) {}
|
||||
|
||||
SPDLOG_INLINE file_helper::~file_helper() { close(); }
|
||||
|
||||
SPDLOG_INLINE void file_helper::open(const filename_t &fname, bool truncate) {
|
||||
close();
|
||||
filename_ = fname;
|
||||
|
||||
auto *mode = SPDLOG_FILENAME_T("ab");
|
||||
auto *trunc_mode = SPDLOG_FILENAME_T("wb");
|
||||
|
||||
if (event_handlers_.before_open) {
|
||||
event_handlers_.before_open(filename_);
|
||||
}
|
||||
for (int tries = 0; tries < open_tries_; ++tries) {
|
||||
// create containing folder if not exists already.
|
||||
os::create_dir(os::dir_name(fname));
|
||||
if (truncate) {
|
||||
// Truncate by opening-and-closing a tmp file in "wb" mode, always
|
||||
// opening the actual log-we-write-to in "ab" mode, since that
|
||||
// interacts more politely with eternal processes that might
|
||||
// rotate/truncate the file underneath us.
|
||||
std::FILE *tmp;
|
||||
if (os::fopen_s(&tmp, fname, trunc_mode)) {
|
||||
continue;
|
||||
}
|
||||
std::fclose(tmp);
|
||||
}
|
||||
if (!os::fopen_s(&fd_, fname, mode)) {
|
||||
if (event_handlers_.after_open) {
|
||||
event_handlers_.after_open(filename_, fd_);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
details::os::sleep_for_millis(open_interval_);
|
||||
}
|
||||
|
||||
throw_spdlog_ex("Failed opening file " + os::filename_to_str(filename_) + " for writing",
|
||||
errno);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void file_helper::reopen(bool truncate) {
|
||||
if (filename_.empty()) {
|
||||
throw_spdlog_ex("Failed re opening file - was not opened before");
|
||||
}
|
||||
this->open(filename_, truncate);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void file_helper::flush() {
|
||||
if (std::fflush(fd_) != 0) {
|
||||
throw_spdlog_ex("Failed flush to file " + os::filename_to_str(filename_), errno);
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void file_helper::sync() {
|
||||
if (!os::fsync(fd_)) {
|
||||
throw_spdlog_ex("Failed to fsync file " + os::filename_to_str(filename_), errno);
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void file_helper::close() {
|
||||
if (fd_ != nullptr) {
|
||||
if (event_handlers_.before_close) {
|
||||
event_handlers_.before_close(filename_, fd_);
|
||||
}
|
||||
|
||||
std::fclose(fd_);
|
||||
fd_ = nullptr;
|
||||
|
||||
if (event_handlers_.after_close) {
|
||||
event_handlers_.after_close(filename_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void file_helper::write(const memory_buf_t &buf) {
|
||||
if (fd_ == nullptr) return;
|
||||
size_t msg_size = buf.size();
|
||||
auto data = buf.data();
|
||||
|
||||
if (!details::os::fwrite_bytes(data, msg_size, fd_)) {
|
||||
throw_spdlog_ex("Failed writing to file " + os::filename_to_str(filename_), errno);
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE size_t file_helper::size() const {
|
||||
if (fd_ == nullptr) {
|
||||
throw_spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(filename_));
|
||||
}
|
||||
return os::filesize(fd_);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE const filename_t &file_helper::filename() const { return filename_; }
|
||||
|
||||
//
|
||||
// return file path and its extension:
|
||||
//
|
||||
// "mylog.txt" => ("mylog", ".txt")
|
||||
// "mylog" => ("mylog", "")
|
||||
// "mylog." => ("mylog.", "")
|
||||
// "/dir1/dir2/mylog.txt" => ("/dir1/dir2/mylog", ".txt")
|
||||
//
|
||||
// the starting dot in filenames is ignored (hidden files):
|
||||
//
|
||||
// ".mylog" => (".mylog". "")
|
||||
// "my_folder/.mylog" => ("my_folder/.mylog", "")
|
||||
// "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt")
|
||||
SPDLOG_INLINE std::tuple<filename_t, filename_t> file_helper::split_by_extension(
|
||||
const filename_t &fname) {
|
||||
auto ext_index = fname.rfind('.');
|
||||
|
||||
// no valid extension found - return whole path and empty string as
|
||||
// extension
|
||||
if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1) {
|
||||
return std::make_tuple(fname, filename_t());
|
||||
}
|
||||
|
||||
// treat cases like "/etc/rc.d/somelogfile or "/abc/.hiddenfile"
|
||||
auto folder_index = fname.find_last_of(details::os::folder_seps_filename);
|
||||
if (folder_index != filename_t::npos && folder_index >= ext_index - 1) {
|
||||
return std::make_tuple(fname, filename_t());
|
||||
}
|
||||
|
||||
// finally - return a valid base and extension tuple
|
||||
return std::make_tuple(fname.substr(0, ext_index), fname.substr(ext_index));
|
||||
}
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,61 +1,118 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/common.h>
|
||||
#include <tuple>
|
||||
// Helper class for file sink
|
||||
// When failing to open a file, retry several times(5) with small delay between the tries(10 ms)
|
||||
// Can be set to auto flush on every line
|
||||
// Throw spdlog_ex exception on errors
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/details/log_msg.h>
|
||||
|
||||
// Helper class for file sinks.
|
||||
// When failing to open a file, retry several times(5) with a delay interval(10 ms).
|
||||
// Throw spdlog_ex exception on errors.
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <cerrno>
|
||||
|
||||
namespace spdlog
|
||||
{
|
||||
namespace details
|
||||
{
|
||||
|
||||
class file_helper
|
||||
{
|
||||
|
||||
class SPDLOG_API file_helper {
|
||||
public:
|
||||
file_helper() = default;
|
||||
explicit file_helper(const file_event_handlers &event_handlers);
|
||||
const int open_tries = 5;
|
||||
const int open_interval = 10;
|
||||
|
||||
file_helper(const file_helper &) = delete;
|
||||
file_helper &operator=(const file_helper &) = delete;
|
||||
~file_helper();
|
||||
explicit file_helper() :
|
||||
_fd(nullptr)
|
||||
{}
|
||||
|
||||
void open(const filename_t &fname, bool truncate = false);
|
||||
void reopen(bool truncate);
|
||||
void flush();
|
||||
void sync();
|
||||
void close();
|
||||
void write(const memory_buf_t &buf);
|
||||
size_t size() const;
|
||||
const filename_t &filename() const;
|
||||
file_helper(const file_helper&) = delete;
|
||||
file_helper& operator=(const file_helper&) = delete;
|
||||
|
||||
//
|
||||
// return file path and its extension:
|
||||
//
|
||||
// "mylog.txt" => ("mylog", ".txt")
|
||||
// "mylog" => ("mylog", "")
|
||||
// "mylog." => ("mylog.", "")
|
||||
// "/dir1/dir2/mylog.txt" => ("/dir1/dir2/mylog", ".txt")
|
||||
//
|
||||
// the starting dot in filenames is ignored (hidden files):
|
||||
//
|
||||
// ".mylog" => (".mylog". "")
|
||||
// "my_folder/.mylog" => ("my_folder/.mylog", "")
|
||||
// "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt")
|
||||
static std::tuple<filename_t, filename_t> split_by_extension(const filename_t &fname);
|
||||
~file_helper()
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
|
||||
void open(const filename_t& fname, bool truncate = false)
|
||||
{
|
||||
|
||||
close();
|
||||
auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab");
|
||||
_filename = fname;
|
||||
for (int tries = 0; tries < open_tries; ++tries)
|
||||
{
|
||||
if (!os::fopen_s(&_fd, fname, mode))
|
||||
return;
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(open_interval));
|
||||
}
|
||||
|
||||
throw spdlog_ex("Failed opening file " + os::filename_to_str(_filename) + " for writing", errno);
|
||||
}
|
||||
|
||||
void reopen(bool truncate)
|
||||
{
|
||||
if (_filename.empty())
|
||||
throw spdlog_ex("Failed re opening file - was not opened before");
|
||||
open(_filename, truncate);
|
||||
|
||||
}
|
||||
|
||||
void flush()
|
||||
{
|
||||
std::fflush(_fd);
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
if (_fd)
|
||||
{
|
||||
std::fclose(_fd);
|
||||
_fd = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void write(const log_msg& msg)
|
||||
{
|
||||
|
||||
size_t msg_size = msg.formatted.size();
|
||||
auto data = msg.formatted.data();
|
||||
if (std::fwrite(data, 1, msg_size, _fd) != msg_size)
|
||||
throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno);
|
||||
}
|
||||
|
||||
size_t size()
|
||||
{
|
||||
if (!_fd)
|
||||
throw spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(_filename));
|
||||
return os::filesize(_fd);
|
||||
}
|
||||
|
||||
const filename_t& filename() const
|
||||
{
|
||||
return _filename;
|
||||
}
|
||||
|
||||
static bool file_exists(const filename_t& name)
|
||||
{
|
||||
|
||||
return os::file_exists(name);
|
||||
}
|
||||
|
||||
private:
|
||||
const int open_tries_ = 5;
|
||||
const unsigned int open_interval_ = 10;
|
||||
std::FILE *fd_{nullptr};
|
||||
filename_t filename_;
|
||||
file_event_handlers event_handlers_;
|
||||
FILE* _fd;
|
||||
filename_t _filename;
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "file_helper-inl.h"
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
@ -1,141 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <iterator>
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/fmt/fmt.h>
|
||||
#include <type_traits>
|
||||
|
||||
#ifdef SPDLOG_USE_STD_FORMAT
|
||||
#include <charconv>
|
||||
#include <limits>
|
||||
#endif
|
||||
|
||||
// Some fmt helpers to efficiently format and pad ints and strings
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
namespace fmt_helper {
|
||||
|
||||
inline void append_string_view(spdlog::string_view_t view, memory_buf_t &dest) {
|
||||
auto *buf_ptr = view.data();
|
||||
dest.append(buf_ptr, buf_ptr + view.size());
|
||||
}
|
||||
|
||||
#ifdef SPDLOG_USE_STD_FORMAT
|
||||
template <typename T>
|
||||
inline void append_int(T n, memory_buf_t &dest) {
|
||||
// Buffer should be large enough to hold all digits (digits10 + 1) and a sign
|
||||
SPDLOG_CONSTEXPR const auto BUF_SIZE = std::numeric_limits<T>::digits10 + 2;
|
||||
char buf[BUF_SIZE];
|
||||
|
||||
auto [ptr, ec] = std::to_chars(buf, buf + BUF_SIZE, n, 10);
|
||||
if (ec == std::errc()) {
|
||||
dest.append(buf, ptr);
|
||||
} else {
|
||||
throw_spdlog_ex("Failed to format int", static_cast<int>(ec));
|
||||
}
|
||||
}
|
||||
#else
|
||||
template <typename T>
|
||||
inline void append_int(T n, memory_buf_t &dest) {
|
||||
fmt::format_int i(n);
|
||||
dest.append(i.data(), i.data() + i.size());
|
||||
}
|
||||
#endif
|
||||
|
||||
template <typename T>
|
||||
SPDLOG_CONSTEXPR_FUNC unsigned int count_digits_fallback(T n) {
|
||||
// taken from fmt: https://github.com/fmtlib/fmt/blob/8.0.1/include/fmt/format.h#L899-L912
|
||||
unsigned int count = 1;
|
||||
for (;;) {
|
||||
// Integer division is slow so do it for a group of four digits instead
|
||||
// of for every digit. The idea comes from the talk by Alexandrescu
|
||||
// "Three Optimization Tips for C++". See speed-test for a comparison.
|
||||
if (n < 10) return count;
|
||||
if (n < 100) return count + 1;
|
||||
if (n < 1000) return count + 2;
|
||||
if (n < 10000) return count + 3;
|
||||
n /= 10000u;
|
||||
count += 4;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline unsigned int count_digits(T n) {
|
||||
using count_type =
|
||||
typename std::conditional<(sizeof(T) > sizeof(uint32_t)), uint64_t, uint32_t>::type;
|
||||
#ifdef SPDLOG_USE_STD_FORMAT
|
||||
return count_digits_fallback(static_cast<count_type>(n));
|
||||
#else
|
||||
return static_cast<unsigned int>(fmt::
|
||||
// fmt 7.0.0 renamed the internal namespace to detail.
|
||||
// See: https://github.com/fmtlib/fmt/issues/1538
|
||||
#if FMT_VERSION < 70000
|
||||
internal
|
||||
#else
|
||||
detail
|
||||
#endif
|
||||
::count_digits(static_cast<count_type>(n)));
|
||||
#endif
|
||||
}
|
||||
|
||||
inline void pad2(int n, memory_buf_t &dest) {
|
||||
if (n >= 0 && n < 100) // 0-99
|
||||
{
|
||||
dest.push_back(static_cast<char>('0' + n / 10));
|
||||
dest.push_back(static_cast<char>('0' + n % 10));
|
||||
} else // unlikely, but just in case, let fmt deal with it
|
||||
{
|
||||
fmt_lib::format_to(std::back_inserter(dest), SPDLOG_FMT_STRING("{:02}"), n);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline void pad_uint(T n, unsigned int width, memory_buf_t &dest) {
|
||||
static_assert(std::is_unsigned<T>::value, "pad_uint must get unsigned T");
|
||||
for (auto digits = count_digits(n); digits < width; digits++) {
|
||||
dest.push_back('0');
|
||||
}
|
||||
append_int(n, dest);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline void pad3(T n, memory_buf_t &dest) {
|
||||
static_assert(std::is_unsigned<T>::value, "pad3 must get unsigned T");
|
||||
if (n < 1000) {
|
||||
dest.push_back(static_cast<char>(n / 100 + '0'));
|
||||
n = n % 100;
|
||||
dest.push_back(static_cast<char>((n / 10) + '0'));
|
||||
dest.push_back(static_cast<char>((n % 10) + '0'));
|
||||
} else {
|
||||
append_int(n, dest);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline void pad6(T n, memory_buf_t &dest) {
|
||||
pad_uint(n, 6, dest);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline void pad9(T n, memory_buf_t &dest) {
|
||||
pad_uint(n, 9, dest);
|
||||
}
|
||||
|
||||
// return fraction of a second of the given time_point.
|
||||
// e.g.
|
||||
// fraction<std::milliseconds>(tp) -> will return the millis part of the second
|
||||
template <typename ToDuration>
|
||||
inline ToDuration time_fraction(log_clock::time_point tp) {
|
||||
using std::chrono::duration_cast;
|
||||
using std::chrono::seconds;
|
||||
auto duration = tp.time_since_epoch();
|
||||
auto secs = duration_cast<seconds>(duration);
|
||||
return duration_cast<ToDuration>(duration) - duration_cast<ToDuration>(secs);
|
||||
}
|
||||
|
||||
} // namespace fmt_helper
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,44 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/details/log_msg.h>
|
||||
#endif
|
||||
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
SPDLOG_INLINE log_msg::log_msg(spdlog::log_clock::time_point log_time,
|
||||
spdlog::source_loc loc,
|
||||
string_view_t a_logger_name,
|
||||
spdlog::level::level_enum lvl,
|
||||
spdlog::string_view_t msg)
|
||||
: logger_name(a_logger_name),
|
||||
level(lvl),
|
||||
time(log_time)
|
||||
#ifndef SPDLOG_NO_THREAD_ID
|
||||
,
|
||||
thread_id(os::thread_id())
|
||||
#endif
|
||||
,
|
||||
source(loc),
|
||||
payload(msg) {
|
||||
}
|
||||
|
||||
SPDLOG_INLINE log_msg::log_msg(spdlog::source_loc loc,
|
||||
string_view_t a_logger_name,
|
||||
spdlog::level::level_enum lvl,
|
||||
spdlog::string_view_t msg)
|
||||
: log_msg(os::now(), loc, a_logger_name, lvl, msg) {}
|
||||
|
||||
SPDLOG_INLINE log_msg::log_msg(string_view_t a_logger_name,
|
||||
spdlog::level::level_enum lvl,
|
||||
spdlog::string_view_t msg)
|
||||
: log_msg(os::now(), source_loc{}, a_logger_name, lvl, msg) {}
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,40 +1,46 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
struct SPDLOG_API log_msg {
|
||||
namespace spdlog
|
||||
{
|
||||
namespace details
|
||||
{
|
||||
struct log_msg
|
||||
{
|
||||
log_msg() = default;
|
||||
log_msg(log_clock::time_point log_time,
|
||||
source_loc loc,
|
||||
string_view_t logger_name,
|
||||
level::level_enum lvl,
|
||||
string_view_t msg);
|
||||
log_msg(source_loc loc, string_view_t logger_name, level::level_enum lvl, string_view_t msg);
|
||||
log_msg(string_view_t logger_name, level::level_enum lvl, string_view_t msg);
|
||||
log_msg(const log_msg &other) = default;
|
||||
log_msg &operator=(const log_msg &other) = default;
|
||||
|
||||
string_view_t logger_name;
|
||||
level::level_enum level{level::off};
|
||||
log_clock::time_point time;
|
||||
size_t thread_id{0};
|
||||
|
||||
// wrapping the formatted text with color (updated by pattern_formatter).
|
||||
mutable size_t color_range_start{0};
|
||||
mutable size_t color_range_end{0};
|
||||
|
||||
source_loc source;
|
||||
string_view_t payload;
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "log_msg-inl.h"
|
||||
log_msg(const std::string *loggers_name, level::level_enum lvl) : logger_name(loggers_name), level(lvl)
|
||||
{
|
||||
#ifndef SPDLOG_NO_DATETIME
|
||||
time = os::now();
|
||||
#endif
|
||||
|
||||
#ifndef SPDLOG_NO_THREAD_ID
|
||||
thread_id = os::thread_id();
|
||||
#endif
|
||||
}
|
||||
|
||||
log_msg(const log_msg& other) = delete;
|
||||
log_msg& operator=(log_msg&& other) = delete;
|
||||
log_msg(log_msg&& other) = delete;
|
||||
|
||||
|
||||
const std::string *logger_name;
|
||||
level::level_enum level;
|
||||
log_clock::time_point time;
|
||||
size_t thread_id;
|
||||
fmt::MemoryWriter raw;
|
||||
fmt::MemoryWriter formatted;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -1,54 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/details/log_msg_buffer.h>
|
||||
#endif
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
SPDLOG_INLINE log_msg_buffer::log_msg_buffer(const log_msg &orig_msg)
|
||||
: log_msg{orig_msg} {
|
||||
buffer.append(logger_name.begin(), logger_name.end());
|
||||
buffer.append(payload.begin(), payload.end());
|
||||
update_string_views();
|
||||
}
|
||||
|
||||
SPDLOG_INLINE log_msg_buffer::log_msg_buffer(const log_msg_buffer &other)
|
||||
: log_msg{other} {
|
||||
buffer.append(logger_name.begin(), logger_name.end());
|
||||
buffer.append(payload.begin(), payload.end());
|
||||
update_string_views();
|
||||
}
|
||||
|
||||
SPDLOG_INLINE log_msg_buffer::log_msg_buffer(log_msg_buffer &&other) SPDLOG_NOEXCEPT
|
||||
: log_msg{other},
|
||||
buffer{std::move(other.buffer)} {
|
||||
update_string_views();
|
||||
}
|
||||
|
||||
SPDLOG_INLINE log_msg_buffer &log_msg_buffer::operator=(const log_msg_buffer &other) {
|
||||
log_msg::operator=(other);
|
||||
buffer.clear();
|
||||
buffer.append(other.buffer.data(), other.buffer.data() + other.buffer.size());
|
||||
update_string_views();
|
||||
return *this;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE log_msg_buffer &log_msg_buffer::operator=(log_msg_buffer &&other) SPDLOG_NOEXCEPT {
|
||||
log_msg::operator=(other);
|
||||
buffer = std::move(other.buffer);
|
||||
update_string_views();
|
||||
return *this;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void log_msg_buffer::update_string_views() {
|
||||
logger_name = string_view_t{buffer.data(), logger_name.size()};
|
||||
payload = string_view_t{buffer.data() + logger_name.size(), payload.size()};
|
||||
}
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,32 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/details/log_msg.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
// Extend log_msg with internal buffer to store its payload.
|
||||
// This is needed since log_msg holds string_views that points to stack data.
|
||||
|
||||
class SPDLOG_API log_msg_buffer : public log_msg {
|
||||
memory_buf_t buffer;
|
||||
void update_string_views();
|
||||
|
||||
public:
|
||||
log_msg_buffer() = default;
|
||||
explicit log_msg_buffer(const log_msg &orig_msg);
|
||||
log_msg_buffer(const log_msg_buffer &other);
|
||||
log_msg_buffer(log_msg_buffer &&other) SPDLOG_NOEXCEPT;
|
||||
log_msg_buffer &operator=(const log_msg_buffer &other);
|
||||
log_msg_buffer &operator=(log_msg_buffer &&other) SPDLOG_NOEXCEPT;
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "log_msg_buffer-inl.h"
|
||||
#endif
|
293
include/spdlog/details/logger_impl.h
Normal file
293
include/spdlog/details/logger_impl.h
Normal file
@ -0,0 +1,293 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/logger.h>
|
||||
#include <spdlog/sinks/stdout_sinks.h>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
|
||||
// create logger with given name, sinks and the default pattern formatter
|
||||
// all other ctors will call this one
|
||||
template<class It>
|
||||
inline spdlog::logger::logger(const std::string& logger_name, const It& begin, const It& end):
|
||||
_name(logger_name),
|
||||
_sinks(begin, end),
|
||||
_formatter(std::make_shared<pattern_formatter>("%+"))
|
||||
{
|
||||
_level = level::info;
|
||||
_flush_level = level::off;
|
||||
_last_err_time = 0;
|
||||
_err_handler = [this](const std::string &msg)
|
||||
{
|
||||
this->_default_err_handler(msg);
|
||||
};
|
||||
}
|
||||
|
||||
// ctor with sinks as init list
|
||||
inline spdlog::logger::logger(const std::string& logger_name, sinks_init_list sinks_list):
|
||||
logger(logger_name, sinks_list.begin(), sinks_list.end())
|
||||
{}
|
||||
|
||||
|
||||
// ctor with single sink
|
||||
inline spdlog::logger::logger(const std::string& logger_name, spdlog::sink_ptr single_sink):
|
||||
logger(logger_name,
|
||||
{
|
||||
single_sink
|
||||
})
|
||||
{}
|
||||
|
||||
|
||||
inline spdlog::logger::~logger() = default;
|
||||
|
||||
|
||||
inline void spdlog::logger::set_formatter(spdlog::formatter_ptr msg_formatter)
|
||||
{
|
||||
_set_formatter(msg_formatter);
|
||||
}
|
||||
|
||||
inline void spdlog::logger::set_pattern(const std::string& pattern)
|
||||
{
|
||||
_set_pattern(pattern);
|
||||
}
|
||||
|
||||
|
||||
template <typename... Args>
|
||||
inline void spdlog::logger::log(level::level_enum lvl, const char* fmt, const Args&... args)
|
||||
{
|
||||
if (!should_log(lvl)) return;
|
||||
|
||||
try
|
||||
{
|
||||
details::log_msg log_msg(&_name, lvl);
|
||||
log_msg.raw.write(fmt, args...);
|
||||
_sink_it(log_msg);
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
_err_handler(ex.what());
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
_err_handler("Unknown exception");
|
||||
}
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
inline void spdlog::logger::log(level::level_enum lvl, const char* msg)
|
||||
{
|
||||
if (!should_log(lvl)) return;
|
||||
try
|
||||
{
|
||||
details::log_msg log_msg(&_name, lvl);
|
||||
log_msg.raw << msg;
|
||||
_sink_it(log_msg);
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
_err_handler(ex.what());
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
_err_handler("Unknown exception");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
inline void spdlog::logger::log(level::level_enum lvl, const T& msg)
|
||||
{
|
||||
if (!should_log(lvl)) return;
|
||||
try
|
||||
{
|
||||
details::log_msg log_msg(&_name, lvl);
|
||||
log_msg.raw << msg;
|
||||
_sink_it(log_msg);
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
_err_handler(ex.what());
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
_err_handler("Unknown exception");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
template <typename... Args>
|
||||
inline void spdlog::logger::trace(const char* fmt, const Args&... args)
|
||||
{
|
||||
log(level::trace, fmt, args...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
inline void spdlog::logger::debug(const char* fmt, const Args&... args)
|
||||
{
|
||||
log(level::debug, fmt, args...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
inline void spdlog::logger::info(const char* fmt, const Args&... args)
|
||||
{
|
||||
log(level::info, fmt, args...);
|
||||
}
|
||||
|
||||
|
||||
template <typename... Args>
|
||||
inline void spdlog::logger::warn(const char* fmt, const Args&... args)
|
||||
{
|
||||
log(level::warn, fmt, args...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
inline void spdlog::logger::error(const char* fmt, const Args&... args)
|
||||
{
|
||||
log(level::err, fmt, args...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
inline void spdlog::logger::critical(const char* fmt, const Args&... args)
|
||||
{
|
||||
log(level::critical, fmt, args...);
|
||||
}
|
||||
|
||||
|
||||
template<typename T>
|
||||
inline void spdlog::logger::trace(const T& msg)
|
||||
{
|
||||
log(level::trace, msg);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
inline void spdlog::logger::debug(const T& msg)
|
||||
{
|
||||
log(level::debug, msg);
|
||||
}
|
||||
|
||||
|
||||
template<typename T>
|
||||
inline void spdlog::logger::info(const T& msg)
|
||||
{
|
||||
log(level::info, msg);
|
||||
}
|
||||
|
||||
|
||||
template<typename T>
|
||||
inline void spdlog::logger::warn(const T& msg)
|
||||
{
|
||||
log(level::warn, msg);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
inline void spdlog::logger::error(const T& msg)
|
||||
{
|
||||
log(level::err, msg);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
inline void spdlog::logger::critical(const T& msg)
|
||||
{
|
||||
log(level::critical, msg);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//
|
||||
// name and level
|
||||
//
|
||||
inline const std::string& spdlog::logger::name() const
|
||||
{
|
||||
return _name;
|
||||
}
|
||||
|
||||
inline void spdlog::logger::set_level(spdlog::level::level_enum log_level)
|
||||
{
|
||||
_level.store(log_level);
|
||||
}
|
||||
|
||||
inline void spdlog::logger::set_error_handler(spdlog::log_err_handler err_handler)
|
||||
{
|
||||
_err_handler = err_handler;
|
||||
}
|
||||
|
||||
inline spdlog::log_err_handler spdlog::logger::error_handler()
|
||||
{
|
||||
return _err_handler;
|
||||
}
|
||||
|
||||
|
||||
inline void spdlog::logger::flush_on(level::level_enum log_level)
|
||||
{
|
||||
_flush_level.store(log_level);
|
||||
}
|
||||
|
||||
inline spdlog::level::level_enum spdlog::logger::level() const
|
||||
{
|
||||
return static_cast<spdlog::level::level_enum>(_level.load(std::memory_order_relaxed));
|
||||
}
|
||||
|
||||
inline bool spdlog::logger::should_log(spdlog::level::level_enum msg_level) const
|
||||
{
|
||||
return msg_level >= _level.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
//
|
||||
// protected virtual called at end of each user log call (if enabled) by the line_logger
|
||||
//
|
||||
inline void spdlog::logger::_sink_it(details::log_msg& msg)
|
||||
{
|
||||
_formatter->format(msg);
|
||||
for (auto &sink : _sinks)
|
||||
{
|
||||
if( sink->should_log( msg.level))
|
||||
{
|
||||
sink->log(msg);
|
||||
}
|
||||
}
|
||||
|
||||
if(_should_flush_on(msg))
|
||||
flush();
|
||||
}
|
||||
|
||||
inline void spdlog::logger::_set_pattern(const std::string& pattern)
|
||||
{
|
||||
_formatter = std::make_shared<pattern_formatter>(pattern);
|
||||
}
|
||||
inline void spdlog::logger::_set_formatter(formatter_ptr msg_formatter)
|
||||
{
|
||||
_formatter = msg_formatter;
|
||||
}
|
||||
|
||||
inline void spdlog::logger::flush()
|
||||
{
|
||||
for (auto& sink : _sinks)
|
||||
sink->flush();
|
||||
}
|
||||
|
||||
inline void spdlog::logger::_default_err_handler(const std::string &msg)
|
||||
{
|
||||
auto now = time(nullptr);
|
||||
if (now - _last_err_time < 60)
|
||||
return;
|
||||
auto tm_time = details::os::localtime(now);
|
||||
char date_buf[100];
|
||||
std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", &tm_time);
|
||||
details::log_msg err_msg;
|
||||
err_msg.formatted.write("[*** LOG ERROR ***] [{}] [{}] [{}]{}", name(), msg, date_buf, details::os::eol);
|
||||
sinks::stderr_sink_mt::instance()->log(err_msg);
|
||||
_last_err_time = now;
|
||||
}
|
||||
|
||||
inline bool spdlog::logger::_should_flush_on(const details::log_msg &msg)
|
||||
{
|
||||
const auto flush_level = _flush_level.load(std::memory_order_relaxed);
|
||||
return (msg.level >= flush_level) && (msg.level != level::off);
|
||||
}
|
@ -1,177 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
// multi producer-multi consumer blocking queue.
|
||||
// enqueue(..) - will block until room found to put the new message.
|
||||
// enqueue_nowait(..) - will return immediately with false if no room left in
|
||||
// the queue.
|
||||
// dequeue_for(..) - will block until the queue is not empty or timeout have
|
||||
// passed.
|
||||
|
||||
#include <spdlog/details/circular_q.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
template <typename T>
|
||||
class mpmc_blocking_queue {
|
||||
public:
|
||||
using item_type = T;
|
||||
explicit mpmc_blocking_queue(size_t max_items)
|
||||
: q_(max_items) {}
|
||||
|
||||
#ifndef __MINGW32__
|
||||
// try to enqueue and block if no room left
|
||||
void enqueue(T &&item) {
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
pop_cv_.wait(lock, [this] { return !this->q_.full(); });
|
||||
q_.push_back(std::move(item));
|
||||
}
|
||||
push_cv_.notify_one();
|
||||
}
|
||||
|
||||
// enqueue immediately. overrun oldest message in the queue if no room left.
|
||||
void enqueue_nowait(T &&item) {
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
q_.push_back(std::move(item));
|
||||
}
|
||||
push_cv_.notify_one();
|
||||
}
|
||||
|
||||
void enqueue_if_have_room(T &&item) {
|
||||
bool pushed = false;
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
if (!q_.full()) {
|
||||
q_.push_back(std::move(item));
|
||||
pushed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (pushed) {
|
||||
push_cv_.notify_one();
|
||||
} else {
|
||||
++discard_counter_;
|
||||
}
|
||||
}
|
||||
|
||||
// dequeue with a timeout.
|
||||
// Return true, if succeeded dequeue item, false otherwise
|
||||
bool dequeue_for(T &popped_item, std::chrono::milliseconds wait_duration) {
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
if (!push_cv_.wait_for(lock, wait_duration, [this] { return !this->q_.empty(); })) {
|
||||
return false;
|
||||
}
|
||||
popped_item = std::move(q_.front());
|
||||
q_.pop_front();
|
||||
}
|
||||
pop_cv_.notify_one();
|
||||
return true;
|
||||
}
|
||||
|
||||
// blocking dequeue without a timeout.
|
||||
void dequeue(T &popped_item) {
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
push_cv_.wait(lock, [this] { return !this->q_.empty(); });
|
||||
popped_item = std::move(q_.front());
|
||||
q_.pop_front();
|
||||
}
|
||||
pop_cv_.notify_one();
|
||||
}
|
||||
|
||||
#else
|
||||
// apparently mingw deadlocks if the mutex is released before cv.notify_one(),
|
||||
// so release the mutex at the very end each function.
|
||||
|
||||
// try to enqueue and block if no room left
|
||||
void enqueue(T &&item) {
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
pop_cv_.wait(lock, [this] { return !this->q_.full(); });
|
||||
q_.push_back(std::move(item));
|
||||
push_cv_.notify_one();
|
||||
}
|
||||
|
||||
// enqueue immediately. overrun oldest message in the queue if no room left.
|
||||
void enqueue_nowait(T &&item) {
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
q_.push_back(std::move(item));
|
||||
push_cv_.notify_one();
|
||||
}
|
||||
|
||||
void enqueue_if_have_room(T &&item) {
|
||||
bool pushed = false;
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
if (!q_.full()) {
|
||||
q_.push_back(std::move(item));
|
||||
pushed = true;
|
||||
}
|
||||
|
||||
if (pushed) {
|
||||
push_cv_.notify_one();
|
||||
} else {
|
||||
++discard_counter_;
|
||||
}
|
||||
}
|
||||
|
||||
// dequeue with a timeout.
|
||||
// Return true, if succeeded dequeue item, false otherwise
|
||||
bool dequeue_for(T &popped_item, std::chrono::milliseconds wait_duration) {
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
if (!push_cv_.wait_for(lock, wait_duration, [this] { return !this->q_.empty(); })) {
|
||||
return false;
|
||||
}
|
||||
popped_item = std::move(q_.front());
|
||||
q_.pop_front();
|
||||
pop_cv_.notify_one();
|
||||
return true;
|
||||
}
|
||||
|
||||
// blocking dequeue without a timeout.
|
||||
void dequeue(T &popped_item) {
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
push_cv_.wait(lock, [this] { return !this->q_.empty(); });
|
||||
popped_item = std::move(q_.front());
|
||||
q_.pop_front();
|
||||
pop_cv_.notify_one();
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
size_t overrun_counter() {
|
||||
std::lock_guard<std::mutex> lock(queue_mutex_);
|
||||
return q_.overrun_counter();
|
||||
}
|
||||
|
||||
size_t discard_counter() { return discard_counter_.load(std::memory_order_relaxed); }
|
||||
|
||||
size_t size() {
|
||||
std::lock_guard<std::mutex> lock(queue_mutex_);
|
||||
return q_.size();
|
||||
}
|
||||
|
||||
void reset_overrun_counter() {
|
||||
std::lock_guard<std::mutex> lock(queue_mutex_);
|
||||
q_.reset_overrun_counter();
|
||||
}
|
||||
|
||||
void reset_discard_counter() { discard_counter_.store(0, std::memory_order_relaxed); }
|
||||
|
||||
private:
|
||||
std::mutex queue_mutex_;
|
||||
std::condition_variable push_cv_;
|
||||
std::condition_variable pop_cv_;
|
||||
spdlog::details::circular_q<T> q_;
|
||||
std::atomic<size_t> discard_counter_{0};
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
172
include/spdlog/details/mpmc_bounded_q.h
Normal file
172
include/spdlog/details/mpmc_bounded_q.h
Normal file
@ -0,0 +1,172 @@
|
||||
/*
|
||||
A modified version of Bounded MPMC queue by Dmitry Vyukov.
|
||||
|
||||
Original code from:
|
||||
http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue
|
||||
|
||||
licensed by Dmitry Vyukov under the terms below:
|
||||
|
||||
Simplified BSD license
|
||||
|
||||
Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of
|
||||
conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list
|
||||
of conditions and the following disclaimer in the documentation and/or other materials
|
||||
provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "AS IS" AND ANY EXPRESS OR IMPLIED
|
||||
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
SHALL DMITRY VYUKOV OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
|
||||
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
|
||||
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
|
||||
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
The views and conclusions contained in the software and documentation are those of the authors and
|
||||
should not be interpreted as representing official policies, either expressed or implied, of Dmitry Vyukov.
|
||||
*/
|
||||
|
||||
/*
|
||||
The code in its current form adds the license below:
|
||||
|
||||
Copyright(c) 2015 Gabi Melman.
|
||||
Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/common.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <utility>
|
||||
|
||||
namespace spdlog
|
||||
{
|
||||
namespace details
|
||||
{
|
||||
|
||||
template<typename T>
|
||||
class mpmc_bounded_queue
|
||||
{
|
||||
public:
|
||||
|
||||
using item_type = T;
|
||||
mpmc_bounded_queue(size_t buffer_size)
|
||||
:max_size_(buffer_size),
|
||||
buffer_(new cell_t [buffer_size]),
|
||||
buffer_mask_(buffer_size - 1)
|
||||
{
|
||||
//queue size must be power of two
|
||||
if(!((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0)))
|
||||
throw spdlog_ex("async logger queue size must be power of two");
|
||||
|
||||
for (size_t i = 0; i != buffer_size; i += 1)
|
||||
buffer_[i].sequence_.store(i, std::memory_order_relaxed);
|
||||
enqueue_pos_.store(0, std::memory_order_relaxed);
|
||||
dequeue_pos_.store(0, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
~mpmc_bounded_queue()
|
||||
{
|
||||
delete [] buffer_;
|
||||
}
|
||||
|
||||
|
||||
bool enqueue(T&& data)
|
||||
{
|
||||
cell_t* cell;
|
||||
size_t pos = enqueue_pos_.load(std::memory_order_relaxed);
|
||||
for (;;)
|
||||
{
|
||||
cell = &buffer_[pos & buffer_mask_];
|
||||
size_t seq = cell->sequence_.load(std::memory_order_acquire);
|
||||
intptr_t dif = (intptr_t)seq - (intptr_t)pos;
|
||||
if (dif == 0)
|
||||
{
|
||||
if (enqueue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed))
|
||||
break;
|
||||
}
|
||||
else if (dif < 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
pos = enqueue_pos_.load(std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
cell->data_ = std::move(data);
|
||||
cell->sequence_.store(pos + 1, std::memory_order_release);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool dequeue(T& data)
|
||||
{
|
||||
cell_t* cell;
|
||||
size_t pos = dequeue_pos_.load(std::memory_order_relaxed);
|
||||
for (;;)
|
||||
{
|
||||
cell = &buffer_[pos & buffer_mask_];
|
||||
size_t seq =
|
||||
cell->sequence_.load(std::memory_order_acquire);
|
||||
intptr_t dif = (intptr_t)seq - (intptr_t)(pos + 1);
|
||||
if (dif == 0)
|
||||
{
|
||||
if (dequeue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed))
|
||||
break;
|
||||
}
|
||||
else if (dif < 0)
|
||||
return false;
|
||||
else
|
||||
pos = dequeue_pos_.load(std::memory_order_relaxed);
|
||||
}
|
||||
data = std::move(cell->data_);
|
||||
cell->sequence_.store(pos + buffer_mask_ + 1, std::memory_order_release);
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t approx_size()
|
||||
{
|
||||
size_t first_pos = dequeue_pos_.load(std::memory_order_relaxed);
|
||||
size_t last_pos = enqueue_pos_.load(std::memory_order_relaxed);
|
||||
if (last_pos <= first_pos)
|
||||
return 0;
|
||||
auto size = last_pos - first_pos;
|
||||
return size < max_size_ ? size : max_size_;
|
||||
}
|
||||
|
||||
private:
|
||||
struct cell_t
|
||||
{
|
||||
std::atomic<size_t> sequence_;
|
||||
T data_;
|
||||
};
|
||||
|
||||
size_t const max_size_;
|
||||
|
||||
static size_t const cacheline_size = 64;
|
||||
typedef char cacheline_pad_t [cacheline_size];
|
||||
|
||||
cacheline_pad_t pad0_;
|
||||
cell_t* const buffer_;
|
||||
size_t const buffer_mask_;
|
||||
cacheline_pad_t pad1_;
|
||||
std::atomic<size_t> enqueue_pos_;
|
||||
cacheline_pad_t pad2_;
|
||||
std::atomic<size_t> dequeue_pos_;
|
||||
cacheline_pad_t pad3_;
|
||||
|
||||
mpmc_bounded_queue(mpmc_bounded_queue const&) = delete;
|
||||
void operator= (mpmc_bounded_queue const&) = delete;
|
||||
};
|
||||
|
||||
} // ns details
|
||||
} // ns spdlog
|
@ -1,35 +1,45 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <utility>
|
||||
// null, no cost dummy "mutex" and dummy "atomic" int
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
struct null_mutex {
|
||||
void lock() const {}
|
||||
void unlock() const {}
|
||||
};
|
||||
|
||||
struct null_atomic_int {
|
||||
int value;
|
||||
null_atomic_int() = default;
|
||||
|
||||
explicit null_atomic_int(int new_value)
|
||||
: value(new_value) {}
|
||||
|
||||
int load(std::memory_order = std::memory_order_relaxed) const { return value; }
|
||||
|
||||
void store(int new_value, std::memory_order = std::memory_order_relaxed) { value = new_value; }
|
||||
|
||||
int exchange(int new_value, std::memory_order = std::memory_order_relaxed) {
|
||||
std::swap(new_value, value);
|
||||
return new_value; // return value before the call
|
||||
namespace spdlog
|
||||
{
|
||||
namespace details
|
||||
{
|
||||
struct null_mutex
|
||||
{
|
||||
void lock() {}
|
||||
void unlock() {}
|
||||
bool try_lock()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
struct null_atomic_int
|
||||
{
|
||||
int value;
|
||||
null_atomic_int() = default;
|
||||
|
||||
null_atomic_int(int val):value(val)
|
||||
{}
|
||||
|
||||
int load(std::memory_order) const
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
void store(int val)
|
||||
{
|
||||
value = val;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -1,607 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/details/os.h>
|
||||
#endif
|
||||
|
||||
#include <spdlog/common.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <string>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <thread>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <spdlog/details/windows_include.h>
|
||||
#include <fileapi.h> // for FlushFileBuffers
|
||||
#include <io.h> // for _get_osfhandle, _isatty, _fileno
|
||||
#include <process.h> // for _get_pid
|
||||
|
||||
#ifdef __MINGW32__
|
||||
#include <share.h>
|
||||
#endif
|
||||
|
||||
#if defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)
|
||||
#include <cassert>
|
||||
#include <limits>
|
||||
#endif
|
||||
|
||||
#include <direct.h> // for _mkdir/_wmkdir
|
||||
|
||||
#else // unix
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef __linux__
|
||||
#include <sys/syscall.h> //Use gettid() syscall under linux to get thread id
|
||||
|
||||
#elif defined(_AIX)
|
||||
#include <pthread.h> // for pthread_getthrds_np
|
||||
|
||||
#elif defined(__DragonFly__) || defined(__FreeBSD__)
|
||||
#include <pthread_np.h> // for pthread_getthreadid_np
|
||||
|
||||
#elif defined(__NetBSD__)
|
||||
#include <lwp.h> // for _lwp_self
|
||||
|
||||
#elif defined(__sun)
|
||||
#include <thread.h> // for thr_self
|
||||
#endif
|
||||
|
||||
#endif // unix
|
||||
|
||||
#if defined __APPLE__
|
||||
#include <AvailabilityMacros.h>
|
||||
#endif
|
||||
|
||||
#ifndef __has_feature // Clang - feature checking macros.
|
||||
#define __has_feature(x) 0 // Compatibility with non-clang compilers.
|
||||
#endif
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
namespace os {
|
||||
|
||||
SPDLOG_INLINE spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT {
|
||||
#if defined __linux__ && defined SPDLOG_CLOCK_COARSE
|
||||
timespec ts;
|
||||
::clock_gettime(CLOCK_REALTIME_COARSE, &ts);
|
||||
return std::chrono::time_point<log_clock, typename log_clock::duration>(
|
||||
std::chrono::duration_cast<typename log_clock::duration>(
|
||||
std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec)));
|
||||
|
||||
#else
|
||||
return log_clock::now();
|
||||
#endif
|
||||
}
|
||||
SPDLOG_INLINE std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT {
|
||||
#ifdef _WIN32
|
||||
std::tm tm;
|
||||
::localtime_s(&tm, &time_tt);
|
||||
#else
|
||||
std::tm tm;
|
||||
::localtime_r(&time_tt, &tm);
|
||||
#endif
|
||||
return tm;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE std::tm localtime() SPDLOG_NOEXCEPT {
|
||||
std::time_t now_t = ::time(nullptr);
|
||||
return localtime(now_t);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT {
|
||||
#ifdef _WIN32
|
||||
std::tm tm;
|
||||
::gmtime_s(&tm, &time_tt);
|
||||
#else
|
||||
std::tm tm;
|
||||
::gmtime_r(&time_tt, &tm);
|
||||
#endif
|
||||
return tm;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE std::tm gmtime() SPDLOG_NOEXCEPT {
|
||||
std::time_t now_t = ::time(nullptr);
|
||||
return gmtime(now_t);
|
||||
}
|
||||
|
||||
// fopen_s on non windows for writing
|
||||
SPDLOG_INLINE bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode) {
|
||||
#ifdef _WIN32
|
||||
#ifdef SPDLOG_WCHAR_FILENAMES
|
||||
*fp = ::_wfsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
|
||||
#else
|
||||
*fp = ::_fsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
|
||||
#endif
|
||||
#if defined(SPDLOG_PREVENT_CHILD_FD)
|
||||
if (*fp != nullptr) {
|
||||
auto file_handle = reinterpret_cast<HANDLE>(_get_osfhandle(::_fileno(*fp)));
|
||||
if (!::SetHandleInformation(file_handle, HANDLE_FLAG_INHERIT, 0)) {
|
||||
::fclose(*fp);
|
||||
*fp = nullptr;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#else // unix
|
||||
#if defined(SPDLOG_PREVENT_CHILD_FD)
|
||||
const int mode_flag = mode == SPDLOG_FILENAME_T("ab") ? O_APPEND : O_TRUNC;
|
||||
const int fd =
|
||||
::open((filename.c_str()), O_CREAT | O_WRONLY | O_CLOEXEC | mode_flag, mode_t(0644));
|
||||
if (fd == -1) {
|
||||
return true;
|
||||
}
|
||||
*fp = ::fdopen(fd, mode.c_str());
|
||||
if (*fp == nullptr) {
|
||||
::close(fd);
|
||||
}
|
||||
#else
|
||||
*fp = ::fopen((filename.c_str()), mode.c_str());
|
||||
#endif
|
||||
#endif
|
||||
|
||||
return *fp == nullptr;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE int remove(const filename_t &filename) SPDLOG_NOEXCEPT {
|
||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||
return ::_wremove(filename.c_str());
|
||||
#else
|
||||
return std::remove(filename.c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
SPDLOG_INLINE int remove_if_exists(const filename_t &filename) SPDLOG_NOEXCEPT {
|
||||
return path_exists(filename) ? remove(filename) : 0;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT {
|
||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||
return ::_wrename(filename1.c_str(), filename2.c_str());
|
||||
#else
|
||||
return std::rename(filename1.c_str(), filename2.c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
// Return true if path exists (file or directory)
|
||||
SPDLOG_INLINE bool path_exists(const filename_t &filename) SPDLOG_NOEXCEPT {
|
||||
#ifdef _WIN32
|
||||
struct _stat buffer;
|
||||
#ifdef SPDLOG_WCHAR_FILENAMES
|
||||
return (::_wstat(filename.c_str(), &buffer) == 0);
|
||||
#else
|
||||
return (::_stat(filename.c_str(), &buffer) == 0);
|
||||
#endif
|
||||
#else // common linux/unix all have the stat system call
|
||||
struct stat buffer;
|
||||
return (::stat(filename.c_str(), &buffer) == 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef _MSC_VER
|
||||
// avoid warning about unreachable statement at the end of filesize()
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4702)
|
||||
#endif
|
||||
|
||||
// Return file size according to open FILE* object
|
||||
SPDLOG_INLINE size_t filesize(FILE *f) {
|
||||
if (f == nullptr) {
|
||||
throw_spdlog_ex("Failed getting file size. fd is null");
|
||||
}
|
||||
#if defined(_WIN32) && !defined(__CYGWIN__)
|
||||
int fd = ::_fileno(f);
|
||||
#if defined(_WIN64) // 64 bits
|
||||
__int64 ret = ::_filelengthi64(fd);
|
||||
if (ret >= 0) {
|
||||
return static_cast<size_t>(ret);
|
||||
}
|
||||
|
||||
#else // windows 32 bits
|
||||
long ret = ::_filelength(fd);
|
||||
if (ret >= 0) {
|
||||
return static_cast<size_t>(ret);
|
||||
}
|
||||
#endif
|
||||
|
||||
#else // unix
|
||||
// OpenBSD and AIX doesn't compile with :: before the fileno(..)
|
||||
#if defined(__OpenBSD__) || defined(_AIX)
|
||||
int fd = fileno(f);
|
||||
#else
|
||||
int fd = ::fileno(f);
|
||||
#endif
|
||||
// 64 bits(but not in osx, linux/musl or cygwin, where fstat64 is deprecated)
|
||||
#if ((defined(__linux__) && defined(__GLIBC__)) || defined(__sun) || defined(_AIX)) && \
|
||||
(defined(__LP64__) || defined(_LP64))
|
||||
struct stat64 st;
|
||||
if (::fstat64(fd, &st) == 0) {
|
||||
return static_cast<size_t>(st.st_size);
|
||||
}
|
||||
#else // other unix or linux 32 bits or cygwin
|
||||
struct stat st;
|
||||
if (::fstat(fd, &st) == 0) {
|
||||
return static_cast<size_t>(st.st_size);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
throw_spdlog_ex("Failed getting file size from fd", errno);
|
||||
return 0; // will not be reached.
|
||||
}
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
|
||||
// Return utc offset in minutes or throw spdlog_ex on failure
|
||||
SPDLOG_INLINE int utc_minutes_offset(const std::tm &tm) {
|
||||
#ifdef _WIN32
|
||||
#if _WIN32_WINNT < _WIN32_WINNT_WS08
|
||||
TIME_ZONE_INFORMATION tzinfo;
|
||||
auto rv = ::GetTimeZoneInformation(&tzinfo);
|
||||
#else
|
||||
DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
|
||||
auto rv = ::GetDynamicTimeZoneInformation(&tzinfo);
|
||||
#endif
|
||||
if (rv == TIME_ZONE_ID_INVALID) throw_spdlog_ex("Failed getting timezone info. ", errno);
|
||||
|
||||
int offset = -tzinfo.Bias;
|
||||
if (tm.tm_isdst) {
|
||||
offset -= tzinfo.DaylightBias;
|
||||
} else {
|
||||
offset -= tzinfo.StandardBias;
|
||||
}
|
||||
return offset;
|
||||
#else
|
||||
|
||||
#if defined(sun) || defined(__sun) || defined(_AIX) || \
|
||||
(defined(__NEWLIB__) && !defined(__TM_GMTOFF)) || \
|
||||
(!defined(__APPLE__) && !defined(_BSD_SOURCE) && !defined(_GNU_SOURCE) && \
|
||||
(!defined(_POSIX_VERSION) || (_POSIX_VERSION < 202405L)))
|
||||
// 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
|
||||
struct helper {
|
||||
static long int calculate_gmt_offset(const std::tm &localtm = details::os::localtime(),
|
||||
const std::tm &gmtm = details::os::gmtime()) {
|
||||
int local_year = localtm.tm_year + (1900 - 1);
|
||||
int gmt_year = gmtm.tm_year + (1900 - 1);
|
||||
|
||||
long int days = (
|
||||
// difference in day of year
|
||||
localtm.tm_yday -
|
||||
gmtm.tm_yday
|
||||
|
||||
// + intervening leap days
|
||||
+ ((local_year >> 2) - (gmt_year >> 2)) - (local_year / 100 - gmt_year / 100) +
|
||||
((local_year / 100 >> 2) - (gmt_year / 100 >> 2))
|
||||
|
||||
// + difference in years * 365 */
|
||||
+ static_cast<long int>(local_year - gmt_year) * 365);
|
||||
|
||||
long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour);
|
||||
long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min);
|
||||
long int secs = (60 * mins) + (localtm.tm_sec - gmtm.tm_sec);
|
||||
|
||||
return secs;
|
||||
}
|
||||
};
|
||||
|
||||
auto offset_seconds = helper::calculate_gmt_offset(tm);
|
||||
#else
|
||||
auto offset_seconds = tm.tm_gmtoff;
|
||||
#endif
|
||||
|
||||
return static_cast<int>(offset_seconds / 60);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Return current thread id as size_t
|
||||
// It exists because the std::this_thread::get_id() is much slower(especially
|
||||
// under VS 2013)
|
||||
SPDLOG_INLINE size_t _thread_id() SPDLOG_NOEXCEPT {
|
||||
#ifdef _WIN32
|
||||
return static_cast<size_t>(::GetCurrentThreadId());
|
||||
#elif defined(__linux__)
|
||||
#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
|
||||
#define SYS_gettid __NR_gettid
|
||||
#endif
|
||||
return static_cast<size_t>(::syscall(SYS_gettid));
|
||||
#elif defined(_AIX)
|
||||
struct __pthrdsinfo buf;
|
||||
int reg_size = 0;
|
||||
pthread_t pt = pthread_self();
|
||||
int retval = pthread_getthrds_np(&pt, PTHRDSINFO_QUERY_TID, &buf, sizeof(buf), NULL, ®_size);
|
||||
int tid = (!retval) ? buf.__pi_tid : 0;
|
||||
return static_cast<size_t>(tid);
|
||||
#elif defined(__DragonFly__) || defined(__FreeBSD__)
|
||||
return static_cast<size_t>(::pthread_getthreadid_np());
|
||||
#elif defined(__NetBSD__)
|
||||
return static_cast<size_t>(::_lwp_self());
|
||||
#elif defined(__OpenBSD__)
|
||||
return static_cast<size_t>(::getthrid());
|
||||
#elif defined(__sun)
|
||||
return static_cast<size_t>(::thr_self());
|
||||
#elif __APPLE__
|
||||
uint64_t tid;
|
||||
// There is no pthread_threadid_np prior to Mac OS X 10.6, and it is not supported on any PPC,
|
||||
// including 10.6.8 Rosetta. __POWERPC__ is Apple-specific define encompassing ppc and ppc64.
|
||||
#ifdef MAC_OS_X_VERSION_MAX_ALLOWED
|
||||
{
|
||||
#if (MAC_OS_X_VERSION_MAX_ALLOWED < 1060) || defined(__POWERPC__)
|
||||
tid = pthread_mach_thread_np(pthread_self());
|
||||
#elif MAC_OS_X_VERSION_MIN_REQUIRED < 1060
|
||||
if (&pthread_threadid_np) {
|
||||
pthread_threadid_np(nullptr, &tid);
|
||||
} else {
|
||||
tid = pthread_mach_thread_np(pthread_self());
|
||||
}
|
||||
#else
|
||||
pthread_threadid_np(nullptr, &tid);
|
||||
#endif
|
||||
}
|
||||
#else
|
||||
pthread_threadid_np(nullptr, &tid);
|
||||
#endif
|
||||
return static_cast<size_t>(tid);
|
||||
#else // Default to standard C++11 (other Unix)
|
||||
return static_cast<size_t>(std::hash<std::thread::id>()(std::this_thread::get_id()));
|
||||
#endif
|
||||
}
|
||||
|
||||
// Return current thread id as size_t (from thread local storage)
|
||||
SPDLOG_INLINE size_t thread_id() SPDLOG_NOEXCEPT {
|
||||
#if defined(SPDLOG_NO_TLS)
|
||||
return _thread_id();
|
||||
#else // cache thread id in tls
|
||||
static thread_local const size_t tid = _thread_id();
|
||||
return tid;
|
||||
#endif
|
||||
}
|
||||
|
||||
// This is avoid msvc issue in sleep_for that happens if the clock changes.
|
||||
// See https://github.com/gabime/spdlog/issues/609
|
||||
SPDLOG_INLINE void sleep_for_millis(unsigned int milliseconds) SPDLOG_NOEXCEPT {
|
||||
#if defined(_WIN32)
|
||||
::Sleep(milliseconds);
|
||||
#else
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
|
||||
#endif
|
||||
}
|
||||
|
||||
// wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined)
|
||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||
SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) {
|
||||
memory_buf_t buf;
|
||||
wstr_to_utf8buf(filename, buf);
|
||||
return SPDLOG_BUF_TO_STRING(buf);
|
||||
}
|
||||
#else
|
||||
SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) { return filename; }
|
||||
#endif
|
||||
|
||||
SPDLOG_INLINE int pid() SPDLOG_NOEXCEPT {
|
||||
#ifdef _WIN32
|
||||
return conditional_static_cast<int>(::GetCurrentProcessId());
|
||||
#else
|
||||
return conditional_static_cast<int>(::getpid());
|
||||
#endif
|
||||
}
|
||||
|
||||
// Determine if the terminal supports colors
|
||||
// Based on: https://github.com/agauniyal/rang/
|
||||
SPDLOG_INLINE bool is_color_terminal() SPDLOG_NOEXCEPT {
|
||||
#ifdef _WIN32
|
||||
return true;
|
||||
#else
|
||||
|
||||
static const bool result = []() {
|
||||
const char *env_colorterm_p = std::getenv("COLORTERM");
|
||||
if (env_colorterm_p != nullptr) {
|
||||
return true;
|
||||
}
|
||||
|
||||
static constexpr std::array<const char *, 16> terms = {
|
||||
{"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys",
|
||||
"putty", "rxvt", "screen", "vt100", "xterm", "alacritty", "vt102"}};
|
||||
|
||||
const char *env_term_p = std::getenv("TERM");
|
||||
if (env_term_p == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return std::any_of(terms.begin(), terms.end(), [&](const char *term) {
|
||||
return std::strstr(env_term_p, term) != nullptr;
|
||||
});
|
||||
}();
|
||||
|
||||
return result;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Determine if the terminal attached
|
||||
// Source: https://github.com/agauniyal/rang/
|
||||
SPDLOG_INLINE bool in_terminal(FILE *file) SPDLOG_NOEXCEPT {
|
||||
#ifdef _WIN32
|
||||
return ::_isatty(_fileno(file)) != 0;
|
||||
#else
|
||||
return ::isatty(fileno(file)) != 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32)
|
||||
SPDLOG_INLINE void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target) {
|
||||
if (wstr.size() > static_cast<size_t>((std::numeric_limits<int>::max)()) / 4 - 1) {
|
||||
throw_spdlog_ex("UTF-16 string is too big to be converted to UTF-8");
|
||||
}
|
||||
|
||||
int wstr_size = static_cast<int>(wstr.size());
|
||||
if (wstr_size == 0) {
|
||||
target.resize(0);
|
||||
return;
|
||||
}
|
||||
|
||||
int result_size = static_cast<int>(target.capacity());
|
||||
if ((wstr_size + 1) * 4 > result_size) {
|
||||
result_size =
|
||||
::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, NULL, 0, NULL, NULL);
|
||||
}
|
||||
|
||||
if (result_size > 0) {
|
||||
target.resize(result_size);
|
||||
result_size = ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, target.data(),
|
||||
result_size, NULL, NULL);
|
||||
|
||||
if (result_size > 0) {
|
||||
target.resize(result_size);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw_spdlog_ex(
|
||||
fmt_lib::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError()));
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target) {
|
||||
if (str.size() > static_cast<size_t>((std::numeric_limits<int>::max)()) - 1) {
|
||||
throw_spdlog_ex("UTF-8 string is too big to be converted to UTF-16");
|
||||
}
|
||||
|
||||
int str_size = static_cast<int>(str.size());
|
||||
if (str_size == 0) {
|
||||
target.resize(0);
|
||||
return;
|
||||
}
|
||||
|
||||
// find the size to allocate for the result buffer
|
||||
int result_size =
|
||||
::MultiByteToWideChar(CP_UTF8, 0, str.data(), str_size, NULL, 0);
|
||||
|
||||
if (result_size > 0) {
|
||||
target.resize(result_size);
|
||||
result_size = ::MultiByteToWideChar(CP_UTF8, 0, str.data(), str_size, target.data(),
|
||||
result_size);
|
||||
if (result_size > 0) {
|
||||
assert(result_size == target.size());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw_spdlog_ex(
|
||||
fmt_lib::format("MultiByteToWideChar failed. Last error: {}", ::GetLastError()));
|
||||
}
|
||||
#endif // (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) &&
|
||||
// defined(_WIN32)
|
||||
|
||||
// return true on success
|
||||
static SPDLOG_INLINE bool mkdir_(const filename_t &path) {
|
||||
#ifdef _WIN32
|
||||
#ifdef SPDLOG_WCHAR_FILENAMES
|
||||
return ::_wmkdir(path.c_str()) == 0;
|
||||
#else
|
||||
return ::_mkdir(path.c_str()) == 0;
|
||||
#endif
|
||||
#else
|
||||
return ::mkdir(path.c_str(), mode_t(0755)) == 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
// create the given directory - and all directories leading to it
|
||||
// return true on success or if the directory already exists
|
||||
SPDLOG_INLINE bool create_dir(const filename_t &path) {
|
||||
if (path_exists(path)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (path.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
size_t search_offset = 0;
|
||||
do {
|
||||
auto token_pos = path.find_first_of(folder_seps_filename, search_offset);
|
||||
// treat the entire path as a folder if no folder separator not found
|
||||
if (token_pos == filename_t::npos) {
|
||||
token_pos = path.size();
|
||||
}
|
||||
|
||||
auto subdir = path.substr(0, token_pos);
|
||||
#ifdef _WIN32
|
||||
// if subdir is just a drive letter, add a slash e.g. "c:"=>"c:\",
|
||||
// otherwise path_exists(subdir) returns false (issue #3079)
|
||||
const bool is_drive = subdir.length() == 2 && subdir[1] == ':';
|
||||
if (is_drive) {
|
||||
subdir += '\\';
|
||||
token_pos++;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (!subdir.empty() && !path_exists(subdir) && !mkdir_(subdir)) {
|
||||
return false; // return error if failed creating dir
|
||||
}
|
||||
search_offset = token_pos + 1;
|
||||
} while (search_offset < path.size());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Return directory name from given path or empty string
|
||||
// "abc/file" => "abc"
|
||||
// "abc/" => "abc"
|
||||
// "abc" => ""
|
||||
// "abc///" => "abc//"
|
||||
SPDLOG_INLINE filename_t dir_name(const filename_t &path) {
|
||||
auto pos = path.find_last_of(folder_seps_filename);
|
||||
return pos != filename_t::npos ? path.substr(0, pos) : filename_t{};
|
||||
}
|
||||
|
||||
std::string SPDLOG_INLINE getenv(const char *field) {
|
||||
#if defined(_MSC_VER)
|
||||
#if defined(__cplusplus_winrt)
|
||||
return std::string{}; // not supported under uwp
|
||||
#else
|
||||
size_t len = 0;
|
||||
char buf[128];
|
||||
bool ok = ::getenv_s(&len, buf, sizeof(buf), field) == 0;
|
||||
return ok ? buf : std::string{};
|
||||
#endif
|
||||
#else // revert to getenv
|
||||
char *buf = ::getenv(field);
|
||||
return buf ? buf : std::string{};
|
||||
#endif
|
||||
}
|
||||
|
||||
// Do fsync by FILE handlerpointer
|
||||
// Return true on success
|
||||
SPDLOG_INLINE bool fsync(FILE *fp) {
|
||||
#ifdef _WIN32
|
||||
return FlushFileBuffers(reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(fp)))) != 0;
|
||||
#else
|
||||
return ::fsync(fileno(fp)) == 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Do non-locking fwrite if possible by the os or use the regular locking fwrite
|
||||
// Return true on success.
|
||||
SPDLOG_INLINE bool fwrite_bytes(const void *ptr, const size_t n_bytes, FILE *fp) {
|
||||
#if defined(_WIN32) && defined(SPDLOG_FWRITE_UNLOCKED)
|
||||
return _fwrite_nolock(ptr, 1, n_bytes, fp) == n_bytes;
|
||||
#elif defined(SPDLOG_FWRITE_UNLOCKED)
|
||||
return ::fwrite_unlocked(ptr, 1, n_bytes, fp) == n_bytes;
|
||||
#else
|
||||
return std::fwrite(ptr, 1, n_bytes, fp) == n_bytes;
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace os
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,127 +1,360 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#include <ctime> // std::time_t
|
||||
#include <spdlog/common.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
namespace os {
|
||||
#include <cstdio>
|
||||
#include <ctime>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
SPDLOG_API spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT;
|
||||
|
||||
SPDLOG_API std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT;
|
||||
#ifdef _WIN32
|
||||
|
||||
SPDLOG_API std::tm localtime() SPDLOG_NOEXCEPT;
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX //prevent windows redefining min/max
|
||||
#endif
|
||||
|
||||
SPDLOG_API std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT;
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
|
||||
SPDLOG_API std::tm gmtime() SPDLOG_NOEXCEPT;
|
||||
#ifdef __MINGW32__
|
||||
#include <share.h>
|
||||
#endif
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
#elif __linux__
|
||||
|
||||
#include <sys/syscall.h> //Use gettid() syscall under linux to get thread id
|
||||
#include <unistd.h>
|
||||
#include <chrono>
|
||||
|
||||
#elif __FreeBSD__
|
||||
#include <sys/thr.h> //Use thr_self() syscall under FreeBSD to get thread id
|
||||
|
||||
#else
|
||||
#include <thread>
|
||||
|
||||
#endif
|
||||
|
||||
namespace spdlog
|
||||
{
|
||||
namespace details
|
||||
{
|
||||
namespace os
|
||||
{
|
||||
|
||||
inline spdlog::log_clock::time_point now()
|
||||
{
|
||||
|
||||
#if defined __linux__ && defined SPDLOG_CLOCK_COARSE
|
||||
timespec ts;
|
||||
::clock_gettime(CLOCK_REALTIME_COARSE, &ts);
|
||||
return std::chrono::time_point<log_clock, typename log_clock::duration>(
|
||||
std::chrono::duration_cast<typename log_clock::duration>(
|
||||
std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec)));
|
||||
|
||||
|
||||
#else
|
||||
return log_clock::now();
|
||||
#endif
|
||||
|
||||
}
|
||||
inline std::tm localtime(const std::time_t &time_tt)
|
||||
{
|
||||
|
||||
#ifdef _WIN32
|
||||
std::tm tm;
|
||||
localtime_s(&tm, &time_tt);
|
||||
#else
|
||||
std::tm tm;
|
||||
localtime_r(&time_tt, &tm);
|
||||
#endif
|
||||
return tm;
|
||||
}
|
||||
|
||||
inline std::tm localtime()
|
||||
{
|
||||
std::time_t now_t = time(nullptr);
|
||||
return localtime(now_t);
|
||||
}
|
||||
|
||||
|
||||
inline std::tm gmtime(const std::time_t &time_tt)
|
||||
{
|
||||
|
||||
#ifdef _WIN32
|
||||
std::tm tm;
|
||||
gmtime_s(&tm, &time_tt);
|
||||
#else
|
||||
std::tm tm;
|
||||
gmtime_r(&time_tt, &tm);
|
||||
#endif
|
||||
return tm;
|
||||
}
|
||||
|
||||
inline std::tm gmtime()
|
||||
{
|
||||
std::time_t now_t = time(nullptr);
|
||||
return gmtime(now_t);
|
||||
}
|
||||
inline bool operator==(const std::tm& tm1, const std::tm& tm2)
|
||||
{
|
||||
return (tm1.tm_sec == tm2.tm_sec &&
|
||||
tm1.tm_min == tm2.tm_min &&
|
||||
tm1.tm_hour == tm2.tm_hour &&
|
||||
tm1.tm_mday == tm2.tm_mday &&
|
||||
tm1.tm_mon == tm2.tm_mon &&
|
||||
tm1.tm_year == tm2.tm_year &&
|
||||
tm1.tm_isdst == tm2.tm_isdst);
|
||||
}
|
||||
|
||||
inline bool operator!=(const std::tm& tm1, const std::tm& tm2)
|
||||
{
|
||||
return !(tm1 == tm2);
|
||||
}
|
||||
|
||||
// eol definition
|
||||
#if !defined(SPDLOG_EOL)
|
||||
#ifdef _WIN32
|
||||
#define SPDLOG_EOL "\r\n"
|
||||
#else
|
||||
#define SPDLOG_EOL "\n"
|
||||
#endif
|
||||
#if !defined (SPDLOG_EOL)
|
||||
#ifdef _WIN32
|
||||
#define SPDLOG_EOL "\r\n"
|
||||
#else
|
||||
#define SPDLOG_EOL "\n"
|
||||
#endif
|
||||
#endif
|
||||
|
||||
SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL;
|
||||
SPDLOG_CONSTEXPR static const char* eol = SPDLOG_EOL;
|
||||
SPDLOG_CONSTEXPR static int eol_size = sizeof(SPDLOG_EOL) - 1;
|
||||
|
||||
// folder separator
|
||||
#if !defined(SPDLOG_FOLDER_SEPS)
|
||||
#ifdef _WIN32
|
||||
#define SPDLOG_FOLDER_SEPS "\\/"
|
||||
#else
|
||||
#define SPDLOG_FOLDER_SEPS "/"
|
||||
#endif
|
||||
|
||||
|
||||
//fopen_s on non windows for writing
|
||||
inline int fopen_s(FILE** fp, const filename_t& filename, const filename_t& mode)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
#ifdef SPDLOG_WCHAR_FILENAMES
|
||||
*fp = _wfsopen((filename.c_str()), mode.c_str(), _SH_DENYWR);
|
||||
#else
|
||||
*fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYWR);
|
||||
#endif
|
||||
return *fp == nullptr;
|
||||
#else
|
||||
*fp = fopen((filename.c_str()), mode.c_str());
|
||||
return *fp == nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
inline int remove(const filename_t &filename)
|
||||
{
|
||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||
return _wremove(filename.c_str());
|
||||
#else
|
||||
return std::remove(filename.c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
inline int rename(const filename_t& filename1, const filename_t& filename2)
|
||||
{
|
||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||
return _wrename(filename1.c_str(), filename2.c_str());
|
||||
#else
|
||||
return std::rename(filename1.c_str(), filename2.c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
//Return if file exists
|
||||
inline bool file_exists(const filename_t& filename)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
#ifdef SPDLOG_WCHAR_FILENAMES
|
||||
auto attribs = GetFileAttributesW(filename.c_str());
|
||||
#else
|
||||
auto attribs = GetFileAttributesA(filename.c_str());
|
||||
#endif
|
||||
return (attribs != INVALID_FILE_ATTRIBUTES && !(attribs & FILE_ATTRIBUTE_DIRECTORY));
|
||||
#else //common linux/unix all have the stat system call
|
||||
struct stat buffer;
|
||||
return (stat (filename.c_str(), &buffer) == 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//Return file size according to open FILE* object
|
||||
inline size_t filesize(FILE *f)
|
||||
{
|
||||
if (f == nullptr)
|
||||
throw spdlog_ex("Failed getting file size. fd is null");
|
||||
#ifdef _WIN32
|
||||
int fd = _fileno(f);
|
||||
#if _WIN64 //64 bits
|
||||
struct _stat64 st;
|
||||
if (_fstat64(fd, &st) == 0)
|
||||
return st.st_size;
|
||||
|
||||
#else //windows 32 bits
|
||||
struct _stat st;
|
||||
if (_fstat(fd, &st) == 0)
|
||||
return st.st_size;
|
||||
#endif
|
||||
|
||||
SPDLOG_CONSTEXPR static const char folder_seps[] = SPDLOG_FOLDER_SEPS;
|
||||
SPDLOG_CONSTEXPR static const filename_t::value_type folder_seps_filename[] =
|
||||
SPDLOG_FILENAME_T(SPDLOG_FOLDER_SEPS);
|
||||
#else // unix
|
||||
int fd = fileno(f);
|
||||
//64 bits(but not in osx, where fstat64 is deprecated)
|
||||
#if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__))
|
||||
struct stat64 st;
|
||||
if (fstat64(fd, &st) == 0)
|
||||
return st.st_size;
|
||||
#else // unix 32 bits or osx
|
||||
struct stat st;
|
||||
if (fstat(fd, &st) == 0)
|
||||
return st.st_size;
|
||||
#endif
|
||||
#endif
|
||||
throw spdlog_ex("Failed getting file size from fd", errno);
|
||||
}
|
||||
|
||||
// fopen_s on non windows for writing
|
||||
SPDLOG_API bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode);
|
||||
|
||||
// Remove filename. return 0 on success
|
||||
SPDLOG_API int remove(const filename_t &filename) SPDLOG_NOEXCEPT;
|
||||
|
||||
// Remove file if exists. return 0 on success
|
||||
// Note: Non atomic (might return failure to delete if concurrently deleted by other process/thread)
|
||||
SPDLOG_API int remove_if_exists(const filename_t &filename) SPDLOG_NOEXCEPT;
|
||||
|
||||
SPDLOG_API int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT;
|
||||
//Return utc offset in minutes or throw spdlog_ex on failure
|
||||
inline int utc_minutes_offset(const std::tm& tm = details::os::localtime())
|
||||
{
|
||||
|
||||
// Return if file exists.
|
||||
SPDLOG_API bool path_exists(const filename_t &filename) SPDLOG_NOEXCEPT;
|
||||
#ifdef _WIN32
|
||||
#if _WIN32_WINNT < _WIN32_WINNT_WS08
|
||||
TIME_ZONE_INFORMATION tzinfo;
|
||||
auto rv = GetTimeZoneInformation(&tzinfo);
|
||||
#else
|
||||
DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
|
||||
auto rv = GetDynamicTimeZoneInformation(&tzinfo);
|
||||
#endif
|
||||
if (rv == TIME_ZONE_ID_INVALID)
|
||||
throw spdlog::spdlog_ex("Failed getting timezone info. ", errno);
|
||||
|
||||
// Return file size according to open FILE* object
|
||||
SPDLOG_API size_t filesize(FILE *f);
|
||||
int offset = -tzinfo.Bias;
|
||||
if (tm.tm_isdst)
|
||||
offset -= tzinfo.DaylightBias;
|
||||
else
|
||||
offset -= tzinfo.StandardBias;
|
||||
return offset;
|
||||
#else
|
||||
|
||||
// Return utc offset in minutes or throw spdlog_ex on failure
|
||||
SPDLOG_API int utc_minutes_offset(const std::tm &tm = details::os::localtime());
|
||||
#if defined(sun) || defined(__sun)
|
||||
// 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
|
||||
struct helper
|
||||
{
|
||||
static long int calculate_gmt_offset(const std::tm & localtm = details::os::localtime(), const std::tm & gmtm = details::os::gmtime())
|
||||
{
|
||||
int local_year = localtm.tm_year + (1900 - 1);
|
||||
int gmt_year = gmtm.tm_year + (1900 - 1);
|
||||
|
||||
// Return current thread id as size_t
|
||||
// It exists because the std::this_thread::get_id() is much slower(especially
|
||||
// under VS 2013)
|
||||
SPDLOG_API size_t _thread_id() SPDLOG_NOEXCEPT;
|
||||
long int days = (
|
||||
// difference in day of year
|
||||
localtm.tm_yday - gmtm.tm_yday
|
||||
|
||||
// Return current thread id as size_t (from thread local storage)
|
||||
SPDLOG_API size_t thread_id() SPDLOG_NOEXCEPT;
|
||||
// + intervening leap days
|
||||
+ ((local_year >> 2) - (gmt_year >> 2))
|
||||
- (local_year / 100 - gmt_year / 100)
|
||||
+ ((local_year / 100 >> 2) - (gmt_year / 100 >> 2))
|
||||
|
||||
// This is avoid msvc issue in sleep_for that happens if the clock changes.
|
||||
// See https://github.com/gabime/spdlog/issues/609
|
||||
SPDLOG_API void sleep_for_millis(unsigned int milliseconds) SPDLOG_NOEXCEPT;
|
||||
// + difference in years * 365 */
|
||||
+ (long int)(local_year - gmt_year) * 365
|
||||
);
|
||||
|
||||
SPDLOG_API std::string filename_to_str(const filename_t &filename);
|
||||
long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour);
|
||||
long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min);
|
||||
long int secs = (60 * mins) + (localtm.tm_sec - gmtm.tm_sec);
|
||||
|
||||
SPDLOG_API int pid() SPDLOG_NOEXCEPT;
|
||||
return secs;
|
||||
}
|
||||
};
|
||||
|
||||
// Determine if the terminal supports colors
|
||||
// Source: https://github.com/agauniyal/rang/
|
||||
SPDLOG_API bool is_color_terminal() SPDLOG_NOEXCEPT;
|
||||
|
||||
// Determine if the terminal attached
|
||||
// Source: https://github.com/agauniyal/rang/
|
||||
SPDLOG_API bool in_terminal(FILE *file) SPDLOG_NOEXCEPT;
|
||||
|
||||
#if (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32)
|
||||
SPDLOG_API void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target);
|
||||
|
||||
SPDLOG_API void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target);
|
||||
long int offset_seconds = helper::calculate_gmt_offset(tm);
|
||||
#else
|
||||
long int offset_seconds = tm.tm_gmtoff;
|
||||
#endif
|
||||
|
||||
// Return directory name from given path or empty string
|
||||
// "abc/file" => "abc"
|
||||
// "abc/" => "abc"
|
||||
// "abc" => ""
|
||||
// "abc///" => "abc//"
|
||||
SPDLOG_API filename_t dir_name(const filename_t &path);
|
||||
|
||||
// Create a dir from the given path.
|
||||
// Return true if succeeded or if this dir already exists.
|
||||
SPDLOG_API bool create_dir(const filename_t &path);
|
||||
|
||||
// non thread safe, cross platform getenv/getenv_s
|
||||
// return empty string if field not found
|
||||
SPDLOG_API std::string getenv(const char *field);
|
||||
|
||||
// Do fsync by FILE objectpointer.
|
||||
// Return true on success.
|
||||
SPDLOG_API bool fsync(FILE *fp);
|
||||
|
||||
// Do non-locking fwrite if possible by the os or use the regular locking fwrite
|
||||
// Return true on success.
|
||||
SPDLOG_API bool fwrite_bytes(const void *ptr, const size_t n_bytes, FILE *fp);
|
||||
|
||||
} // namespace os
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "os-inl.h"
|
||||
return static_cast<int>(offset_seconds / 60);
|
||||
#endif
|
||||
}
|
||||
|
||||
//Return current thread id as size_t
|
||||
//It exists because the std::this_thread::get_id() is much slower(espcially under VS 2013)
|
||||
inline size_t thread_id()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return static_cast<size_t>(::GetCurrentThreadId());
|
||||
#elif __linux__
|
||||
# if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
|
||||
# define SYS_gettid __NR_gettid
|
||||
# endif
|
||||
return static_cast<size_t>(syscall(SYS_gettid));
|
||||
#elif __FreeBSD__
|
||||
long tid;
|
||||
thr_self(&tid);
|
||||
return static_cast<size_t>(tid);
|
||||
#else //Default to standard C++11 (OSX and other Unix)
|
||||
return static_cast<size_t>(std::hash<std::thread::id>()(std::this_thread::get_id()));
|
||||
#endif
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
// wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined)
|
||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||
#define SPDLOG_FILENAME_T(s) L ## s
|
||||
inline std::string filename_to_str(const filename_t& filename)
|
||||
{
|
||||
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> c;
|
||||
return c.to_bytes(filename);
|
||||
}
|
||||
#else
|
||||
#define SPDLOG_FILENAME_T(s) s
|
||||
inline std::string filename_to_str(const filename_t& filename)
|
||||
{
|
||||
return filename;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// Return errno string (thread safe)
|
||||
inline std::string errno_str(int err_num)
|
||||
{
|
||||
char buf[256];
|
||||
SPDLOG_CONSTEXPR auto buf_size = sizeof(buf);
|
||||
|
||||
#ifdef _WIN32
|
||||
if(strerror_s(buf, buf_size, err_num) == 0)
|
||||
return std::string(buf);
|
||||
else
|
||||
return "Unkown error";
|
||||
|
||||
#elif defined(__FreeBSD__) || defined(__APPLE__) || defined(ANDROID) || \
|
||||
((_POSIX_C_SOURCE >= 200112L) && ! _GNU_SOURCE) // posix version
|
||||
|
||||
if (strerror_r(err_num, buf, buf_size) == 0)
|
||||
return std::string(buf);
|
||||
else
|
||||
return "Unkown error";
|
||||
|
||||
#else // gnu version (might not use the given buf, so its retval pointer must be used)
|
||||
return std::string(strerror_r(err_num, buf, buf_size));
|
||||
#endif
|
||||
}
|
||||
|
||||
} //os
|
||||
} //details
|
||||
} //spdlog
|
||||
|
636
include/spdlog/details/pattern_formatter_impl.h
Normal file
636
include/spdlog/details/pattern_formatter_impl.h
Normal file
@ -0,0 +1,636 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/formatter.h>
|
||||
#include <spdlog/details/log_msg.h>
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/fmt/fmt.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace spdlog
|
||||
{
|
||||
namespace details
|
||||
{
|
||||
class flag_formatter
|
||||
{
|
||||
public:
|
||||
virtual ~flag_formatter()
|
||||
{}
|
||||
virtual void format(details::log_msg& msg, const std::tm& tm_time) = 0;
|
||||
};
|
||||
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// name & level pattern appenders
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
namespace
|
||||
{
|
||||
class name_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm&) override
|
||||
{
|
||||
msg.formatted << *msg.logger_name;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// log level appender
|
||||
class level_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm&) override
|
||||
{
|
||||
msg.formatted << level::to_str(msg.level);
|
||||
}
|
||||
};
|
||||
|
||||
// short log level appender
|
||||
class short_level_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm&) override
|
||||
{
|
||||
msg.formatted << level::to_short_str(msg.level);
|
||||
}
|
||||
};
|
||||
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// Date time pattern appenders
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
|
||||
static const char* ampm(const tm& t)
|
||||
{
|
||||
return t.tm_hour >= 12 ? "PM" : "AM";
|
||||
}
|
||||
|
||||
static int to12h(const tm& t)
|
||||
{
|
||||
return t.tm_hour > 12 ? t.tm_hour - 12 : t.tm_hour;
|
||||
}
|
||||
|
||||
//Abbreviated weekday name
|
||||
static const std::string days[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
|
||||
class a_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << days[tm_time.tm_wday];
|
||||
}
|
||||
};
|
||||
|
||||
//Full weekday name
|
||||
static const std::string full_days[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
|
||||
class A_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << full_days[tm_time.tm_wday];
|
||||
}
|
||||
};
|
||||
|
||||
//Abbreviated month
|
||||
static const std::string months[] { "Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec" };
|
||||
class b_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << months[tm_time.tm_mon];
|
||||
}
|
||||
};
|
||||
|
||||
//Full month name
|
||||
static const std::string full_months[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
|
||||
class B_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << full_months[tm_time.tm_mon];
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
//write 2 ints seperated by sep with padding of 2
|
||||
static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, char sep)
|
||||
{
|
||||
w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0');
|
||||
return w;
|
||||
}
|
||||
|
||||
//write 3 ints seperated by sep with padding of 2
|
||||
static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, int v3, char sep)
|
||||
{
|
||||
w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0') << sep << fmt::pad(v3, 2, '0');
|
||||
return w;
|
||||
}
|
||||
|
||||
|
||||
//Date and time representation (Thu Aug 23 15:35:46 2014)
|
||||
class c_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << days[tm_time.tm_wday] << ' ' << months[tm_time.tm_mon] << ' ' << tm_time.tm_mday << ' ';
|
||||
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << tm_time.tm_year + 1900;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// year - 2 digit
|
||||
class C_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << fmt::pad(tm_time.tm_year % 100, 2, '0');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
// Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01
|
||||
class D_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
pad_n_join(msg.formatted, tm_time.tm_mon + 1, tm_time.tm_mday, tm_time.tm_year % 100, '/');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// year - 4 digit
|
||||
class Y_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << tm_time.tm_year + 1900;
|
||||
}
|
||||
};
|
||||
|
||||
// month 1-12
|
||||
class m_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << fmt::pad(tm_time.tm_mon + 1, 2, '0');
|
||||
}
|
||||
};
|
||||
|
||||
// day of month 1-31
|
||||
class d_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << fmt::pad(tm_time.tm_mday, 2, '0');
|
||||
}
|
||||
};
|
||||
|
||||
// hours in 24 format 0-23
|
||||
class H_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << fmt::pad(tm_time.tm_hour, 2, '0');
|
||||
}
|
||||
};
|
||||
|
||||
// hours in 12 format 1-12
|
||||
class I_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << fmt::pad(to12h(tm_time), 2, '0');
|
||||
}
|
||||
};
|
||||
|
||||
// minutes 0-59
|
||||
class M_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << fmt::pad(tm_time.tm_min, 2, '0');
|
||||
}
|
||||
};
|
||||
|
||||
// seconds 0-59
|
||||
class S_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << fmt::pad(tm_time.tm_sec, 2, '0');
|
||||
}
|
||||
};
|
||||
|
||||
// milliseconds
|
||||
class e_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm&) override
|
||||
{
|
||||
auto duration = msg.time.time_since_epoch();
|
||||
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() % 1000;
|
||||
msg.formatted << fmt::pad(static_cast<int>(millis), 3, '0');
|
||||
}
|
||||
};
|
||||
|
||||
// microseconds
|
||||
class f_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm&) override
|
||||
{
|
||||
auto duration = msg.time.time_since_epoch();
|
||||
auto micros = std::chrono::duration_cast<std::chrono::microseconds>(duration).count() % 1000000;
|
||||
msg.formatted << fmt::pad(static_cast<int>(micros), 6, '0');
|
||||
}
|
||||
};
|
||||
|
||||
// nanoseconds
|
||||
class F_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm&) override
|
||||
{
|
||||
auto duration = msg.time.time_since_epoch();
|
||||
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count() % 1000000000;
|
||||
msg.formatted << fmt::pad(static_cast<int>(ns), 9, '0');
|
||||
}
|
||||
};
|
||||
|
||||
// AM/PM
|
||||
class p_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
msg.formatted << ampm(tm_time);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// 12 hour clock 02:55:02 pm
|
||||
class r_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
pad_n_join(msg.formatted, to12h(tm_time), tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << ampm(tm_time);
|
||||
}
|
||||
};
|
||||
|
||||
// 24-hour HH:MM time, equivalent to %H:%M
|
||||
class R_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, ':');
|
||||
}
|
||||
};
|
||||
|
||||
// ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S
|
||||
class T_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// ISO 8601 offset from UTC in timezone (+-HH:MM)
|
||||
class z_formatter:public flag_formatter
|
||||
{
|
||||
public:
|
||||
const std::chrono::seconds cache_refresh = std::chrono::seconds(5);
|
||||
|
||||
z_formatter():_last_update(std::chrono::seconds(0))
|
||||
{}
|
||||
z_formatter(const z_formatter&) = delete;
|
||||
z_formatter& operator=(const z_formatter&) = delete;
|
||||
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
#ifdef _WIN32
|
||||
int total_minutes = get_cached_offset(msg, tm_time);
|
||||
#else
|
||||
// No need to chache under gcc,
|
||||
// it is very fast (already stored in tm.tm_gmtoff)
|
||||
int total_minutes = os::utc_minutes_offset(tm_time);
|
||||
#endif
|
||||
bool is_negative = total_minutes < 0;
|
||||
char sign;
|
||||
if (is_negative)
|
||||
{
|
||||
total_minutes = -total_minutes;
|
||||
sign = '-';
|
||||
}
|
||||
else
|
||||
{
|
||||
sign = '+';
|
||||
}
|
||||
|
||||
int h = total_minutes / 60;
|
||||
int m = total_minutes % 60;
|
||||
msg.formatted << sign;
|
||||
pad_n_join(msg.formatted, h, m, ':');
|
||||
}
|
||||
private:
|
||||
log_clock::time_point _last_update;
|
||||
int _offset_minutes;
|
||||
std::mutex _mutex;
|
||||
|
||||
int get_cached_offset(const log_msg& msg, const std::tm& tm_time)
|
||||
{
|
||||
using namespace std::chrono;
|
||||
std::lock_guard<std::mutex> l(_mutex);
|
||||
if (msg.time - _last_update >= cache_refresh)
|
||||
{
|
||||
_offset_minutes = os::utc_minutes_offset(tm_time);
|
||||
_last_update = msg.time;
|
||||
}
|
||||
return _offset_minutes;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
//Thread id
|
||||
class t_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm&) override
|
||||
{
|
||||
msg.formatted << msg.thread_id;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
class v_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm&) override
|
||||
{
|
||||
msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size());
|
||||
}
|
||||
};
|
||||
|
||||
class ch_formatter:public flag_formatter
|
||||
{
|
||||
public:
|
||||
explicit ch_formatter(char ch): _ch(ch)
|
||||
{}
|
||||
void format(details::log_msg& msg, const std::tm&) override
|
||||
{
|
||||
msg.formatted << _ch;
|
||||
}
|
||||
private:
|
||||
char _ch;
|
||||
};
|
||||
|
||||
|
||||
//aggregate user chars to display as is
|
||||
class aggregate_formatter:public flag_formatter
|
||||
{
|
||||
public:
|
||||
aggregate_formatter()
|
||||
{}
|
||||
void add_ch(char ch)
|
||||
{
|
||||
_str += ch;
|
||||
}
|
||||
void format(details::log_msg& msg, const std::tm&) override
|
||||
{
|
||||
msg.formatted << _str;
|
||||
}
|
||||
private:
|
||||
std::string _str;
|
||||
};
|
||||
|
||||
// Full info formatter
|
||||
// pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v
|
||||
class full_formatter:public flag_formatter
|
||||
{
|
||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||
{
|
||||
#ifndef SPDLOG_NO_DATETIME
|
||||
auto duration = msg.time.time_since_epoch();
|
||||
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() % 1000;
|
||||
|
||||
/* Slower version(while still very fast - about 3.2 million lines/sec under 10 threads),
|
||||
msg.formatted.write("[{:d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}.{:03d}] [{}] [{}] {} ",
|
||||
tm_time.tm_year + 1900,
|
||||
tm_time.tm_mon + 1,
|
||||
tm_time.tm_mday,
|
||||
tm_time.tm_hour,
|
||||
tm_time.tm_min,
|
||||
tm_time.tm_sec,
|
||||
static_cast<int>(millis),
|
||||
msg.logger_name,
|
||||
level::to_str(msg.level),
|
||||
msg.raw.str());*/
|
||||
|
||||
|
||||
// Faster (albeit uglier) way to format the line (5.6 million lines/sec under 10 threads)
|
||||
msg.formatted << '[' << static_cast<unsigned int>(tm_time.tm_year + 1900) << '-'
|
||||
<< fmt::pad(static_cast<unsigned int>(tm_time.tm_mon + 1), 2, '0') << '-'
|
||||
<< fmt::pad(static_cast<unsigned int>(tm_time.tm_mday), 2, '0') << ' '
|
||||
<< fmt::pad(static_cast<unsigned int>(tm_time.tm_hour), 2, '0') << ':'
|
||||
<< fmt::pad(static_cast<unsigned int>(tm_time.tm_min), 2, '0') << ':'
|
||||
<< fmt::pad(static_cast<unsigned int>(tm_time.tm_sec), 2, '0') << '.'
|
||||
<< fmt::pad(static_cast<unsigned int>(millis), 3, '0') << "] ";
|
||||
|
||||
//no datetime needed
|
||||
#else
|
||||
(void)tm_time;
|
||||
#endif
|
||||
|
||||
#ifndef SPDLOG_NO_NAME
|
||||
msg.formatted << '[' << *msg.logger_name << "] ";
|
||||
#endif
|
||||
|
||||
msg.formatted << '[' << level::to_str(msg.level) << "] ";
|
||||
msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size());
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// pattern_formatter inline impl
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
inline spdlog::pattern_formatter::pattern_formatter(const std::string& pattern)
|
||||
{
|
||||
compile_pattern(pattern);
|
||||
}
|
||||
|
||||
inline void spdlog::pattern_formatter::compile_pattern(const std::string& pattern)
|
||||
{
|
||||
auto end = pattern.end();
|
||||
std::unique_ptr<details::aggregate_formatter> user_chars;
|
||||
for (auto it = pattern.begin(); it != end; ++it)
|
||||
{
|
||||
if (*it == '%')
|
||||
{
|
||||
if (user_chars) //append user chars found so far
|
||||
_formatters.push_back(std::move(user_chars));
|
||||
|
||||
if (++it != end)
|
||||
handle_flag(*it);
|
||||
else
|
||||
break;
|
||||
}
|
||||
else // chars not following the % sign should be displayed as is
|
||||
{
|
||||
if (!user_chars)
|
||||
user_chars = std::unique_ptr<details::aggregate_formatter>(new details::aggregate_formatter());
|
||||
user_chars->add_ch(*it);
|
||||
}
|
||||
}
|
||||
if (user_chars) //append raw chars found so far
|
||||
{
|
||||
_formatters.push_back(std::move(user_chars));
|
||||
}
|
||||
|
||||
}
|
||||
inline void spdlog::pattern_formatter::handle_flag(char flag)
|
||||
{
|
||||
switch (flag)
|
||||
{
|
||||
// logger name
|
||||
case 'n':
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::name_formatter()));
|
||||
break;
|
||||
|
||||
case 'l':
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::level_formatter()));
|
||||
break;
|
||||
|
||||
case 'L':
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::short_level_formatter()));
|
||||
break;
|
||||
|
||||
case('t'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::t_formatter()));
|
||||
break;
|
||||
|
||||
case('v'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::v_formatter()));
|
||||
break;
|
||||
|
||||
case('a'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::a_formatter()));
|
||||
break;
|
||||
|
||||
case('A'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::A_formatter()));
|
||||
break;
|
||||
|
||||
case('b'):
|
||||
case('h'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::b_formatter()));
|
||||
break;
|
||||
|
||||
case('B'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::B_formatter()));
|
||||
break;
|
||||
case('c'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::c_formatter()));
|
||||
break;
|
||||
|
||||
case('C'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::C_formatter()));
|
||||
break;
|
||||
|
||||
case('Y'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::Y_formatter()));
|
||||
break;
|
||||
|
||||
case('D'):
|
||||
case('x'):
|
||||
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::D_formatter()));
|
||||
break;
|
||||
|
||||
case('m'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::m_formatter()));
|
||||
break;
|
||||
|
||||
case('d'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::d_formatter()));
|
||||
break;
|
||||
|
||||
case('H'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::H_formatter()));
|
||||
break;
|
||||
|
||||
case('I'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::I_formatter()));
|
||||
break;
|
||||
|
||||
case('M'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::M_formatter()));
|
||||
break;
|
||||
|
||||
case('S'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::S_formatter()));
|
||||
break;
|
||||
|
||||
case('e'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::e_formatter()));
|
||||
break;
|
||||
|
||||
case('f'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::f_formatter()));
|
||||
break;
|
||||
case('F'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::F_formatter()));
|
||||
break;
|
||||
|
||||
case('p'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::p_formatter()));
|
||||
break;
|
||||
|
||||
case('r'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::r_formatter()));
|
||||
break;
|
||||
|
||||
case('R'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::R_formatter()));
|
||||
break;
|
||||
|
||||
case('T'):
|
||||
case('X'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::T_formatter()));
|
||||
break;
|
||||
|
||||
case('z'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::z_formatter()));
|
||||
break;
|
||||
|
||||
case ('+'):
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::full_formatter()));
|
||||
break;
|
||||
|
||||
default: //Unkown flag appears as is
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::ch_formatter('%')));
|
||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::ch_formatter(flag)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
inline void spdlog::pattern_formatter::format(details::log_msg& msg)
|
||||
{
|
||||
|
||||
#ifndef SPDLOG_NO_DATETIME
|
||||
auto tm_time = details::os::localtime(log_clock::to_time_t(msg.time));
|
||||
#else
|
||||
std::tm tm_time;
|
||||
#endif
|
||||
for (auto &f : _formatters)
|
||||
{
|
||||
f->format(msg, tm_time);
|
||||
}
|
||||
//write eol
|
||||
msg.formatted.write(details::os::eol, details::os::eol_size);
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/details/periodic_worker.h>
|
||||
#endif
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
// stop the worker thread and join it
|
||||
SPDLOG_INLINE periodic_worker::~periodic_worker() {
|
||||
if (worker_thread_.joinable()) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
active_ = false;
|
||||
}
|
||||
cv_.notify_one();
|
||||
worker_thread_.join();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,58 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
// periodic worker thread - periodically executes the given callback function.
|
||||
//
|
||||
// RAII over the owned thread:
|
||||
// creates the thread on construction.
|
||||
// stops and joins the thread on destruction (if the thread is executing a callback, wait for it
|
||||
// to finish first).
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
class SPDLOG_API periodic_worker {
|
||||
public:
|
||||
template <typename Rep, typename Period>
|
||||
periodic_worker(const std::function<void()> &callback_fun,
|
||||
std::chrono::duration<Rep, Period> interval) {
|
||||
active_ = (interval > std::chrono::duration<Rep, Period>::zero());
|
||||
if (!active_) {
|
||||
return;
|
||||
}
|
||||
|
||||
worker_thread_ = std::thread([this, callback_fun, interval]() {
|
||||
for (;;) {
|
||||
std::unique_lock<std::mutex> lock(this->mutex_);
|
||||
if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; })) {
|
||||
return; // active_ == false, so exit this thread
|
||||
}
|
||||
callback_fun();
|
||||
}
|
||||
});
|
||||
}
|
||||
std::thread &get_thread() { return worker_thread_; }
|
||||
periodic_worker(const periodic_worker &) = delete;
|
||||
periodic_worker &operator=(const periodic_worker &) = delete;
|
||||
// stop the worker thread and join it
|
||||
~periodic_worker();
|
||||
|
||||
private:
|
||||
bool active_;
|
||||
std::thread worker_thread_;
|
||||
std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "periodic_worker-inl.h"
|
||||
#endif
|
@ -1,261 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/details/registry.h>
|
||||
#endif
|
||||
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/periodic_worker.h>
|
||||
#include <spdlog/logger.h>
|
||||
#include <spdlog/pattern_formatter.h>
|
||||
|
||||
#ifndef SPDLOG_DISABLE_DEFAULT_LOGGER
|
||||
// support for the default stdout color logger
|
||||
#ifdef _WIN32
|
||||
#include <spdlog/sinks/wincolor_sink.h>
|
||||
#else
|
||||
#include <spdlog/sinks/ansicolor_sink.h>
|
||||
#endif
|
||||
#endif // SPDLOG_DISABLE_DEFAULT_LOGGER
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
SPDLOG_INLINE registry::registry()
|
||||
: formatter_(new pattern_formatter()) {
|
||||
#ifndef SPDLOG_DISABLE_DEFAULT_LOGGER
|
||||
// create default logger (ansicolor_stdout_sink_mt or wincolor_stdout_sink_mt in windows).
|
||||
#ifdef _WIN32
|
||||
auto color_sink = std::make_shared<sinks::wincolor_stdout_sink_mt>();
|
||||
#else
|
||||
auto color_sink = std::make_shared<sinks::ansicolor_stdout_sink_mt>();
|
||||
#endif
|
||||
|
||||
const char *default_logger_name = "";
|
||||
default_logger_ = std::make_shared<spdlog::logger>(default_logger_name, std::move(color_sink));
|
||||
loggers_[default_logger_name] = default_logger_;
|
||||
|
||||
#endif // SPDLOG_DISABLE_DEFAULT_LOGGER
|
||||
}
|
||||
|
||||
SPDLOG_INLINE registry::~registry() = default;
|
||||
|
||||
SPDLOG_INLINE void registry::register_logger(std::shared_ptr<logger> new_logger) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
register_logger_(std::move(new_logger));
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::initialize_logger(std::shared_ptr<logger> new_logger) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
new_logger->set_formatter(formatter_->clone());
|
||||
|
||||
if (err_handler_) {
|
||||
new_logger->set_error_handler(err_handler_);
|
||||
}
|
||||
|
||||
// set new level according to previously configured level or default level
|
||||
auto it = log_levels_.find(new_logger->name());
|
||||
auto new_level = it != log_levels_.end() ? it->second : global_log_level_;
|
||||
new_logger->set_level(new_level);
|
||||
|
||||
new_logger->flush_on(flush_level_);
|
||||
|
||||
if (backtrace_n_messages_ > 0) {
|
||||
new_logger->enable_backtrace(backtrace_n_messages_);
|
||||
}
|
||||
|
||||
if (automatic_registration_) {
|
||||
register_logger_(std::move(new_logger));
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE std::shared_ptr<logger> registry::get(const std::string &logger_name) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
auto found = loggers_.find(logger_name);
|
||||
return found == loggers_.end() ? nullptr : found->second;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE std::shared_ptr<logger> registry::default_logger() {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
return default_logger_;
|
||||
}
|
||||
|
||||
// Return raw ptr to the default logger.
|
||||
// To be used directly by the spdlog default api (e.g. spdlog::info)
|
||||
// This make the default API faster, but cannot be used concurrently with set_default_logger().
|
||||
// e.g do not call set_default_logger() from one thread while calling spdlog::info() from another.
|
||||
SPDLOG_INLINE logger *registry::get_default_raw() { return default_logger_.get(); }
|
||||
|
||||
// set default logger.
|
||||
// default logger is stored in default_logger_ (for faster retrieval) and in the loggers_ map.
|
||||
SPDLOG_INLINE void registry::set_default_logger(std::shared_ptr<logger> new_default_logger) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
if (new_default_logger != nullptr) {
|
||||
loggers_[new_default_logger->name()] = new_default_logger;
|
||||
}
|
||||
default_logger_ = std::move(new_default_logger);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::set_tp(std::shared_ptr<thread_pool> tp) {
|
||||
std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
|
||||
tp_ = std::move(tp);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE std::shared_ptr<thread_pool> registry::get_tp() {
|
||||
std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
|
||||
return tp_;
|
||||
}
|
||||
|
||||
// Set global formatter. Each sink in each logger will get a clone of this object
|
||||
SPDLOG_INLINE void registry::set_formatter(std::unique_ptr<formatter> formatter) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
formatter_ = std::move(formatter);
|
||||
for (auto &l : loggers_) {
|
||||
l.second->set_formatter(formatter_->clone());
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::enable_backtrace(size_t n_messages) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
backtrace_n_messages_ = n_messages;
|
||||
|
||||
for (auto &l : loggers_) {
|
||||
l.second->enable_backtrace(n_messages);
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::disable_backtrace() {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
backtrace_n_messages_ = 0;
|
||||
for (auto &l : loggers_) {
|
||||
l.second->disable_backtrace();
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::set_level(level::level_enum log_level) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
for (auto &l : loggers_) {
|
||||
l.second->set_level(log_level);
|
||||
}
|
||||
global_log_level_ = log_level;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::flush_on(level::level_enum log_level) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
for (auto &l : loggers_) {
|
||||
l.second->flush_on(log_level);
|
||||
}
|
||||
flush_level_ = log_level;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::set_error_handler(err_handler handler) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
for (auto &l : loggers_) {
|
||||
l.second->set_error_handler(handler);
|
||||
}
|
||||
err_handler_ = std::move(handler);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::apply_all(
|
||||
const std::function<void(const std::shared_ptr<logger>)> &fun) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
for (auto &l : loggers_) {
|
||||
fun(l.second);
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::flush_all() {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
for (auto &l : loggers_) {
|
||||
l.second->flush();
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::drop(const std::string &logger_name) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
auto is_default_logger = default_logger_ && default_logger_->name() == logger_name;
|
||||
loggers_.erase(logger_name);
|
||||
if (is_default_logger) {
|
||||
default_logger_.reset();
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::drop_all() {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
loggers_.clear();
|
||||
default_logger_.reset();
|
||||
}
|
||||
|
||||
// clean all resources and threads started by the registry
|
||||
SPDLOG_INLINE void registry::shutdown() {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(flusher_mutex_);
|
||||
periodic_flusher_.reset();
|
||||
}
|
||||
|
||||
drop_all();
|
||||
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
|
||||
tp_.reset();
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE std::recursive_mutex ®istry::tp_mutex() { return tp_mutex_; }
|
||||
|
||||
SPDLOG_INLINE void registry::set_automatic_registration(bool automatic_registration) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
automatic_registration_ = automatic_registration;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::set_levels(log_levels levels, level::level_enum *global_level) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
log_levels_ = std::move(levels);
|
||||
auto global_level_requested = global_level != nullptr;
|
||||
global_log_level_ = global_level_requested ? *global_level : global_log_level_;
|
||||
|
||||
for (auto &logger : loggers_) {
|
||||
auto logger_entry = log_levels_.find(logger.first);
|
||||
if (logger_entry != log_levels_.end()) {
|
||||
logger.second->set_level(logger_entry->second);
|
||||
} else if (global_level_requested) {
|
||||
logger.second->set_level(*global_level);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE registry ®istry::instance() {
|
||||
static registry s_instance;
|
||||
return s_instance;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::apply_logger_env_levels(std::shared_ptr<logger> new_logger) {
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
auto it = log_levels_.find(new_logger->name());
|
||||
auto new_level = it != log_levels_.end() ? it->second : global_log_level_;
|
||||
new_logger->set_level(new_level);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::throw_if_exists_(const std::string &logger_name) {
|
||||
if (loggers_.find(logger_name) != loggers_.end()) {
|
||||
throw_spdlog_ex("logger with name '" + logger_name + "' already exists");
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::register_logger_(std::shared_ptr<logger> new_logger) {
|
||||
auto logger_name = new_logger->name();
|
||||
throw_if_exists_(logger_name);
|
||||
loggers_[logger_name] = std::move(new_logger);
|
||||
}
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,15 +1,19 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
// Loggers registry of unique name->logger pointer
|
||||
// An attempt to create a logger with an already existing name will result with spdlog_ex exception.
|
||||
// Loggers registy of unique name->logger pointer
|
||||
// An attempt to create a logger with an already existing name will be ignored
|
||||
// If user requests a non existing logger, nullptr will be returned
|
||||
// This class is thread safe
|
||||
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/logger.h>
|
||||
#include <spdlog/async_logger.h>
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/periodic_worker.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
@ -18,112 +22,164 @@
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace spdlog {
|
||||
class logger;
|
||||
|
||||
namespace details {
|
||||
class thread_pool;
|
||||
|
||||
class SPDLOG_API registry {
|
||||
namespace spdlog
|
||||
{
|
||||
namespace details
|
||||
{
|
||||
template <class Mutex> class registry_t
|
||||
{
|
||||
public:
|
||||
using log_levels = std::unordered_map<std::string, level::level_enum>;
|
||||
registry(const registry &) = delete;
|
||||
registry &operator=(const registry &) = delete;
|
||||
|
||||
void register_logger(std::shared_ptr<logger> new_logger);
|
||||
void initialize_logger(std::shared_ptr<logger> new_logger);
|
||||
std::shared_ptr<logger> get(const std::string &logger_name);
|
||||
std::shared_ptr<logger> default_logger();
|
||||
|
||||
// Return raw ptr to the default logger.
|
||||
// To be used directly by the spdlog default api (e.g. spdlog::info)
|
||||
// This make the default API faster, but cannot be used concurrently with set_default_logger().
|
||||
// e.g do not call set_default_logger() from one thread while calling spdlog::info() from
|
||||
// another.
|
||||
logger *get_default_raw();
|
||||
|
||||
// set default logger and add it to the registry if not registered already.
|
||||
// default logger is stored in default_logger_ (for faster retrieval) and in the loggers_ map.
|
||||
// Note: Make sure to unregister it when no longer needed or before calling again with a new
|
||||
// logger.
|
||||
void set_default_logger(std::shared_ptr<logger> new_default_logger);
|
||||
|
||||
void set_tp(std::shared_ptr<thread_pool> tp);
|
||||
|
||||
std::shared_ptr<thread_pool> get_tp();
|
||||
|
||||
// Set global formatter. Each sink in each logger will get a clone of this object
|
||||
void set_formatter(std::unique_ptr<formatter> formatter);
|
||||
|
||||
void enable_backtrace(size_t n_messages);
|
||||
|
||||
void disable_backtrace();
|
||||
|
||||
void set_level(level::level_enum log_level);
|
||||
|
||||
void flush_on(level::level_enum log_level);
|
||||
|
||||
template <typename Rep, typename Period>
|
||||
void flush_every(std::chrono::duration<Rep, Period> interval) {
|
||||
std::lock_guard<std::mutex> lock(flusher_mutex_);
|
||||
auto clbk = [this]() { this->flush_all(); };
|
||||
periodic_flusher_ = details::make_unique<periodic_worker>(clbk, interval);
|
||||
void register_logger(std::shared_ptr<logger> logger)
|
||||
{
|
||||
std::lock_guard<Mutex> lock(_mutex);
|
||||
auto logger_name = logger->name();
|
||||
throw_if_exists(logger_name);
|
||||
_loggers[logger_name] = logger;
|
||||
}
|
||||
|
||||
std::unique_ptr<periodic_worker> &get_flusher() {
|
||||
std::lock_guard<std::mutex> lock(flusher_mutex_);
|
||||
return periodic_flusher_;
|
||||
|
||||
std::shared_ptr<logger> get(const std::string& logger_name)
|
||||
{
|
||||
std::lock_guard<Mutex> lock(_mutex);
|
||||
auto found = _loggers.find(logger_name);
|
||||
return found == _loggers.end() ? nullptr : found->second;
|
||||
}
|
||||
|
||||
void set_error_handler(err_handler handler);
|
||||
template<class It>
|
||||
std::shared_ptr<logger> create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end)
|
||||
{
|
||||
std::lock_guard<Mutex> lock(_mutex);
|
||||
throw_if_exists(logger_name);
|
||||
std::shared_ptr<logger> new_logger;
|
||||
if (_async_mode)
|
||||
new_logger = std::make_shared<async_logger>(logger_name, sinks_begin, sinks_end, _async_q_size, _overflow_policy, _worker_warmup_cb, _flush_interval_ms, _worker_teardown_cb);
|
||||
else
|
||||
new_logger = std::make_shared<logger>(logger_name, sinks_begin, sinks_end);
|
||||
|
||||
void apply_all(const std::function<void(const std::shared_ptr<logger>)> &fun);
|
||||
if (_formatter)
|
||||
new_logger->set_formatter(_formatter);
|
||||
|
||||
void flush_all();
|
||||
if (_err_handler)
|
||||
new_logger->set_error_handler(_err_handler);
|
||||
|
||||
void drop(const std::string &logger_name);
|
||||
new_logger->set_level(_level);
|
||||
|
||||
void drop_all();
|
||||
|
||||
// clean all resources and threads started by the registry
|
||||
void shutdown();
|
||||
//Add to registry
|
||||
_loggers[logger_name] = new_logger;
|
||||
return new_logger;
|
||||
}
|
||||
|
||||
std::recursive_mutex &tp_mutex();
|
||||
void apply_all(std::function<void(std::shared_ptr<logger>)> fun)
|
||||
{
|
||||
std::lock_guard<Mutex> lock(_mutex);
|
||||
for (auto &l : _loggers)
|
||||
fun(l.second);
|
||||
}
|
||||
|
||||
void set_automatic_registration(bool automatic_registration);
|
||||
void drop(const std::string& logger_name)
|
||||
{
|
||||
std::lock_guard<Mutex> lock(_mutex);
|
||||
_loggers.erase(logger_name);
|
||||
}
|
||||
|
||||
// set levels for all existing/future loggers. global_level can be null if should not set.
|
||||
void set_levels(log_levels levels, level::level_enum *global_level);
|
||||
void drop_all()
|
||||
{
|
||||
std::lock_guard<Mutex> lock(_mutex);
|
||||
_loggers.clear();
|
||||
}
|
||||
std::shared_ptr<logger> create(const std::string& logger_name, sinks_init_list sinks)
|
||||
{
|
||||
return create(logger_name, sinks.begin(), sinks.end());
|
||||
}
|
||||
|
||||
static registry &instance();
|
||||
std::shared_ptr<logger> create(const std::string& logger_name, sink_ptr sink)
|
||||
{
|
||||
return create(logger_name, { sink });
|
||||
}
|
||||
|
||||
void apply_logger_env_levels(std::shared_ptr<logger> new_logger);
|
||||
|
||||
void formatter(formatter_ptr f)
|
||||
{
|
||||
std::lock_guard<Mutex> lock(_mutex);
|
||||
_formatter = f;
|
||||
for (auto& l : _loggers)
|
||||
l.second->set_formatter(_formatter);
|
||||
}
|
||||
|
||||
void set_pattern(const std::string& pattern)
|
||||
{
|
||||
std::lock_guard<Mutex> lock(_mutex);
|
||||
_formatter = std::make_shared<pattern_formatter>(pattern);
|
||||
for (auto& l : _loggers)
|
||||
l.second->set_formatter(_formatter);
|
||||
}
|
||||
|
||||
void set_level(level::level_enum log_level)
|
||||
{
|
||||
std::lock_guard<Mutex> lock(_mutex);
|
||||
for (auto& l : _loggers)
|
||||
l.second->set_level(log_level);
|
||||
_level = log_level;
|
||||
}
|
||||
|
||||
void set_error_handler(log_err_handler handler)
|
||||
{
|
||||
for (auto& l : _loggers)
|
||||
l.second->set_error_handler(handler);
|
||||
_err_handler = handler;
|
||||
}
|
||||
|
||||
void set_async_mode(size_t q_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb)
|
||||
{
|
||||
std::lock_guard<Mutex> lock(_mutex);
|
||||
_async_mode = true;
|
||||
_async_q_size = q_size;
|
||||
_overflow_policy = overflow_policy;
|
||||
_worker_warmup_cb = worker_warmup_cb;
|
||||
_flush_interval_ms = flush_interval_ms;
|
||||
_worker_teardown_cb = worker_teardown_cb;
|
||||
}
|
||||
|
||||
void set_sync_mode()
|
||||
{
|
||||
std::lock_guard<Mutex> lock(_mutex);
|
||||
_async_mode = false;
|
||||
}
|
||||
|
||||
static registry_t<Mutex>& instance()
|
||||
{
|
||||
static registry_t<Mutex> s_instance;
|
||||
return s_instance;
|
||||
}
|
||||
|
||||
private:
|
||||
registry();
|
||||
~registry();
|
||||
registry_t<Mutex>() {}
|
||||
registry_t<Mutex>(const registry_t<Mutex>&) = delete;
|
||||
registry_t<Mutex>& operator=(const registry_t<Mutex>&) = delete;
|
||||
|
||||
void throw_if_exists_(const std::string &logger_name);
|
||||
void register_logger_(std::shared_ptr<logger> new_logger);
|
||||
bool set_level_from_cfg_(logger *logger);
|
||||
std::mutex logger_map_mutex_, flusher_mutex_;
|
||||
std::recursive_mutex tp_mutex_;
|
||||
std::unordered_map<std::string, std::shared_ptr<logger>> loggers_;
|
||||
log_levels log_levels_;
|
||||
std::unique_ptr<formatter> formatter_;
|
||||
spdlog::level::level_enum global_log_level_ = level::info;
|
||||
level::level_enum flush_level_ = level::off;
|
||||
err_handler err_handler_;
|
||||
std::shared_ptr<thread_pool> tp_;
|
||||
std::unique_ptr<periodic_worker> periodic_flusher_;
|
||||
std::shared_ptr<logger> default_logger_;
|
||||
bool automatic_registration_ = true;
|
||||
size_t backtrace_n_messages_ = 0;
|
||||
void throw_if_exists(const std::string &logger_name)
|
||||
{
|
||||
if (_loggers.find(logger_name) != _loggers.end())
|
||||
throw spdlog_ex("logger with name '" + logger_name + "' already exists");
|
||||
}
|
||||
Mutex _mutex;
|
||||
std::unordered_map <std::string, std::shared_ptr<logger>> _loggers;
|
||||
formatter_ptr _formatter;
|
||||
level::level_enum _level = level::info;
|
||||
log_err_handler _err_handler;
|
||||
bool _async_mode = false;
|
||||
size_t _async_q_size = 0;
|
||||
async_overflow_policy _overflow_policy = async_overflow_policy::block_retry;
|
||||
std::function<void()> _worker_warmup_cb = nullptr;
|
||||
std::chrono::milliseconds _flush_interval_ms;
|
||||
std::function<void()> _worker_teardown_cb = nullptr;
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "registry-inl.h"
|
||||
#ifdef SPDLOG_NO_REGISTRY_MUTEX
|
||||
typedef registry_t<spdlog::details::null_mutex> registry;
|
||||
#else
|
||||
typedef registry_t<std::mutex> registry;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
182
include/spdlog/details/spdlog_impl.h
Normal file
182
include/spdlog/details/spdlog_impl.h
Normal file
@ -0,0 +1,182 @@
|
||||
//
|
||||
// Copyright(c) 2015 Gabi Melman.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
//
|
||||
// Global registry functions
|
||||
//
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <spdlog/details/registry.h>
|
||||
#include <spdlog/sinks/file_sinks.h>
|
||||
#include <spdlog/sinks/stdout_sinks.h>
|
||||
#include <spdlog/sinks/syslog_sink.h>
|
||||
#include <spdlog/sinks/ansicolor_sink.h>
|
||||
#include <spdlog/sinks/android_sink.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
inline void spdlog::register_logger(std::shared_ptr<logger> logger)
|
||||
{
|
||||
return details::registry::instance().register_logger(logger);
|
||||
}
|
||||
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::get(const std::string& name)
|
||||
{
|
||||
return details::registry::instance().get(name);
|
||||
}
|
||||
|
||||
inline void spdlog::drop(const std::string &name)
|
||||
{
|
||||
details::registry::instance().drop(name);
|
||||
}
|
||||
|
||||
// Create multi/single threaded simple file logger
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::basic_logger_mt(const std::string& logger_name, const filename_t& filename, bool truncate)
|
||||
{
|
||||
return create<spdlog::sinks::simple_file_sink_mt>(logger_name, filename, truncate);
|
||||
}
|
||||
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::basic_logger_st(const std::string& logger_name, const filename_t& filename, bool truncate)
|
||||
{
|
||||
return create<spdlog::sinks::simple_file_sink_st>(logger_name, filename, truncate);
|
||||
}
|
||||
|
||||
// Create multi/single threaded rotating file logger
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::rotating_logger_mt(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files)
|
||||
{
|
||||
return create<spdlog::sinks::rotating_file_sink_mt>(logger_name, filename, SPDLOG_FILENAME_T("txt"), max_file_size, max_files);
|
||||
}
|
||||
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::rotating_logger_st(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files)
|
||||
{
|
||||
return create<spdlog::sinks::rotating_file_sink_st>(logger_name, filename, SPDLOG_FILENAME_T("txt"), max_file_size, max_files);
|
||||
}
|
||||
|
||||
// Create file logger which creates new file at midnight):
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::daily_logger_mt(const std::string& logger_name, const filename_t& filename, int hour, int minute)
|
||||
{
|
||||
return create<spdlog::sinks::daily_file_sink_mt>(logger_name, filename, SPDLOG_FILENAME_T("txt"), hour, minute);
|
||||
}
|
||||
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::daily_logger_st(const std::string& logger_name, const filename_t& filename, int hour, int minute)
|
||||
{
|
||||
return create<spdlog::sinks::daily_file_sink_st>(logger_name, filename, SPDLOG_FILENAME_T("txt"), hour, minute);
|
||||
}
|
||||
|
||||
// Create stdout/stderr loggers (with optinal color support)
|
||||
inline std::shared_ptr<spdlog::logger> create_console_logger(const std::string& logger_name, spdlog::sink_ptr sink, bool color)
|
||||
{
|
||||
if (color) //use color wrapper sink
|
||||
sink = std::make_shared<spdlog::sinks::ansicolor_sink>(sink);
|
||||
return spdlog::details::registry::instance().create(logger_name, sink);
|
||||
}
|
||||
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::stdout_logger_mt(const std::string& logger_name, bool color)
|
||||
{
|
||||
return create_console_logger(logger_name, sinks::stdout_sink_mt::instance(), color);
|
||||
}
|
||||
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::stdout_logger_st(const std::string& logger_name, bool color)
|
||||
{
|
||||
return create_console_logger(logger_name, sinks::stdout_sink_st::instance(), color);
|
||||
}
|
||||
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::stderr_logger_mt(const std::string& logger_name, bool color)
|
||||
{
|
||||
return create_console_logger(logger_name, sinks::stderr_sink_mt::instance(), color);
|
||||
}
|
||||
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::stderr_logger_st(const std::string& logger_name, bool color)
|
||||
{
|
||||
return create_console_logger(logger_name, sinks::stderr_sink_st::instance(), color);
|
||||
}
|
||||
|
||||
#ifdef SPDLOG_ENABLE_SYSLOG
|
||||
// Create syslog logger
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::syslog_logger(const std::string& logger_name, const std::string& syslog_ident, int syslog_option)
|
||||
{
|
||||
return create<spdlog::sinks::syslog_sink>(logger_name, syslog_ident, syslog_option);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::android_logger(const std::string& logger_name, const std::string& tag)
|
||||
{
|
||||
return create<spdlog::sinks::android_sink>(logger_name, tag);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Create and register a logger a single sink
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, const spdlog::sink_ptr& sink)
|
||||
{
|
||||
return details::registry::instance().create(logger_name, sink);
|
||||
}
|
||||
|
||||
//Create logger with multiple sinks
|
||||
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, spdlog::sinks_init_list sinks)
|
||||
{
|
||||
return details::registry::instance().create(logger_name, sinks);
|
||||
}
|
||||
|
||||
|
||||
template <typename Sink, typename... Args>
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, Args... args)
|
||||
{
|
||||
sink_ptr sink = std::make_shared<Sink>(args...);
|
||||
return details::registry::instance().create(logger_name, { sink });
|
||||
}
|
||||
|
||||
|
||||
template<class It>
|
||||
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end)
|
||||
{
|
||||
return details::registry::instance().create(logger_name, sinks_begin, sinks_end);
|
||||
}
|
||||
|
||||
inline void spdlog::set_formatter(spdlog::formatter_ptr f)
|
||||
{
|
||||
details::registry::instance().formatter(f);
|
||||
}
|
||||
|
||||
inline void spdlog::set_pattern(const std::string& format_string)
|
||||
{
|
||||
return details::registry::instance().set_pattern(format_string);
|
||||
}
|
||||
|
||||
inline void spdlog::set_level(level::level_enum log_level)
|
||||
{
|
||||
return details::registry::instance().set_level(log_level);
|
||||
}
|
||||
|
||||
inline void spdlog::set_error_handler(log_err_handler handler)
|
||||
{
|
||||
return details::registry::instance().set_error_handler(handler);
|
||||
}
|
||||
|
||||
|
||||
inline void spdlog::set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb)
|
||||
{
|
||||
details::registry::instance().set_async_mode(queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb);
|
||||
}
|
||||
|
||||
inline void spdlog::set_sync_mode()
|
||||
{
|
||||
details::registry::instance().set_sync_mode();
|
||||
}
|
||||
|
||||
inline void spdlog::apply_all(std::function<void(std::shared_ptr<logger>)> fun)
|
||||
{
|
||||
details::registry::instance().apply_all(fun);
|
||||
}
|
||||
|
||||
inline void spdlog::drop_all()
|
||||
{
|
||||
details::registry::instance().drop_all();
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "registry.h"
|
||||
|
||||
namespace spdlog {
|
||||
|
||||
// Default logger factory- creates synchronous loggers
|
||||
class logger;
|
||||
|
||||
struct synchronous_factory {
|
||||
template <typename Sink, typename... SinkArgs>
|
||||
static std::shared_ptr<spdlog::logger> create(std::string logger_name, SinkArgs &&...args) {
|
||||
auto sink = std::make_shared<Sink>(std::forward<SinkArgs>(args)...);
|
||||
auto new_logger = std::make_shared<spdlog::logger>(std::move(logger_name), std::move(sink));
|
||||
details::registry::instance().initialize_logger(new_logger);
|
||||
return new_logger;
|
||||
}
|
||||
};
|
||||
} // namespace spdlog
|
@ -1,135 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
// tcp client helper
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string>
|
||||
#include <windows.h>
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
|
||||
#pragma comment(lib, "Ws2_32.lib")
|
||||
#pragma comment(lib, "Mswsock.lib")
|
||||
#pragma comment(lib, "AdvApi32.lib")
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
class tcp_client {
|
||||
SOCKET socket_ = INVALID_SOCKET;
|
||||
|
||||
static void init_winsock_() {
|
||||
WSADATA wsaData;
|
||||
auto rv = WSAStartup(MAKEWORD(2, 2), &wsaData);
|
||||
if (rv != 0) {
|
||||
throw_winsock_error_("WSAStartup failed", ::WSAGetLastError());
|
||||
}
|
||||
}
|
||||
|
||||
static void throw_winsock_error_(const std::string &msg, int last_error) {
|
||||
char buf[512];
|
||||
::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
|
||||
last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf,
|
||||
(sizeof(buf) / sizeof(char)), NULL);
|
||||
|
||||
throw_spdlog_ex(fmt_lib::format("tcp_sink - {}: {}", msg, buf));
|
||||
}
|
||||
|
||||
public:
|
||||
tcp_client() { init_winsock_(); }
|
||||
|
||||
~tcp_client() {
|
||||
close();
|
||||
::WSACleanup();
|
||||
}
|
||||
|
||||
bool is_connected() const { return socket_ != INVALID_SOCKET; }
|
||||
|
||||
void close() {
|
||||
::closesocket(socket_);
|
||||
socket_ = INVALID_SOCKET;
|
||||
}
|
||||
|
||||
SOCKET fd() const { return socket_; }
|
||||
|
||||
// try to connect or throw on failure
|
||||
void connect(const std::string &host, int port) {
|
||||
if (is_connected()) {
|
||||
close();
|
||||
}
|
||||
struct addrinfo hints {};
|
||||
ZeroMemory(&hints, sizeof(hints));
|
||||
|
||||
hints.ai_family = AF_UNSPEC; // To work with IPv4, IPv6, and so on
|
||||
hints.ai_socktype = SOCK_STREAM; // TCP
|
||||
hints.ai_flags = AI_NUMERICSERV; // port passed as as numeric value
|
||||
hints.ai_protocol = 0;
|
||||
|
||||
auto port_str = std::to_string(port);
|
||||
struct addrinfo *addrinfo_result;
|
||||
auto rv = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &addrinfo_result);
|
||||
int last_error = 0;
|
||||
if (rv != 0) {
|
||||
last_error = ::WSAGetLastError();
|
||||
WSACleanup();
|
||||
throw_winsock_error_("getaddrinfo failed", last_error);
|
||||
}
|
||||
|
||||
// Try each address until we successfully connect(2).
|
||||
|
||||
for (auto *rp = addrinfo_result; rp != nullptr; rp = rp->ai_next) {
|
||||
socket_ = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
|
||||
if (socket_ == INVALID_SOCKET) {
|
||||
last_error = ::WSAGetLastError();
|
||||
WSACleanup();
|
||||
continue;
|
||||
}
|
||||
if (::connect(socket_, rp->ai_addr, (int)rp->ai_addrlen) == 0) {
|
||||
break;
|
||||
} else {
|
||||
last_error = ::WSAGetLastError();
|
||||
close();
|
||||
}
|
||||
}
|
||||
::freeaddrinfo(addrinfo_result);
|
||||
if (socket_ == INVALID_SOCKET) {
|
||||
WSACleanup();
|
||||
throw_winsock_error_("connect failed", last_error);
|
||||
}
|
||||
|
||||
// set TCP_NODELAY
|
||||
int enable_flag = 1;
|
||||
::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&enable_flag),
|
||||
sizeof(enable_flag));
|
||||
}
|
||||
|
||||
// Send exactly n_bytes of the given data.
|
||||
// On error close the connection and throw.
|
||||
void send(const char *data, size_t n_bytes) {
|
||||
size_t bytes_sent = 0;
|
||||
while (bytes_sent < n_bytes) {
|
||||
const int send_flags = 0;
|
||||
auto write_result =
|
||||
::send(socket_, data + bytes_sent, (int)(n_bytes - bytes_sent), send_flags);
|
||||
if (write_result == SOCKET_ERROR) {
|
||||
int last_error = ::WSAGetLastError();
|
||||
close();
|
||||
throw_winsock_error_("send failed", last_error);
|
||||
}
|
||||
|
||||
if (write_result == 0) // (probably should not happen but in any case..)
|
||||
{
|
||||
break;
|
||||
}
|
||||
bytes_sent += static_cast<size_t>(write_result);
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,127 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifdef _WIN32
|
||||
#error include tcp_client-windows.h instead
|
||||
#endif
|
||||
|
||||
// tcp client helper
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
class tcp_client {
|
||||
int socket_ = -1;
|
||||
|
||||
public:
|
||||
bool is_connected() const { return socket_ != -1; }
|
||||
|
||||
void close() {
|
||||
if (is_connected()) {
|
||||
::close(socket_);
|
||||
socket_ = -1;
|
||||
}
|
||||
}
|
||||
|
||||
int fd() const { return socket_; }
|
||||
|
||||
~tcp_client() { close(); }
|
||||
|
||||
// try to connect or throw on failure
|
||||
void connect(const std::string &host, int port) {
|
||||
close();
|
||||
struct addrinfo hints {};
|
||||
memset(&hints, 0, sizeof(struct addrinfo));
|
||||
hints.ai_family = AF_UNSPEC; // To work with IPv4, IPv6, and so on
|
||||
hints.ai_socktype = SOCK_STREAM; // TCP
|
||||
hints.ai_flags = AI_NUMERICSERV; // port passed as as numeric value
|
||||
hints.ai_protocol = 0;
|
||||
|
||||
auto port_str = std::to_string(port);
|
||||
struct addrinfo *addrinfo_result;
|
||||
auto rv = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &addrinfo_result);
|
||||
if (rv != 0) {
|
||||
throw_spdlog_ex(fmt_lib::format("::getaddrinfo failed: {}", gai_strerror(rv)));
|
||||
}
|
||||
|
||||
// Try each address until we successfully connect(2).
|
||||
int last_errno = 0;
|
||||
for (auto *rp = addrinfo_result; rp != nullptr; rp = rp->ai_next) {
|
||||
#if defined(SOCK_CLOEXEC)
|
||||
const int flags = SOCK_CLOEXEC;
|
||||
#else
|
||||
const int flags = 0;
|
||||
#endif
|
||||
socket_ = ::socket(rp->ai_family, rp->ai_socktype | flags, rp->ai_protocol);
|
||||
if (socket_ == -1) {
|
||||
last_errno = errno;
|
||||
continue;
|
||||
}
|
||||
rv = ::connect(socket_, rp->ai_addr, rp->ai_addrlen);
|
||||
if (rv == 0) {
|
||||
break;
|
||||
}
|
||||
last_errno = errno;
|
||||
::close(socket_);
|
||||
socket_ = -1;
|
||||
}
|
||||
::freeaddrinfo(addrinfo_result);
|
||||
if (socket_ == -1) {
|
||||
throw_spdlog_ex("::connect failed", last_errno);
|
||||
}
|
||||
|
||||
// set TCP_NODELAY
|
||||
int enable_flag = 1;
|
||||
::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&enable_flag),
|
||||
sizeof(enable_flag));
|
||||
|
||||
// prevent sigpipe on systems where MSG_NOSIGNAL is not available
|
||||
#if defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
|
||||
::setsockopt(socket_, SOL_SOCKET, SO_NOSIGPIPE, reinterpret_cast<char *>(&enable_flag),
|
||||
sizeof(enable_flag));
|
||||
#endif
|
||||
|
||||
#if !defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
|
||||
#error "tcp_sink would raise SIGPIPE since neither SO_NOSIGPIPE nor MSG_NOSIGNAL are available"
|
||||
#endif
|
||||
}
|
||||
|
||||
// Send exactly n_bytes of the given data.
|
||||
// On error close the connection and throw.
|
||||
void send(const char *data, size_t n_bytes) {
|
||||
size_t bytes_sent = 0;
|
||||
while (bytes_sent < n_bytes) {
|
||||
#if defined(MSG_NOSIGNAL)
|
||||
const int send_flags = MSG_NOSIGNAL;
|
||||
#else
|
||||
const int send_flags = 0;
|
||||
#endif
|
||||
auto write_result =
|
||||
::send(socket_, data + bytes_sent, n_bytes - bytes_sent, send_flags);
|
||||
if (write_result < 0) {
|
||||
close();
|
||||
throw_spdlog_ex("write(2) failed", errno);
|
||||
}
|
||||
|
||||
if (write_result == 0) // (probably should not happen but in any case..)
|
||||
{
|
||||
break;
|
||||
}
|
||||
bytes_sent += static_cast<size_t>(write_result);
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,127 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/details/thread_pool.h>
|
||||
#endif
|
||||
|
||||
#include <cassert>
|
||||
#include <spdlog/common.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items,
|
||||
size_t threads_n,
|
||||
std::function<void()> on_thread_start,
|
||||
std::function<void()> on_thread_stop)
|
||||
: q_(q_max_items) {
|
||||
if (threads_n == 0 || threads_n > 1000) {
|
||||
throw_spdlog_ex(
|
||||
"spdlog::thread_pool(): invalid threads_n param (valid "
|
||||
"range is 1-1000)");
|
||||
}
|
||||
for (size_t i = 0; i < threads_n; i++) {
|
||||
threads_.emplace_back([this, on_thread_start, on_thread_stop] {
|
||||
on_thread_start();
|
||||
this->thread_pool::worker_loop_();
|
||||
on_thread_stop();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items,
|
||||
size_t threads_n,
|
||||
std::function<void()> on_thread_start)
|
||||
: thread_pool(q_max_items, threads_n, on_thread_start, [] {}) {}
|
||||
|
||||
SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n)
|
||||
: thread_pool(
|
||||
q_max_items, threads_n, [] {}, [] {}) {}
|
||||
|
||||
// message all threads to terminate gracefully join them
|
||||
SPDLOG_INLINE thread_pool::~thread_pool() {
|
||||
SPDLOG_TRY {
|
||||
for (size_t i = 0; i < threads_.size(); i++) {
|
||||
post_async_msg_(async_msg(async_msg_type::terminate), async_overflow_policy::block);
|
||||
}
|
||||
|
||||
for (auto &t : threads_) {
|
||||
t.join();
|
||||
}
|
||||
}
|
||||
SPDLOG_CATCH_STD
|
||||
}
|
||||
|
||||
void SPDLOG_INLINE thread_pool::post_log(async_logger_ptr &&worker_ptr,
|
||||
const details::log_msg &msg,
|
||||
async_overflow_policy overflow_policy) {
|
||||
async_msg async_m(std::move(worker_ptr), async_msg_type::log, msg);
|
||||
post_async_msg_(std::move(async_m), overflow_policy);
|
||||
}
|
||||
|
||||
void SPDLOG_INLINE thread_pool::post_flush(async_logger_ptr &&worker_ptr,
|
||||
async_overflow_policy overflow_policy) {
|
||||
post_async_msg_(async_msg(std::move(worker_ptr), async_msg_type::flush), overflow_policy);
|
||||
}
|
||||
|
||||
size_t SPDLOG_INLINE thread_pool::overrun_counter() { return q_.overrun_counter(); }
|
||||
|
||||
void SPDLOG_INLINE thread_pool::reset_overrun_counter() { q_.reset_overrun_counter(); }
|
||||
|
||||
size_t SPDLOG_INLINE thread_pool::discard_counter() { return q_.discard_counter(); }
|
||||
|
||||
void SPDLOG_INLINE thread_pool::reset_discard_counter() { q_.reset_discard_counter(); }
|
||||
|
||||
size_t SPDLOG_INLINE thread_pool::queue_size() { return q_.size(); }
|
||||
|
||||
void SPDLOG_INLINE thread_pool::post_async_msg_(async_msg &&new_msg,
|
||||
async_overflow_policy overflow_policy) {
|
||||
if (overflow_policy == async_overflow_policy::block) {
|
||||
q_.enqueue(std::move(new_msg));
|
||||
} else if (overflow_policy == async_overflow_policy::overrun_oldest) {
|
||||
q_.enqueue_nowait(std::move(new_msg));
|
||||
} else {
|
||||
assert(overflow_policy == async_overflow_policy::discard_new);
|
||||
q_.enqueue_if_have_room(std::move(new_msg));
|
||||
}
|
||||
}
|
||||
|
||||
void SPDLOG_INLINE thread_pool::worker_loop_() {
|
||||
while (process_next_msg_()) {
|
||||
}
|
||||
}
|
||||
|
||||
// process next message in the queue
|
||||
// return true if this thread should still be active (while no terminate msg
|
||||
// was received)
|
||||
bool SPDLOG_INLINE thread_pool::process_next_msg_() {
|
||||
async_msg incoming_async_msg;
|
||||
q_.dequeue(incoming_async_msg);
|
||||
|
||||
switch (incoming_async_msg.msg_type) {
|
||||
case async_msg_type::log: {
|
||||
incoming_async_msg.worker_ptr->backend_sink_it_(incoming_async_msg);
|
||||
return true;
|
||||
}
|
||||
case async_msg_type::flush: {
|
||||
incoming_async_msg.worker_ptr->backend_flush_();
|
||||
return true;
|
||||
}
|
||||
|
||||
case async_msg_type::terminate: {
|
||||
return false;
|
||||
}
|
||||
|
||||
default: {
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,117 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/details/log_msg_buffer.h>
|
||||
#include <spdlog/details/mpmc_blocking_q.h>
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace spdlog {
|
||||
class async_logger;
|
||||
|
||||
namespace details {
|
||||
|
||||
using async_logger_ptr = std::shared_ptr<spdlog::async_logger>;
|
||||
|
||||
enum class async_msg_type { log, flush, terminate };
|
||||
|
||||
// Async msg to move to/from the queue
|
||||
// Movable only. should never be copied
|
||||
struct async_msg : log_msg_buffer {
|
||||
async_msg_type msg_type{async_msg_type::log};
|
||||
async_logger_ptr worker_ptr;
|
||||
|
||||
async_msg() = default;
|
||||
~async_msg() = default;
|
||||
|
||||
// should only be moved in or out of the queue..
|
||||
async_msg(const async_msg &) = delete;
|
||||
|
||||
// support for vs2013 move
|
||||
#if defined(_MSC_VER) && _MSC_VER <= 1800
|
||||
async_msg(async_msg &&other)
|
||||
: log_msg_buffer(std::move(other)),
|
||||
msg_type(other.msg_type),
|
||||
worker_ptr(std::move(other.worker_ptr)) {}
|
||||
|
||||
async_msg &operator=(async_msg &&other) {
|
||||
*static_cast<log_msg_buffer *>(this) = std::move(other);
|
||||
msg_type = other.msg_type;
|
||||
worker_ptr = std::move(other.worker_ptr);
|
||||
return *this;
|
||||
}
|
||||
#else // (_MSC_VER) && _MSC_VER <= 1800
|
||||
async_msg(async_msg &&) = default;
|
||||
async_msg &operator=(async_msg &&) = default;
|
||||
#endif
|
||||
|
||||
// construct from log_msg with given type
|
||||
async_msg(async_logger_ptr &&worker, async_msg_type the_type, const details::log_msg &m)
|
||||
: log_msg_buffer{m},
|
||||
msg_type{the_type},
|
||||
worker_ptr{std::move(worker)} {}
|
||||
|
||||
async_msg(async_logger_ptr &&worker, async_msg_type the_type)
|
||||
: log_msg_buffer{},
|
||||
msg_type{the_type},
|
||||
worker_ptr{std::move(worker)} {}
|
||||
|
||||
explicit async_msg(async_msg_type the_type)
|
||||
: async_msg{nullptr, the_type} {}
|
||||
};
|
||||
|
||||
class SPDLOG_API thread_pool {
|
||||
public:
|
||||
using item_type = async_msg;
|
||||
using q_type = details::mpmc_blocking_queue<item_type>;
|
||||
|
||||
thread_pool(size_t q_max_items,
|
||||
size_t threads_n,
|
||||
std::function<void()> on_thread_start,
|
||||
std::function<void()> on_thread_stop);
|
||||
thread_pool(size_t q_max_items, size_t threads_n, std::function<void()> on_thread_start);
|
||||
thread_pool(size_t q_max_items, size_t threads_n);
|
||||
|
||||
// message all threads to terminate gracefully and join them
|
||||
~thread_pool();
|
||||
|
||||
thread_pool(const thread_pool &) = delete;
|
||||
thread_pool &operator=(thread_pool &&) = delete;
|
||||
|
||||
void post_log(async_logger_ptr &&worker_ptr,
|
||||
const details::log_msg &msg,
|
||||
async_overflow_policy overflow_policy);
|
||||
void post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy overflow_policy);
|
||||
size_t overrun_counter();
|
||||
void reset_overrun_counter();
|
||||
size_t discard_counter();
|
||||
void reset_discard_counter();
|
||||
size_t queue_size();
|
||||
|
||||
private:
|
||||
q_type q_;
|
||||
|
||||
std::vector<std::thread> threads_;
|
||||
|
||||
void post_async_msg_(async_msg &&new_msg, async_overflow_policy overflow_policy);
|
||||
void worker_loop_();
|
||||
|
||||
// process next message in the queue
|
||||
// return true if this thread should still be active (while no terminate msg
|
||||
// was received)
|
||||
bool process_next_msg_();
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "thread_pool-inl.h"
|
||||
#endif
|
@ -1,98 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
// Helper RAII over winsock udp client socket.
|
||||
// Will throw on construction if socket creation failed.
|
||||
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/details/windows_include.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string>
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#pragma comment(lib, "Ws2_32.lib")
|
||||
#pragma comment(lib, "Mswsock.lib")
|
||||
#pragma comment(lib, "AdvApi32.lib")
|
||||
#endif
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
class udp_client {
|
||||
static constexpr int TX_BUFFER_SIZE = 1024 * 10;
|
||||
SOCKET socket_ = INVALID_SOCKET;
|
||||
sockaddr_in addr_ = {};
|
||||
|
||||
static void init_winsock_() {
|
||||
WSADATA wsaData;
|
||||
auto rv = ::WSAStartup(MAKEWORD(2, 2), &wsaData);
|
||||
if (rv != 0) {
|
||||
throw_winsock_error_("WSAStartup failed", ::WSAGetLastError());
|
||||
}
|
||||
}
|
||||
|
||||
static void throw_winsock_error_(const std::string &msg, int last_error) {
|
||||
char buf[512];
|
||||
::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
|
||||
last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf,
|
||||
(sizeof(buf) / sizeof(char)), NULL);
|
||||
|
||||
throw_spdlog_ex(fmt_lib::format("udp_sink - {}: {}", msg, buf));
|
||||
}
|
||||
|
||||
void cleanup_() {
|
||||
if (socket_ != INVALID_SOCKET) {
|
||||
::closesocket(socket_);
|
||||
}
|
||||
socket_ = INVALID_SOCKET;
|
||||
::WSACleanup();
|
||||
}
|
||||
|
||||
public:
|
||||
udp_client(const std::string &host, uint16_t port) {
|
||||
init_winsock_();
|
||||
|
||||
addr_.sin_family = PF_INET;
|
||||
addr_.sin_port = htons(port);
|
||||
addr_.sin_addr.s_addr = INADDR_ANY;
|
||||
if (InetPtonA(PF_INET, host.c_str(), &addr_.sin_addr.s_addr) != 1) {
|
||||
int last_error = ::WSAGetLastError();
|
||||
::WSACleanup();
|
||||
throw_winsock_error_("error: Invalid address!", last_error);
|
||||
}
|
||||
|
||||
socket_ = ::socket(PF_INET, SOCK_DGRAM, 0);
|
||||
if (socket_ == INVALID_SOCKET) {
|
||||
int last_error = ::WSAGetLastError();
|
||||
::WSACleanup();
|
||||
throw_winsock_error_("error: Create Socket failed", last_error);
|
||||
}
|
||||
|
||||
int option_value = TX_BUFFER_SIZE;
|
||||
if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,
|
||||
reinterpret_cast<const char *>(&option_value), sizeof(option_value)) < 0) {
|
||||
int last_error = ::WSAGetLastError();
|
||||
cleanup_();
|
||||
throw_winsock_error_("error: setsockopt(SO_SNDBUF) Failed!", last_error);
|
||||
}
|
||||
}
|
||||
|
||||
~udp_client() { cleanup_(); }
|
||||
|
||||
SOCKET fd() const { return socket_; }
|
||||
|
||||
void send(const char *data, size_t n_bytes) {
|
||||
socklen_t tolen = sizeof(struct sockaddr);
|
||||
if (::sendto(socket_, data, static_cast<int>(n_bytes), 0, (struct sockaddr *)&addr_,
|
||||
tolen) == -1) {
|
||||
throw_spdlog_ex("sendto(2) failed", errno);
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,81 +0,0 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
// Helper RAII over unix udp client socket.
|
||||
// Will throw on construction if the socket creation failed.
|
||||
|
||||
#ifdef _WIN32
|
||||
#error "include udp_client-windows.h instead"
|
||||
#endif
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <cstring>
|
||||
#include <netdb.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/udp.h>
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/os.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
class udp_client {
|
||||
static constexpr int TX_BUFFER_SIZE = 1024 * 10;
|
||||
int socket_ = -1;
|
||||
struct sockaddr_in sockAddr_;
|
||||
|
||||
void cleanup_() {
|
||||
if (socket_ != -1) {
|
||||
::close(socket_);
|
||||
socket_ = -1;
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
udp_client(const std::string &host, uint16_t port) {
|
||||
socket_ = ::socket(PF_INET, SOCK_DGRAM, 0);
|
||||
if (socket_ < 0) {
|
||||
throw_spdlog_ex("error: Create Socket Failed!");
|
||||
}
|
||||
|
||||
int option_value = TX_BUFFER_SIZE;
|
||||
if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,
|
||||
reinterpret_cast<const char *>(&option_value), sizeof(option_value)) < 0) {
|
||||
cleanup_();
|
||||
throw_spdlog_ex("error: setsockopt(SO_SNDBUF) Failed!");
|
||||
}
|
||||
|
||||
sockAddr_.sin_family = AF_INET;
|
||||
sockAddr_.sin_port = htons(port);
|
||||
|
||||
if (::inet_aton(host.c_str(), &sockAddr_.sin_addr) == 0) {
|
||||
cleanup_();
|
||||
throw_spdlog_ex("error: Invalid address!");
|
||||
}
|
||||
|
||||
::memset(sockAddr_.sin_zero, 0x00, sizeof(sockAddr_.sin_zero));
|
||||
}
|
||||
|
||||
~udp_client() { cleanup_(); }
|
||||
|
||||
int fd() const { return socket_; }
|
||||
|
||||
// Send exactly n_bytes of the given data.
|
||||
// On error close the connection and throw.
|
||||
void send(const char *data, size_t n_bytes) {
|
||||
ssize_t toslen = 0;
|
||||
socklen_t tolen = sizeof(struct sockaddr);
|
||||
if ((toslen = ::sendto(socket_, data, n_bytes, 0, (struct sockaddr *)&sockAddr_, tolen)) ==
|
||||
-1) {
|
||||
throw_spdlog_ex("sendto(2) failed", errno);
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX // prevent windows redefining min/max
|
||||
#endif
|
||||
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
|
||||
#include <windows.h>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user