Compare commits

...

51 Commits

Author SHA1 Message Date
gabime
b6b9d835c5 Version 1.1.0 2018-08-15 19:34:10 +03:00
gabime
ebea09c8b4 Added pedantic flag to compiler in cmake 2018-08-15 19:09:37 +03:00
gabime
137f801ec7 Merge branch 'v1.x' of https://github.com/gabime/spdlog into v1.x 2018-08-15 19:02:07 +03:00
gabime
3d58f8d471 code formatting 2018-08-15 19:01:54 +03:00
gabime
b962fbb15c Fixed issue #797 2018-08-15 19:01:44 +03:00
Gabi Melman
e8927dc75f Merge pull request #796 from DanielChabrowski/cmake-refactor
Little cmake and tests refactor
2018-08-14 23:21:11 +03:00
Daniel Chabrowski
fb37585bc1 Little cmake and tests refactor
Change from spdlog_ex to const spdlog_ex& got rid of the GCC8 warning.
2018-08-14 21:33:47 +02:00
gabime
4a871b9792 Added some mpmc_q tests 2018-08-14 17:59:14 +03:00
gabime
057bf1b92d Added some mpmc_q tests 2018-08-14 17:57:55 +03:00
gabime
750b520f41 Fix broken build 2018-08-14 16:38:35 +03:00
Gabi Melman
c23f36c734 Merge pull request #795 from indiosmo/queue_full_counter
Expose a counter for how many messages were dropped in async mode
2018-08-14 16:36:38 +03:00
Luiz Siqueira
4eb80dd8d2 acquire lock before reading overrun_counter 2018-08-14 10:11:03 -03:00
Luiz Siqueira
c543985cf4 use size_t instead of int for overrun counter 2018-08-14 09:21:52 -03:00
Luiz Siqueira
863f704f47 increment counter every time we overrid a message in async mode. 2018-08-14 08:51:20 -03:00
gabime
54896763ab Update readme 2018-08-14 01:51:22 +03:00
Gabi Melman
0272bd2846 Update README.md 2018-08-14 01:50:09 +03:00
gabime
70f3ed66f4 Update readme 2018-08-14 01:46:57 +03:00
gabime
1dba3162c4 Fixed travis 2018-08-14 01:19:29 +03:00
gabime
cb0d8cfbbd Fixed travis 2018-08-14 01:15:39 +03:00
gabime
08064716b3 Fixed cmake for bench 2018-08-14 01:05:16 +03:00
gabime
dca20731a2 Added thread sanitizer tests to travis CI 2018-08-14 01:02:05 +03:00
gabime
530e209f66 Fixed async tests to pass TASN checks 2018-08-14 00:58:50 +03:00
gabime
566df7e826 Added missing include to q 2018-08-14 00:58:09 +03:00
gabime
56b3a17e56 Udpated README 2018-08-13 12:38:36 +03:00
gabime
d6cc5847fa Udpated README 2018-08-13 12:37:15 +03:00
gabime
1d672d39cf Udpated README 2018-08-13 12:33:58 +03:00
gabime
aefde13858 formatting 2018-08-13 12:27:25 +03:00
gabime
607779cccf micro optimization in log_msg constructor 2018-08-13 12:27:11 +03:00
gabime
da2af6ea2e Fixed some clang-tidy warning 2018-08-13 11:43:00 +03:00
gabime
ba337d1393 Fixed warning in tests 2018-08-13 11:16:50 +03:00
gabime
6ae240c0b6 code formatting and clang tidy warnings fixes 2018-08-13 10:32:07 +03:00
gabime
05d6960ebc code formatting and clang tidy warnings fixes 2018-08-13 10:30:02 +03:00
gabime
4866f2ac05 Put override kw again 2018-08-13 09:27:11 +03:00
gabime
4456f96ae3 Fixed clang warnings 2018-08-13 09:21:47 +03:00
gabime
8008d7fe53 Replace emplace_back with push_back in pattern_formatter 2018-08-13 09:09:49 +03:00
gabime
0a585092dc Added ASAN test in release build to travis 2018-08-13 02:02:17 +03:00
gabime
387ccae7d8 Removed gcc7 debug from travis 2018-08-13 01:59:49 +03:00
gabime
d951ea32a6 travis improvments 2018-08-13 01:44:10 +03:00
gabime
da30e2ef18 Improved CMakeLists and added bench 2018-08-13 01:22:35 +03:00
Gabi Melman
cb299375f6 Merge pull request #789 from DanielChabrowski/ci-v1
Modify travis-ci, fix compilation issues
2018-08-12 21:52:26 +03:00
Daniel Chabrowski
4534d5239f Remove tsan and gcc 4.9 jobs 2018-08-12 20:34:30 +02:00
Daniel Chabrowski
af5a516443 Add valgrind to a clang6 addon
Unfortunately valgrind is required for all addons
2018-08-12 18:51:34 +02:00
Daniel Chabrowski
368b3699d0 Run ASAN/TSAN jobs with clang
Bring back removed tests/Makefile
2018-08-12 18:42:54 +02:00
Daniel Chabrowski
49d663f6c8 Move tsan/asan flag management to cmake
Add sudo: required to fix asan builds
2018-08-12 17:11:56 +02:00
Daniel Chabrowski
7e32ccbd8f Modify travis-ci, fix issues
Added:
* Release/Debug job for gcc 7 and clang 3.5
* Debug asan gcc 7 job
* Debug tsan gcc 7 job
* Disabled extensions
* Added a spdlog::spdlog alias for tests

Removed:
* Valgrind workaround, the current version is 3.10.1
* install_libcxx
* Makefiles

Fixed:
* examples build
* multisink build

Workarounds:
* gcc7 with tsan and asan needs gold linker, otherwise build
  fails becase of unrecognized option '--push-state'
2018-08-11 02:24:45 +02:00
Gabi Melman
f8f2d7b950 Merge pull request #786 from rajesh-p/v1.x
Namespace fix  for the issue 785
2018-08-10 09:45:31 +03:00
rajesh-p
769f11109d Namespace fix for the issue 785
Added namespace fix
2018-08-09 21:17:53 -07:00
Gabi Melman
85a2bf1c17 Merge pull request #784 from baishuai/v1.x
add new line at end of file, fix compiler warnings #778
2018-08-08 22:29:14 +03:00
baishuai
a2fa7a833c add new line at end of file, fix compiler warnings 2018-08-08 22:59:57 +08:00
Gabi Melman
8179b26388 Update file_log.cpp 2018-08-07 03:29:45 +03:00
Gabi Melman
12bbef308b Update README.md 2018-08-06 22:19:16 +03:00
37 changed files with 509 additions and 267 deletions

View File

@@ -2,90 +2,112 @@
# - Louis Dionne's Hana: https://github.com/ldionne/hana # - Louis Dionne's Hana: https://github.com/ldionne/hana
# - Paul Fultz II's FIT: https://github.com/pfultz2/Fit # - Paul Fultz II's FIT: https://github.com/pfultz2/Fit
# - Eric Niebler's range-v3: https://github.com/ericniebler/range-v3 # - Eric Niebler's range-v3: https://github.com/ericniebler/range-v3
sudo: required
language: cpp language: cpp
# Test matrix: addons: &gcc48
# - Build matrix per compiler: C++11/C++14 + Debug/Release apt:
# - Optionally: AddressSanitizer (ASAN) packages:
# - Valgrind: all release builds are also tested with valgrind - g++-4.8
# - clang 3.4, 3.5, 3.6, trunk - valgrind
# - Note: 3.4 and trunk are tested with/without ASAN, sources:
# the rest is only tested with ASAN=On. - ubuntu-toolchain-r-test
# - gcc 4.9, 5.0
# addons: &gcc7
apt:
packages:
- g++-7
- valgrind
sources:
- ubuntu-toolchain-r-test
addons: &clang35
apt:
packages:
- clang-3.5
- valgrind
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.5
addons: &clang6
apt:
packages:
- clang-6.0
- valgrind
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-trusty-6.0
matrix: matrix:
include: include:
# Test gcc-4.8: C++11, Build=Debug/Release
# Test gcc-4.8: C++11, Build=Debug/Release, ASAN=Off - env: GCC_VERSION=4.8 BUILD_TYPE=Debug CPP=11
- 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 os: linux
addons: *gcc48 addons: *gcc48
# Test gcc-4.9: C++11, Build=Debug/Release, ASAN=Off - env: GCC_VERSION=4.8 BUILD_TYPE=Release CPP=11
- env: GCC_VERSION=4.9 BUILD_TYPE=Debug CPP=11 ASAN=Off LIBCXX=Off
os: linux os: linux
addons: &gcc49 addons: *gcc48
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 - env: GCC_VERSION=7 BUILD_TYPE=Release CPP=11
os: linux os: linux
addons: *gcc49 addons: *gcc7
# Install dependencies # Test clang-3.5: C++11, Build=Debug/Release
before_install: - env: CLANG_VERSION=3.5 BUILD_TYPE=Debug CPP=11
- export CHECKOUT_PATH=`pwd`; os: linux
addons: *clang35
- env: CLANG_VERSION=3.5 BUILD_TYPE=Release CPP=11
os: linux
addons: *clang35
# Test clang-6.0: C++11, Build=Debug, ASAN=On
- env: CLANG_VERSION=6.0 BUILD_TYPE=Debug CPP=11 ASAN=On TSAN=Off
os: linux
addons: *clang6
- env: CLANG_VERSION=6.0 BUILD_TYPE=Release CPP=11 ASAN=On TSAN=Off
os: linux
addons: *clang6
# Test clang-6.0: C++11, Build=Debug, TSAN=On
- env: CLANG_VERSION=6.0 BUILD_TYPE=Debug CPP=11 ASAN=Off TSAN=On
os: linux
addons: *clang6
- env: CLANG_VERSION=6.0 BUILD_TYPE=Release CPP=11 ASAN=Off TSAN=On
os: linux
addons: *clang6
before_script:
- if [ -n "$GCC_VERSION" ]; then export CXX="g++-${GCC_VERSION}" CC="gcc-${GCC_VERSION}"; fi - 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 [ -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 $CXX
- which $CC - which $CC
- which valgrind - which valgrind
- if [ -n "$CLANG_VERSION" ]; then sudo CXX=$CXX CC=$CC ./tests/install_libcxx.sh; fi - $CXX --version
- cmake --version
install: - valgrind --version
- 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: script:
- ./"${BIN}" - cd ${TRAVIS_BUILD_DIR}
- valgrind --trace-children=yes --leak-check=full ./"${BIN}" - mkdir -p build && cd build
- cd $CHECKOUT_PATH/tests; make rebuild; ./tests - |
- cd $CHECKOUT_PATH/tests; STYLE=printf make rebuild; ./tests cmake .. \
--warn-uninitialized \
-DCMAKE_BUILD_TYPE=$BUILD_TYPE \
-DCMAKE_CXX_STANDARD=$CPP \
-DSPDLOG_BUILD_EXAMPLES=ON \
-DSPDLOG_BUILD_BENCH=OFF \
-DSPDLOG_SANITIZE_ADDRESS=$ASAN \
-DSPDLOG_SANITIZE_THREAD=$TSAN
- make VERBOSE=1 -j2
- ctest -j2 --output-on-failure
notifications: notifications:
email: false email: false

View File

@@ -4,27 +4,47 @@
# #
cmake_minimum_required(VERSION 3.1) cmake_minimum_required(VERSION 3.1)
project(spdlog VERSION 1.0.0 LANGUAGES CXX) project(spdlog VERSION 1.1.0 LANGUAGES CXX)
include(CTest) include(CTest)
include(CMakeDependentOption) include(CMakeDependentOption)
include(GNUInstallDirs) include(GNUInstallDirs)
#---------------------------------------------------------------------------------------
# set default build to release
#---------------------------------------------------------------------------------------
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE)
endif()
message(STATUS "Build type: " ${CMAKE_BUILD_TYPE})
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
# compiler config # compiler config
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
set(CMAKE_CXX_FLAGS "-Wall -O3 ${CMAKE_CXX_FLAGS}") add_compile_options("-Wall")
add_compile_options("-Wextra")
add_compile_options("-pedantic")
endif() endif()
#---------------------------------------------------------------------------------------
# address sanitizers check
#---------------------------------------------------------------------------------------
include(cmake/sanitizers.cmake)
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
# spdlog target # spdlog target
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
add_library(spdlog INTERFACE) add_library(spdlog INTERFACE)
add_library(spdlog::spdlog ALIAS spdlog)
option(SPDLOG_BUILD_EXAMPLES "Build examples" ON)
option(SPDLOG_BUILD_BENCH "Build benchmarks" ON)
option(SPDLOG_BUILD_EXAMPLES "Build examples" OFF)
cmake_dependent_option(SPDLOG_BUILD_TESTING cmake_dependent_option(SPDLOG_BUILD_TESTING
"Build spdlog tests" ON "Build spdlog tests" ON
"BUILD_TESTING" OFF "BUILD_TESTING" OFF
@@ -47,6 +67,10 @@ if(SPDLOG_BUILD_TESTING)
add_subdirectory(tests) add_subdirectory(tests)
endif() endif()
if(SPDLOG_BUILD_BENCH)
add_subdirectory(bench)
endif()
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
# Install/export targets and files # Install/export targets and files
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------

View File

@@ -28,7 +28,7 @@ Very fast, header only, C++ logging library. [![Build Status](https://travis-ci.
## Features ## Features
* Very fast - performance is the primary goal (see [benchmarks](#benchmarks) below). * Very fast - performance is the primary goal (see [benchmarks](#benchmarks) below).
* Headers only, just copy and use. * Headers only, just copy and use.
* Feature rich [call style](#usage-example) using the excellent [fmt](https://github.com/fmtlib/fmt) library. * Feature rich using the excellent [fmt](https://github.com/fmtlib/fmt) library.
* Fast asynchronous mode (optional) * Fast asynchronous mode (optional)
* [Custom](https://github.com/gabime/spdlog/wiki/3.-Custom-formatting) formatting. * [Custom](https://github.com/gabime/spdlog/wiki/3.-Custom-formatting) formatting.
* Conditional Logging * Conditional Logging
@@ -53,27 +53,28 @@ Below are some [benchmarks](https://github.com/gabime/spdlog/blob/v1.x/bench/ben
******************************************************************************* *******************************************************************************
Single thread, 1,000,000 iterations Single thread, 1,000,000 iterations
******************************************************************************* *******************************************************************************
basic_st... Elapsed: 0.231041 4,328,228/sec basic_st... Elapsed: 0.226664 4,411,806/sec
rotating... Elapsed: 0.233466 4,283,282/sec rotating_st... Elapsed: 0.214339 4,665,499/sec
daily_st... Elapsed: 0.244491 4,090,136/sec daily_st... Elapsed: 0.211292 4,732,797/sec
null_st... Elapsed: 0.162708 6,145,995/sec null_st... Elapsed: 0.102815 9,726,227/sec
******************************************************************************* *******************************************************************************
10 threads sharing same logger, 1,000,000 iterations 10 threads sharing same logger, 1,000,000 iterations
******************************************************************************* *******************************************************************************
basic_mt... Elapsed: 0.854029 1,170,920/sec basic_mt... Elapsed: 0.882268 1,133,441/sec
rotating_mt Elapsed: 0.867038 1,153,351/sec rotating_mt... Elapsed: 0.875515 1,142,184/sec
daily_mt... Elapsed: 0.869593 1,149,963/sec daily_mt... Elapsed: 0.879573 1,136,915/sec
null_mt... Elapsed: 0.171215 2,033,537/sec null_mt... Elapsed: 0.220114 4,543,105/sec
``` ```
#### Asynchronous mode #### Asynchronous mode
``` ```
******************************************************************************* *******************************************************************************
10 threads sharing same logger, 1,000,000 iterations 10 threads sharing same logger, 1,000,000 iterations
******************************************************************************* *******************************************************************************
async... Elapsed: 0.442731 2,258,706/sec async... Elapsed: 0.429088 2,330,524/sec
async... Elapsed: 0.427072 2,341,527/sec async... Elapsed: 0.411501 2,430,126/sec
async... Elapsed: 0.449768 2,223,369/sec async... Elapsed: 0.428979 2,331,116/sec
``` ```
## Usage samples ## Usage samples
@@ -166,22 +167,9 @@ spdlog::flush_every(std::chrono::seconds(3));
``` ```
---
#### Asynchronous logging
```c++
#include "spdlog/async.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");
}
```
--- ---
#### Logger with multi targets - each with different format and log level #### Logger with multi sinks - each with different format and log level
```c++ ```c++
// create logger with 2 targets with different log levels and formats. // create logger with 2 targets with different log levels and formats.
@@ -201,6 +189,40 @@ void multi_sink_example()
logger.info("this message should not appear in the console, only in the file"); logger.info("this message should not appear in the console, only in the file");
} }
``` ```
---
#### 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/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 #### User defined types
```c++ ```c++
@@ -240,7 +262,7 @@ void err_handler_example()
void syslog_example() void syslog_example()
{ {
std::string ident = "spdlog-example"; std::string ident = "spdlog-example";
auto syslog_logger = spdlog::syslog_logger("syslog", ident, LOG_PID); auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog."); syslog_logger->warn("This is warning that will end up in syslog.");
} }
``` ```

43
bench/CMakeLists.txt Normal file
View File

@@ -0,0 +1,43 @@
# *************************************************************************/
# * 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.1)
project(SpdlogBench CXX)
if(NOT TARGET spdlog)
# Stand-alone build
find_package(spdlog CONFIG REQUIRED)
endif()
find_package(Threads REQUIRED)
add_executable(bench bench.cpp)
target_link_libraries(bench spdlog::spdlog Threads::Threads)
add_executable(async_bench async_bench.cpp)
target_link_libraries(async_bench spdlog::spdlog Threads::Threads)
add_executable(latency latency.cpp)
target_link_libraries(latency spdlog::spdlog Threads::Threads)
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs")

21
cmake/sanitizers.cmake Normal file
View File

@@ -0,0 +1,21 @@
if(SPDLOG_SANITIZE_THREAD AND SPDLOG_SANITIZE_ADDRESS)
message(FATAL_ERROR "AddressSanitizer is not compatible with ThreadSanitizer.")
endif()
if(SPDLOG_SANITIZE_ADDRESS)
message(STATUS "AddressSanitizer enabled")
set(SANITIZER_FLAGS "-fsanitize=address,undefined")
add_compile_options("-fno-sanitize=signed-integer-overflow")
endif()
if(SPDLOG_SANITIZE_THREAD)
message(STATUS "ThreadSanitizer enabled")
set(SANITIZER_FLAGS "-fsanitize=thread")
endif()
if(SPDLOG_SANITIZE_THREAD OR SPDLOG_SANITIZE_ADDRESS)
add_compile_options(${SANITIZER_FLAGS})
add_compile_options("-fno-sanitize-recover=all")
add_compile_options("-fno-omit-frame-pointer")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${SANITIZER_FLAGS} -fuse-ld=gold")
endif()

View File

@@ -24,10 +24,7 @@
cmake_minimum_required(VERSION 3.1) cmake_minimum_required(VERSION 3.1)
project(SpdlogExamples CXX) project(SpdlogExamples CXX)
if(TARGET spdlog) if(NOT TARGET spdlog)
# Part of the main project
add_library(spdlog::spdlog ALIAS spdlog)
else()
# Stand-alone build # Stand-alone build
find_package(spdlog CONFIG REQUIRED) find_package(spdlog CONFIG REQUIRED)
endif() endif()
@@ -37,13 +34,10 @@ find_package(Threads REQUIRED)
add_executable(example example.cpp) add_executable(example example.cpp)
target_link_libraries(example spdlog::spdlog Threads::Threads) target_link_libraries(example spdlog::spdlog Threads::Threads)
add_executable(benchmark bench.cpp)
target_link_libraries(benchmark spdlog::spdlog Threads::Threads)
add_executable(multisink multisink.cpp) add_executable(multisink multisink.cpp)
target_link_libraries(multisink spdlog::spdlog Threads::Threads) target_link_libraries(multisink spdlog::spdlog Threads::Threads)
enable_testing()
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs")
add_test(NAME RunExample COMMAND example)
add_test(NAME RunBenchmark COMMAND benchmark) enable_testing()
add_test(NAME example COMMAND example)

View File

@@ -1,10 +1,9 @@
#include "spdlog/sinks/file_sinks.h" #include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/stdout_sinks.h" #include "spdlog/sinks/stdout_sinks.h"
#include "spdlog/spdlog.h" #include "spdlog/spdlog.h"
#include <iostream> #include <iostream>
#include <memory> #include <memory>
namespace spd = spdlog;
int main(int, char *[]) int main(int, char *[])
{ {
bool enable_debug = true; bool enable_debug = true;
@@ -39,7 +38,7 @@ int main(int, char *[])
spdlog::drop_all(); spdlog::drop_all();
} }
// Exceptions will only be thrown upon failed logger or sink construction (not during logging) // Exceptions will only be thrown upon failed logger or sink construction (not during logging)
catch (const spd::spdlog_ex &ex) catch (const spdlog::spdlog_ex &ex)
{ {
std::cout << "Log init failed: " << ex.what() << std::endl; std::cout << "Log init failed: " << ex.what() << std::endl;
return 1; return 1;

View File

@@ -42,7 +42,7 @@ struct async_factory_impl
auto &registry_inst = details::registry::instance(); auto &registry_inst = details::registry::instance();
// create global thread pool if not already exists.. // create global thread pool if not already exists..
std::lock_guard<std::recursive_mutex>(registry_inst.tp_mutex()); std::lock_guard<std::recursive_mutex> tp_lock(registry_inst.tp_mutex());
auto tp = registry_inst.get_tp(); auto tp = registry_inst.get_tp();
if (tp == nullptr) if (tp == nullptr)
{ {

View File

@@ -49,7 +49,7 @@ public:
async_logger(std::string logger_name, const It &begin, const It &end, std::weak_ptr<details::thread_pool> tp, async_logger(std::string logger_name, const It &begin, const It &end, std::weak_ptr<details::thread_pool> tp,
async_overflow_policy overflow_policy = async_overflow_policy::block); async_overflow_policy overflow_policy = async_overflow_policy::block);
async_logger(std::string logger_name, sinks_init_list sinks, std::weak_ptr<details::thread_pool> tp, 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_overflow_policy overflow_policy = async_overflow_policy::block);
async_logger(std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp, async_logger(std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp,

View File

@@ -100,6 +100,7 @@ inline const char *to_short_c_str(spdlog::level::level_enum l)
{ {
return short_level_names[l]; return short_level_names[l];
} }
inline spdlog::level::level_enum from_str(const std::string &name) inline spdlog::level::level_enum from_str(const std::string &name)
{ {
static std::unordered_map<std::string, level_enum> name_to_level = // map string->level static std::unordered_map<std::string, level_enum> name_to_level = // map string->level
@@ -131,35 +132,28 @@ enum class pattern_time_type
// //
// Log exception // Log exception
// //
class spdlog_ex : public std::runtime_error class spdlog_ex : public std::exception
{ {
public: public:
explicit spdlog_ex(const std::string &msg) explicit spdlog_ex(const std::string &msg)
: runtime_error(msg) : msg_(msg)
{ {
} }
spdlog_ex(std::string msg, int last_errno)
: runtime_error(std::move(msg)) spdlog_ex(const std::string &msg, int last_errno)
, last_errno_(last_errno)
{ {
fmt::memory_buffer outbuf;
fmt::format_system_error(outbuf, last_errno, msg);
msg_ = fmt::to_string(outbuf);
} }
const char *what() const SPDLOG_NOEXCEPT override const char *what() const SPDLOG_NOEXCEPT override
{ {
if (last_errno_) return msg_.c_str();
{
fmt::memory_buffer buf;
std::string msg(runtime_error::what());
fmt::format_system_error(buf, last_errno_, msg);
return fmt::to_string(buf).c_str();
}
else
{
return runtime_error::what();
}
} }
private: private:
int last_errno_{0}; std::string msg_;
}; };
// //

View File

@@ -47,7 +47,7 @@ inline void spdlog::async_logger::sink_it_(details::log_msg &msg)
} }
else else
{ {
throw spdlog_ex("async log: thread pool doens't exist anymore"); throw spdlog_ex("async log: thread pool doesn't exist anymore");
} }
} }

View File

@@ -6,6 +6,8 @@
// cirucal q view of std::vector. // cirucal q view of std::vector.
#pragma once #pragma once
#include <vector>
namespace spdlog { namespace spdlog {
namespace details { namespace details {
template<typename T> template<typename T>
@@ -29,6 +31,7 @@ public:
if (tail_ == head_) // overrun last item if full if (tail_ == head_) // overrun last item if full
{ {
head_ = (head_ + 1) % max_items_; head_ = (head_ + 1) % max_items_;
++overrun_counter_;
} }
} }
@@ -51,12 +54,19 @@ public:
return ((tail_ + 1) % max_items_) == head_; return ((tail_ + 1) % max_items_) == head_;
} }
size_t overrun_counter() const
{
return overrun_counter_;
}
private: private:
size_t max_items_; size_t max_items_;
typename std::vector<T>::size_type head_ = 0; typename std::vector<T>::size_type head_ = 0;
typename std::vector<T>::size_type tail_ = 0; typename std::vector<T>::size_type tail_ = 0;
std::vector<T> v_; std::vector<T> v_;
size_t overrun_counter_ = 0;
}; };
} // namespace details } // namespace details
} // namespace spdlog } // namespace spdlog

View File

@@ -5,14 +5,14 @@
// //
#include "spdlog/details/null_mutex.h" #include "spdlog/details/null_mutex.h"
#include "stdio.h" #include <cstdio>
#include <mutex> #include <mutex>
namespace spdlog { namespace spdlog {
namespace details { namespace details {
struct console_stdout struct console_stdout
{ {
static FILE *stream() static std::FILE *stream()
{ {
return stdout; return stdout;
} }
@@ -26,7 +26,7 @@ struct console_stdout
struct console_stderr struct console_stderr
{ {
static FILE *stream() static std::FILE *stream()
{ {
return stderr; return stderr;
} }

View File

@@ -136,7 +136,7 @@ public:
// treat casese like "/etc/rc.d/somelogfile or "/abc/.hiddenfile" // treat casese like "/etc/rc.d/somelogfile or "/abc/.hiddenfile"
auto folder_index = fname.rfind(details::os::folder_sep); auto folder_index = fname.rfind(details::os::folder_sep);
if (folder_index != fname.npos && folder_index >= ext_index - 1) if (folder_index != filename_t::npos && folder_index >= ext_index - 1)
{ {
return std::make_tuple(fname, spdlog::filename_t()); return std::make_tuple(fname, spdlog::filename_t());
} }

View File

@@ -16,17 +16,18 @@ namespace details {
struct log_msg struct log_msg
{ {
log_msg() = default; log_msg() = default;
log_msg(const std::string *loggers_name, level::level_enum lvl) log_msg(const std::string *loggers_name, level::level_enum lvl)
: logger_name(loggers_name) : logger_name(loggers_name)
, level(lvl) , level(lvl)
{
#ifndef SPDLOG_NO_DATETIME #ifndef SPDLOG_NO_DATETIME
time = os::now(); , time(os::now())
#endif #endif
#ifndef SPDLOG_NO_THREAD_ID #ifndef SPDLOG_NO_THREAD_ID
thread_id = os::thread_id(); , thread_id(os::thread_id())
#endif #endif
{
} }
log_msg(const log_msg &other) = delete; log_msg(const log_msg &other) = delete;

View File

@@ -105,6 +105,12 @@ public:
#endif #endif
size_t overrun_counter()
{
std::unique_lock<std::mutex> lock(queue_mutex_);
return q_.overrun_counter();
}
private: private:
std::mutex queue_mutex_; std::mutex queue_mutex_;
std::condition_variable push_cv_; std::condition_variable push_cv_;

View File

@@ -69,7 +69,7 @@ static const char *ampm(const tm &t)
return t.tm_hour >= 12 ? "PM" : "AM"; return t.tm_hour >= 12 ? "PM" : "AM";
} }
static unsigned int to12h(const tm &t) static int to12h(const tm &t)
{ {
return t.tm_hour > 12 ? t.tm_hour - 12 : t.tm_hour; return t.tm_hour > 12 ? t.tm_hour - 12 : t.tm_hour;
} }
@@ -242,7 +242,7 @@ class f_formatter SPDLOG_FINAL : public flag_formatter
void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override
{ {
auto micros = fmt_helper::time_fraction<std::chrono::microseconds>(msg.time); auto micros = fmt_helper::time_fraction<std::chrono::microseconds>(msg.time);
fmt_helper::pad6(static_cast<int>(micros.count()), dest); fmt_helper::pad6(static_cast<size_t>(micros.count()), dest);
} }
}; };
@@ -545,7 +545,7 @@ public:
pattern_formatter(const pattern_formatter &other) = delete; pattern_formatter(const pattern_formatter &other) = delete;
pattern_formatter &operator=(const pattern_formatter &other) = delete; pattern_formatter &operator=(const pattern_formatter &other) = delete;
virtual std::unique_ptr<formatter> clone() const override std::unique_ptr<formatter> clone() const override
{ {
return std::unique_ptr<formatter>(new pattern_formatter(pattern_, pattern_time_type_, eol_)); return std::unique_ptr<formatter>(new pattern_formatter(pattern_, pattern_time_type_, eol_));
} }
@@ -588,145 +588,146 @@ private:
void handle_flag_(char flag) void handle_flag_(char flag)
{ {
using flag_formatter_ptr = std::unique_ptr<details::flag_formatter>;
switch (flag) switch (flag)
{ {
// logger name // logger name
case 'n': case 'n':
formatters_.emplace_back(new details::name_formatter()); formatters_.push_back(flag_formatter_ptr(new details::name_formatter()));
break; break;
case 'l': case 'l':
formatters_.emplace_back(new details::level_formatter()); formatters_.push_back(flag_formatter_ptr(new details::level_formatter()));
break; break;
case 'L': case 'L':
formatters_.emplace_back(new details::short_level_formatter()); formatters_.push_back(flag_formatter_ptr(new details::short_level_formatter()));
break; break;
case ('t'): case ('t'):
formatters_.emplace_back(new details::t_formatter()); formatters_.push_back(flag_formatter_ptr(new details::t_formatter()));
break; break;
case ('v'): case ('v'):
formatters_.emplace_back(new details::v_formatter()); formatters_.push_back(flag_formatter_ptr(new details::v_formatter()));
break; break;
case ('a'): case ('a'):
formatters_.emplace_back(new details::a_formatter()); formatters_.push_back(flag_formatter_ptr(new details::a_formatter()));
break; break;
case ('A'): case ('A'):
formatters_.emplace_back(new details::A_formatter()); formatters_.push_back(flag_formatter_ptr(new details::A_formatter()));
break; break;
case ('b'): case ('b'):
case ('h'): case ('h'):
formatters_.emplace_back(new details::b_formatter()); formatters_.push_back(flag_formatter_ptr(new details::b_formatter()));
break; break;
case ('B'): case ('B'):
formatters_.emplace_back(new details::B_formatter()); formatters_.push_back(flag_formatter_ptr(new details::B_formatter()));
break; break;
case ('c'): case ('c'):
formatters_.emplace_back(new details::c_formatter()); formatters_.push_back(flag_formatter_ptr(new details::c_formatter()));
break; break;
case ('C'): case ('C'):
formatters_.emplace_back(new details::C_formatter()); formatters_.push_back(flag_formatter_ptr(new details::C_formatter()));
break; break;
case ('Y'): case ('Y'):
formatters_.emplace_back(new details::Y_formatter()); formatters_.push_back(flag_formatter_ptr(new details::Y_formatter()));
break; break;
case ('D'): case ('D'):
case ('x'): case ('x'):
formatters_.emplace_back(new details::D_formatter()); formatters_.push_back(flag_formatter_ptr(new details::D_formatter()));
break; break;
case ('m'): case ('m'):
formatters_.emplace_back(new details::m_formatter()); formatters_.push_back(flag_formatter_ptr(new details::m_formatter()));
break; break;
case ('d'): case ('d'):
formatters_.emplace_back(new details::d_formatter()); formatters_.push_back(flag_formatter_ptr(new details::d_formatter()));
break; break;
case ('H'): case ('H'):
formatters_.emplace_back(new details::H_formatter()); formatters_.push_back(flag_formatter_ptr(new details::H_formatter()));
break; break;
case ('I'): case ('I'):
formatters_.emplace_back(new details::I_formatter()); formatters_.push_back(flag_formatter_ptr(new details::I_formatter()));
break; break;
case ('M'): case ('M'):
formatters_.emplace_back(new details::M_formatter()); formatters_.push_back(flag_formatter_ptr(new details::M_formatter()));
break; break;
case ('S'): case ('S'):
formatters_.emplace_back(new details::S_formatter()); formatters_.push_back(flag_formatter_ptr(new details::S_formatter()));
break; break;
case ('e'): case ('e'):
formatters_.emplace_back(new details::e_formatter()); formatters_.push_back(flag_formatter_ptr(new details::e_formatter()));
break; break;
case ('f'): case ('f'):
formatters_.emplace_back(new details::f_formatter()); formatters_.push_back(flag_formatter_ptr(new details::f_formatter()));
break; break;
case ('F'): case ('F'):
formatters_.emplace_back(new details::F_formatter()); formatters_.push_back(flag_formatter_ptr(new details::F_formatter()));
break; break;
case ('E'): case ('E'):
formatters_.emplace_back(new details::E_formatter()); formatters_.push_back(flag_formatter_ptr(new details::E_formatter()));
break; break;
case ('p'): case ('p'):
formatters_.emplace_back(new details::p_formatter()); formatters_.push_back(flag_formatter_ptr(new details::p_formatter()));
break; break;
case ('r'): case ('r'):
formatters_.emplace_back(new details::r_formatter()); formatters_.push_back(flag_formatter_ptr(new details::r_formatter()));
break; break;
case ('R'): case ('R'):
formatters_.emplace_back(new details::R_formatter()); formatters_.push_back(flag_formatter_ptr(new details::R_formatter()));
break; break;
case ('T'): case ('T'):
case ('X'): case ('X'):
formatters_.emplace_back(new details::T_formatter()); formatters_.push_back(flag_formatter_ptr(new details::T_formatter()));
break; break;
case ('z'): case ('z'):
formatters_.emplace_back(new details::z_formatter()); formatters_.push_back(flag_formatter_ptr(new details::z_formatter()));
break; break;
case ('+'): case ('+'):
formatters_.emplace_back(new details::full_formatter()); formatters_.push_back(flag_formatter_ptr(new details::full_formatter()));
break; break;
case ('P'): case ('P'):
formatters_.emplace_back(new details::pid_formatter()); formatters_.push_back(flag_formatter_ptr(new details::pid_formatter()));
break; break;
case ('i'): case ('i'):
formatters_.emplace_back(new details::i_formatter()); formatters_.push_back(flag_formatter_ptr(new details::i_formatter()));
break; break;
case ('^'): case ('^'):
formatters_.emplace_back(new details::color_start_formatter()); formatters_.push_back(flag_formatter_ptr(new details::color_start_formatter()));
break; break;
case ('$'): case ('$'):
formatters_.emplace_back(new details::color_stop_formatter()); formatters_.push_back(flag_formatter_ptr(new details::color_stop_formatter()));
break; break;
default: // Unknown flag appears as is default: // Unknown flag appears as is
formatters_.emplace_back(new details::ch_formatter('%')); formatters_.push_back(flag_formatter_ptr(new details::ch_formatter('%')));
formatters_.emplace_back(new details::ch_formatter(flag)); formatters_.push_back(flag_formatter_ptr(new details::ch_formatter(flag)));
break; break;
} }
} }
@@ -744,7 +745,6 @@ private:
{ {
formatters_.push_back(std::move(user_chars)); formatters_.push_back(std::move(user_chars));
} }
// if(
if (++it != end) if (++it != end)
{ {
handle_flag_(*it); handle_flag_(*it);

View File

@@ -23,7 +23,7 @@ namespace details {
class periodic_worker class periodic_worker
{ {
public: public:
periodic_worker(std::function<void()> callback_fun, std::chrono::seconds interval) periodic_worker(const std::function<void()> &callback_fun, std::chrono::seconds interval)
{ {
active_ = (interval > std::chrono::seconds::zero()); active_ = (interval > std::chrono::seconds::zero());
if (!active_) if (!active_)

View File

@@ -35,7 +35,7 @@ public:
std::lock_guard<std::mutex> lock(logger_map_mutex_); std::lock_guard<std::mutex> lock(logger_map_mutex_);
auto logger_name = new_logger->name(); auto logger_name = new_logger->name();
throw_if_exists_(logger_name); throw_if_exists_(logger_name);
loggers_[logger_name] = new_logger; loggers_[logger_name] = std::move(new_logger);
} }
void register_and_init(std::shared_ptr<logger> new_logger) void register_and_init(std::shared_ptr<logger> new_logger)
@@ -56,7 +56,7 @@ public:
new_logger->flush_on(flush_level_); new_logger->flush_on(flush_level_);
// add to registry // add to registry
loggers_[logger_name] = new_logger; loggers_[logger_name] = std::move(new_logger);
} }
std::shared_ptr<logger> get(const std::string &logger_name) std::shared_ptr<logger> get(const std::string &logger_name)
@@ -112,7 +112,7 @@ public:
void flush_every(std::chrono::seconds interval) void flush_every(std::chrono::seconds interval)
{ {
std::lock_guard<std::mutex> lock(flusher_mutex_); std::lock_guard<std::mutex> lock(flusher_mutex_);
std::function<void()> clbk(std::bind(&registry::flush_all, this)); std::function<void()> clbk = std::bind(&registry::flush_all, this);
periodic_flusher_.reset(new periodic_worker(clbk, interval)); periodic_flusher_.reset(new periodic_worker(clbk, interval));
} }
@@ -126,7 +126,7 @@ public:
err_handler_ = handler; err_handler_ = handler;
} }
void apply_all(std::function<void(std::shared_ptr<logger>)> fun) void apply_all(const std::function<void(const std::shared_ptr<logger>)> &fun)
{ {
std::lock_guard<std::mutex> lock(logger_map_mutex_); std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_) for (auto &l : loggers_)
@@ -189,11 +189,7 @@ private:
{ {
} }
~registry() ~registry() = default;
{
/*std::lock_guard<std::mutex> lock(flusher_mutex_);
periodic_flusher_.reset();*/
}
void throw_if_exists_(const std::string &logger_name) void throw_if_exists_(const std::string &logger_name)
{ {

View File

@@ -122,7 +122,7 @@ public:
} }
for (size_t i = 0; i < threads_n; i++) for (size_t i = 0; i < threads_n; i++)
{ {
threads_.emplace_back(std::bind(&thread_pool::worker_loop_, this)); threads_.emplace_back(&thread_pool::worker_loop_, this);
} }
} }
@@ -157,6 +157,11 @@ public:
post_async_msg_(async_msg(std::move(worker_ptr), async_msg_type::flush), overflow_policy); post_async_msg_(async_msg(std::move(worker_ptr), async_msg_type::flush), overflow_policy);
} }
size_t overrun_counter()
{
return q_.overrun_counter();
}
private: private:
q_type q_; q_type q_;

View File

@@ -30,8 +30,8 @@ template<typename Mutex>
class android_sink SPDLOG_FINAL : public base_sink<Mutex> class android_sink SPDLOG_FINAL : public base_sink<Mutex>
{ {
public: public:
explicit android_sink(const std::string &tag = "spdlog", bool use_raw_msg = false) explicit android_sink(std::string tag = "spdlog", bool use_raw_msg = false)
: tag_(tag) : tag_(std::move(tag))
, use_raw_msg_(use_raw_msg) , use_raw_msg_(use_raw_msg)
{ {
} }
@@ -43,11 +43,11 @@ protected:
fmt::memory_buffer formatted; fmt::memory_buffer formatted;
if (use_raw_msg_) if (use_raw_msg_)
{ {
fmt_helper::append_buf(msg.raw, formatted); details::fmt_helper::append_buf(msg.raw, formatted);
} }
else else
{ {
formatter_->format(msg, formatted); sink::formatter_->format(msg, formatted);
} }
formatted.push_back('\0'); formatted.push_back('\0');
const char *msg_output = formatted.data(); const char *msg_output = formatted.data();

View File

@@ -24,7 +24,7 @@ namespace sinks {
* If no color terminal detected, omit the escape codes. * If no color terminal detected, omit the escape codes.
*/ */
template<typename TargetStream, class ConsoleMutex> template<typename TargetStream, class ConsoleMutex>
class ansicolor_sink : public sink class ansicolor_sink SPDLOG_FINAL : public sink
{ {
public: public:
using mutex_t = typename ConsoleMutex::mutex_t; using mutex_t = typename ConsoleMutex::mutex_t;
@@ -84,7 +84,7 @@ public:
const std::string on_cyan = "\033[46m"; const std::string on_cyan = "\033[46m";
const std::string on_white = "\033[47m"; const std::string on_white = "\033[47m";
void log(const details::log_msg &msg) SPDLOG_FINAL override void log(const details::log_msg &msg) override
{ {
// Wrap the originally formatted message in color codes. // Wrap the originally formatted message in color codes.
// If color is not supported in the terminal, log as is instead. // If color is not supported in the terminal, log as is instead.
@@ -110,19 +110,19 @@ public:
fflush(target_file_); fflush(target_file_);
} }
void flush() SPDLOG_FINAL override void flush() override
{ {
std::lock_guard<mutex_t> lock(mutex_); std::lock_guard<mutex_t> lock(mutex_);
fflush(target_file_); fflush(target_file_);
} }
void set_pattern(const std::string &pattern) override SPDLOG_FINAL void set_pattern(const std::string &pattern) SPDLOG_FINAL
{ {
std::lock_guard<mutex_t> lock(mutex_); std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern)); formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));
} }
void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override SPDLOG_FINAL void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override
{ {
std::lock_guard<mutex_t> lock(mutex_); std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::move(sink_formatter); formatter_ = std::move(sink_formatter);

View File

@@ -30,7 +30,7 @@ public:
base_sink(const base_sink &) = delete; base_sink(const base_sink &) = delete;
base_sink &operator=(const base_sink &) = delete; base_sink &operator=(const base_sink &) = delete;
void log(const details::log_msg &msg) SPDLOG_FINAL override void log(const details::log_msg &msg) SPDLOG_FINAL
{ {
std::lock_guard<Mutex> lock(mutex_); std::lock_guard<Mutex> lock(mutex_);
sink_it_(msg); sink_it_(msg);

View File

@@ -20,7 +20,7 @@ public:
{ {
} }
sink(std::unique_ptr<spdlog::pattern_formatter> formatter) explicit sink(std::unique_ptr<spdlog::pattern_formatter> formatter)
: level_(level::trace) : level_(level::trace)
, formatter_(std::move(formatter)){}; , formatter_(std::move(formatter)){};

View File

@@ -19,7 +19,7 @@ namespace spdlog {
namespace sinks { namespace sinks {
template<typename TargetStream, typename ConsoleMutex> template<typename TargetStream, typename ConsoleMutex>
class stdout_sink : public sink class stdout_sink SPDLOG_FINAL : public sink
{ {
public: public:
using mutex_t = typename ConsoleMutex::mutex_t; using mutex_t = typename ConsoleMutex::mutex_t;
@@ -28,7 +28,7 @@ public:
, file_(TargetStream::stream()) , file_(TargetStream::stream())
{ {
} }
~stdout_sink() = default; ~stdout_sink() override = default;
stdout_sink(const stdout_sink &other) = delete; stdout_sink(const stdout_sink &other) = delete;
stdout_sink &operator=(const stdout_sink &other) = delete; stdout_sink &operator=(const stdout_sink &other) = delete;
@@ -48,13 +48,13 @@ public:
fflush(file_); fflush(file_);
} }
void set_pattern(const std::string &pattern) override SPDLOG_FINAL void set_pattern(const std::string &pattern) override
{ {
std::lock_guard<mutex_t> lock(mutex_); std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern)); formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));
} }
void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override SPDLOG_FINAL void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override
{ {
std::lock_guard<mutex_t> lock(mutex_); std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::move(sink_formatter); formatter_ = std::move(sink_formatter);

View File

@@ -24,8 +24,8 @@ class syslog_sink : public base_sink<Mutex>
{ {
public: public:
// //
syslog_sink(const std::string &ident = "", int syslog_option = 0, int syslog_facility = LOG_USER) explicit syslog_sink(std::string ident = "", int syslog_option = 0, int syslog_facility = LOG_USER)
: ident_(ident) : ident_(std::move(ident))
{ {
priorities_[static_cast<size_t>(level::trace)] = LOG_DEBUG; priorities_[static_cast<size_t>(level::trace)] = LOG_DEBUG;
priorities_[static_cast<size_t>(level::debug)] = LOG_DEBUG; priorities_[static_cast<size_t>(level::debug)] = LOG_DEBUG;

View File

@@ -64,7 +64,7 @@ inline void set_formatter(std::unique_ptr<spdlog::formatter> formatter)
// example: spdlog::set_pattern("%Y-%m-%d %H:%M:%S.%e %l : %v"); // example: spdlog::set_pattern("%Y-%m-%d %H:%M:%S.%e %l : %v");
inline void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local) inline void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local)
{ {
set_formatter(std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern, time_type))); set_formatter(std::unique_ptr<spdlog::formatter>(new pattern_formatter(std::move(pattern), time_type)));
} }
// Set global logging level // Set global logging level
@@ -101,9 +101,9 @@ inline void register_logger(std::shared_ptr<logger> logger)
// Apply a user defined function on all registered loggers // Apply a user defined function on all registered loggers
// Example: // Example:
// spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) {l->flush();}); // spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) {l->flush();});
inline void apply_all(std::function<void(std::shared_ptr<logger>)> fun) inline void apply_all(const std::function<void(std::shared_ptr<logger>)> &fun)
{ {
details::registry::instance().apply_all(std::move(fun)); details::registry::instance().apply_all(fun);
} }
// Drop the reference to the given logger // Drop the reference to the given logger

View File

@@ -6,7 +6,7 @@
#pragma once #pragma once
#define SPDLOG_VER_MAJOR 1 #define SPDLOG_VER_MAJOR 1
#define SPDLOG_VER_MINOR 0 #define SPDLOG_VER_MINOR 1
#define SPDLOG_VER_PATCH 0 #define SPDLOG_VER_PATCH 0
#define SPDLOG_VERSION (SPDLOG_VER_MAJOR * 10000 + SPDLOG_VER_MINOR * 100 + SPDLOG_VER_PATCH) #define SPDLOG_VERSION (SPDLOG_VER_MAJOR * 10000 + SPDLOG_VER_MINOR * 100 + SPDLOG_VER_PATCH)

View File

@@ -1,5 +1,5 @@
project(spdlog-utests CXX) project(spdlog-utests CXX)
enable_testing()
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
set(SPDLOG_UTESTS_SOURCES set(SPDLOG_UTESTS_SOURCES
@@ -7,18 +7,23 @@ set(SPDLOG_UTESTS_SOURCES
file_helper.cpp file_helper.cpp
file_log.cpp file_log.cpp
test_misc.cpp test_misc.cpp
test_pattern_formatter.cpp test_pattern_formatter.cpp
test_async.cpp test_async.cpp
includes.h includes.h
registry.cpp registry.cpp
test_macros.cpp test_macros.cpp
utils.cpp utils.cpp
utils.h utils.h
main.cpp) main.cpp
test_mpmc_q.cpp
test_sink.h
)
add_executable(${PROJECT_NAME} ${SPDLOG_UTESTS_SOURCES}) add_executable(${PROJECT_NAME} ${SPDLOG_UTESTS_SOURCES})
target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads)
target_link_libraries(${PROJECT_NAME} PRIVATE spdlog) target_link_libraries(${PROJECT_NAME} PRIVATE spdlog::spdlog)
add_test(NAME ${PROJECT_NAME} COMMAND ${PROJECT_NAME})
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs")
enable_testing()
add_test(NAME ${PROJECT_NAME} COMMAND ${PROJECT_NAME})

View File

@@ -9,15 +9,15 @@ class failing_sink : public spdlog::sinks::base_sink<std::mutex>
{ {
public: public:
failing_sink() = default; failing_sink() = default;
~failing_sink() = default; ~failing_sink() final = default;
protected: protected:
void sink_it_(const spdlog::details::log_msg &) override void sink_it_(const spdlog::details::log_msg &) final
{ {
throw std::runtime_error("some error happened during log"); throw std::runtime_error("some error happened during log");
} }
void flush_() override void flush_() final
{ {
throw std::runtime_error("some error happened during flush"); throw std::runtime_error("some error happened during flush");
} }
@@ -25,7 +25,6 @@ protected:
TEST_CASE("default_error_handler", "[errors]]") TEST_CASE("default_error_handler", "[errors]]")
{ {
prepare_logdir(); prepare_logdir();
std::string filename = "logs/simple_log.txt"; std::string filename = "logs/simple_log.txt";

View File

@@ -33,7 +33,7 @@ TEST_CASE("flush_on", "[flush_on]]")
logger->info("Test message {}", 1); logger->info("Test message {}", 1);
logger->info("Test message {}", 2); logger->info("Test message {}", 2);
logger->flush();
REQUIRE(file_contents(filename) == std::string("Should not be flushed\nTest message 1\nTest message 2\n")); REQUIRE(file_contents(filename) == std::string("Should not be flushed\nTest message 1\nTest message 2\n"));
REQUIRE(count_lines(filename) == 3); REQUIRE(count_lines(filename) == 3);
} }

View File

@@ -1,12 +0,0 @@
#!/bin/bash
#
# Install libc++ under travis
svn --quiet co http://llvm.org/svn/llvm-project/libcxx/trunk libcxx
mkdir libcxx/build
(cd libcxx/build && cmake .. -DLIBCXX_CXX_ABI=libstdc++ -DLIBCXX_CXX_ABI_INCLUDE_PATHS="/usr/include/c++/4.6;/usr/include/c++/4.6/x86_64-linux-gnu")
make -C libcxx/build cxx -j2
sudo cp libcxx/build/lib/libc++.so.1.0 /usr/lib/
sudo cp -r libcxx/build/include/c++/v1 /usr/include/c++/v1/
sudo ln -sf /usr/lib/libc++.so.1.0 /usr/lib/libc++.so
sudo ln -sf /usr/lib/libc++.so.1.0 /usr/lib/libc++.so.1

View File

@@ -9,7 +9,7 @@ TEST_CASE("register_drop", "[registry]")
spdlog::create<spdlog::sinks::null_sink_mt>(tested_logger_name); spdlog::create<spdlog::sinks::null_sink_mt>(tested_logger_name);
REQUIRE(spdlog::get(tested_logger_name) != nullptr); REQUIRE(spdlog::get(tested_logger_name) != nullptr);
// Throw if registring existing name // Throw if registring existing name
REQUIRE_THROWS_AS(spdlog::create<spdlog::sinks::null_sink_mt>(tested_logger_name), spdlog::spdlog_ex); REQUIRE_THROWS_AS(spdlog::create<spdlog::sinks::null_sink_mt>(tested_logger_name), const spdlog::spdlog_ex&);
} }
TEST_CASE("explicit register" TEST_CASE("explicit register"
@@ -20,7 +20,7 @@ TEST_CASE("explicit register"
spdlog::register_logger(logger); spdlog::register_logger(logger);
REQUIRE(spdlog::get(tested_logger_name) != nullptr); REQUIRE(spdlog::get(tested_logger_name) != nullptr);
// Throw if registring existing name // Throw if registring existing name
REQUIRE_THROWS_AS(spdlog::create<spdlog::sinks::null_sink_mt>(tested_logger_name), spdlog::spdlog_ex); REQUIRE_THROWS_AS(spdlog::create<spdlog::sinks::null_sink_mt>(tested_logger_name), const spdlog::spdlog_ex&);
} }
TEST_CASE("apply_all" TEST_CASE("apply_all"
@@ -33,7 +33,7 @@ TEST_CASE("apply_all"
spdlog::register_logger(logger2); spdlog::register_logger(logger2);
int counter = 0; int counter = 0;
spdlog::apply_all([&counter](std::shared_ptr<spdlog::logger> l) { counter++; }); spdlog::apply_all([&counter](std::shared_ptr<spdlog::logger>) { counter++; });
REQUIRE(counter == 2); REQUIRE(counter == 2);
counter = 0; counter = 0;

View File

@@ -7,6 +7,7 @@ TEST_CASE("basic async test ", "[async]")
{ {
using namespace spdlog; using namespace spdlog;
auto test_sink = std::make_shared<sinks::test_sink_mt>(); auto test_sink = std::make_shared<sinks::test_sink_mt>();
size_t overrun_counter = 0;
size_t queue_size = 128; size_t queue_size = 128;
size_t messages = 256; size_t messages = 256;
{ {
@@ -17,17 +18,20 @@ TEST_CASE("basic async test ", "[async]")
logger->info("Hello message #{}", i); logger->info("Hello message #{}", i);
} }
logger->flush(); logger->flush();
overrun_counter = tp->overrun_counter();
} }
REQUIRE(test_sink->msg_counter() == messages); REQUIRE(test_sink->msg_counter() == messages);
REQUIRE(test_sink->flush_counter() == 1); REQUIRE(test_sink->flush_counter() == 1);
REQUIRE(overrun_counter == 0);
} }
TEST_CASE("discard policy ", "[async]") TEST_CASE("discard policy ", "[async]")
{ {
using namespace spdlog; using namespace spdlog;
auto test_sink = std::make_shared<sinks::test_sink_mt>(); auto test_sink = std::make_shared<sinks::test_sink_mt>();
size_t queue_size = 2; test_sink->set_delay(std::chrono::milliseconds(1));
size_t messages = 10240; size_t queue_size = 4;
size_t messages = 1024;
auto tp = std::make_shared<details::thread_pool>(queue_size, 1); auto tp = std::make_shared<details::thread_pool>(queue_size, 1);
auto logger = std::make_shared<async_logger>("as", test_sink, tp, async_overflow_policy::overrun_oldest); auto logger = std::make_shared<async_logger>("as", test_sink, tp, async_overflow_policy::overrun_oldest);
@@ -36,22 +40,26 @@ TEST_CASE("discard policy ", "[async]")
logger->info("Hello message"); logger->info("Hello message");
} }
REQUIRE(test_sink->msg_counter() < messages); REQUIRE(test_sink->msg_counter() < messages);
REQUIRE(tp->overrun_counter() > 0);
} }
TEST_CASE("discard policy using factory ", "[async]") TEST_CASE("discard policy using factory ", "[async]")
{ {
using namespace spdlog; using namespace spdlog;
size_t queue_size = 2; size_t queue_size = 4;
size_t messages = 10240; size_t messages = 1024;
spdlog::init_thread_pool(queue_size, 1); spdlog::init_thread_pool(queue_size, 1);
auto logger = spdlog::create_async_nb<sinks::test_sink_mt>("as2"); auto logger = spdlog::create_async_nb<sinks::test_sink_mt>("as2");
auto test_sink = std::static_pointer_cast<sinks::test_sink_mt>(logger->sinks()[0]);
test_sink->set_delay(std::chrono::milliseconds(1));
for (size_t i = 0; i < messages; i++) for (size_t i = 0; i < messages; i++)
{ {
logger->info("Hello message"); logger->info("Hello message");
} }
auto sink = std::static_pointer_cast<sinks::test_sink_mt>(logger->sinks()[0]);
REQUIRE(sink->msg_counter() < messages); REQUIRE(test_sink->msg_counter() < messages);
spdlog::drop_all(); spdlog::drop_all();
} }

103
tests/test_mpmc_q.cpp Normal file
View File

@@ -0,0 +1,103 @@
#include "includes.h"
using namespace std::chrono;
using std::chrono::milliseconds;
using std::chrono::system_clock;
system_clock::time_point now_millis()
{
return time_point_cast<milliseconds>(system_clock::now());
}
TEST_CASE("dequeue-empty-nowait", "[mpmc_blocking_q]")
{
size_t q_size = 100;
milliseconds tolerance_wait(10);
spdlog::details::mpmc_blocking_queue<int> q(q_size);
int popped_item;
auto millis_0 = now_millis();
auto rv = q.dequeue_for(popped_item, milliseconds::zero());
auto millis_1 = now_millis();
REQUIRE(rv == false);
REQUIRE((millis_1 - millis_0) <= tolerance_wait);
}
TEST_CASE("dequeue-empty-wait", "[mpmc_blocking_q]")
{
size_t q_size = 100;
milliseconds wait_ms(250);
milliseconds tolerance_wait(10);
spdlog::details::mpmc_blocking_queue<int> q(q_size);
int popped_item;
auto millis_0 = now_millis();
auto rv = q.dequeue_for(popped_item, wait_ms);
auto millis_1 = now_millis();
auto delta_ms = millis_1 - millis_0;
REQUIRE(rv == false);
REQUIRE(delta_ms >= wait_ms);
REQUIRE(delta_ms <= wait_ms + tolerance_wait);
}
TEST_CASE("enqueue_nowait", "[mpmc_blocking_q]")
{
size_t q_size = 1;
spdlog::details::mpmc_blocking_queue<int> q(q_size);
milliseconds tolerance_wait(10);
q.enqueue(1);
REQUIRE(q.overrun_counter() == 0);
auto millis_0 = now_millis();
q.enqueue_nowait(2);
auto millis_1 = now_millis();
REQUIRE((millis_1 - millis_0) <= tolerance_wait);
REQUIRE(q.overrun_counter() == 1);
}
TEST_CASE("bad_queue", "[mpmc_blocking_q]")
{
size_t q_size = 0;
spdlog::details::mpmc_blocking_queue<int> q(q_size);
q.enqueue_nowait(1);
REQUIRE(q.overrun_counter() == 1);
int i;
REQUIRE(q.dequeue_for(i, milliseconds(0)) == false);
}
TEST_CASE("empty_queue", "[mpmc_blocking_q]")
{
size_t q_size = 10;
spdlog::details::mpmc_blocking_queue<int> q(q_size);
int i;
REQUIRE(q.dequeue_for(i, milliseconds(10)) == false);
}
TEST_CASE("full_queue", "[mpmc_blocking_q]")
{
size_t q_size = 100;
spdlog::details::mpmc_blocking_queue<int> q(q_size);
for (int i = 0; i < static_cast<int>(q_size); i++)
{
q.enqueue(std::move(i));
}
q.enqueue_nowait(123456);
REQUIRE(q.overrun_counter() == 1);
for (int i = 1; i < static_cast<int>(q_size); i++)
{
int item = -1;
q.dequeue_for(item, milliseconds(0));
REQUIRE(item == i);
}
// last item pushed has overridden the oldest.
int item = -1;
q.dequeue_for(item, milliseconds(0));
REQUIRE(item == 123456);
}

View File

@@ -21,11 +21,13 @@ class test_sink : public base_sink<Mutex>
public: public:
size_t msg_counter() size_t msg_counter()
{ {
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
return msg_counter_; return msg_counter_;
} }
size_t flush_counter() size_t flush_counter()
{ {
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
return flush_counter_; return flush_counter_;
} }