Commit 22f85deb authored by Philip Miller's avatar Philip Miller

Merge remote-tracking branch 'origin/v1.x' into pwm1234/rotate_on_open

parents 52a01b2c 1cb49bfe
...@@ -2,90 +2,114 @@ ...@@ -2,90 +2,114 @@
# - 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
# - 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: apt:
packages: packages:
- g++-4.8 - g++-4.8
- valgrind
sources: sources:
- ubuntu-toolchain-r-test - ubuntu-toolchain-r-test
- env: GCC_VERSION=4.8 BUILD_TYPE=Release CPP=11 ASAN=Off LIBCXX=Off addons: &gcc7
os: linux apt:
addons: *gcc48 packages:
- g++-7
sources:
- ubuntu-toolchain-r-test
# Test gcc-4.9: C++11, Build=Debug/Release, ASAN=Off addons: &clang35
- env: GCC_VERSION=4.9 BUILD_TYPE=Debug CPP=11 ASAN=Off LIBCXX=Off
os: linux
addons: &gcc49
apt: apt:
packages: packages:
- g++-4.9 - clang-3.5
- valgrind
sources: sources:
- ubuntu-toolchain-r-test - ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.5
- env: GCC_VERSION=4.9 BUILD_TYPE=Release CPP=11 ASAN=Off LIBCXX=Off addons: &clang6
apt:
packages:
- clang-6.0
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-trusty-6.0
matrix:
include:
# Test gcc-4.8: C++11, Build=Debug/Release
- env: GCC_VERSION=4.8 BUILD_TYPE=Debug CPP=11
os: linux os: linux
addons: *gcc49 addons: *gcc48
# Install dependencies - env: GCC_VERSION=4.8 BUILD_TYPE=Release CPP=11
before_install: os: linux
- export CHECKOUT_PATH=`pwd`; addons: *gcc48
- 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 - env: GCC_VERSION=7 BUILD_TYPE=Release CPP=11
- if [ "$CLANG_VERSION" == "3.4" ]; then export CXX="/usr/local/clang-3.4/bin/clang++" CC="/usr/local/clang-3.4/bin/clang"; fi os: linux
- which $CXX addons: *gcc7
- which $CC
- which valgrind # Test clang-3.5: C++11, Build=Debug/Release
- if [ -n "$CLANG_VERSION" ]; then sudo CXX=$CXX CC=$CC ./tests/install_libcxx.sh; fi - env: CLANG_VERSION=3.5 BUILD_TYPE=Debug CPP=11
os: linux
addons: *clang35
install: - env: CLANG_VERSION=3.5 BUILD_TYPE=Release CPP=11
- cd $CHECKOUT_PATH os: linux
addons: *clang35
# Workaround for valgrind bug: https://bugs.kde.org/show_bug.cgi?id=326469. # Test clang-6.0: C++11, Build=Debug, ASAN=On
# It is fixed in valgrind 3.10 so this won't be necessary if someone - env: CLANG_VERSION=6.0 BUILD_TYPE=Debug CPP=11 ASAN=On TSAN=Off
# replaces the current valgrind (3.7) with valgrind-3.10 os: linux
- sed -i 's/march=native/msse4.2/' example/Makefile addons: *clang6
- if [ ! -d build ]; then mkdir build; fi - env: CLANG_VERSION=6.0 BUILD_TYPE=Release CPP=11 ASAN=On TSAN=Off
- export CXX_FLAGS="-I${CHECKOUT_PATH}/include" os: linux
- export CXX_LINKER_FLAGS="" addons: *clang6
- 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 # Test clang-6.0: C++11, Build=Debug, TSAN=On
- cd example - env: CLANG_VERSION=6.0 BUILD_TYPE=Debug CPP=11 ASAN=Off TSAN=On
- if [ "$BUILD_TYPE" == "Release" ]; then make rebuild CXXFLAGS="${CXX_FLAGS} ${CXX_LINKER_FLAGS}" VERBOSE=1; export BIN=example; fi os: linux
- if [ "$BUILD_TYPE" == "Debug" ]; then make rebuild debug CXXFLAGS="${CXX_FLAGS} ${CXX_LINKER_FLAGS}" VERBOSE=1; export BIN=example-debug; fi addons: *clang6
- env: CLANG_VERSION=6.0 BUILD_TYPE=Release CPP=11 ASAN=Off TSAN=On
os: linux
addons: *clang6
# osx
- env: BUILD_TYPE=Release CPP=11 ASAN=Off TSAN=Off
os: osx
before_script:
- 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 [[ "$TRAVIS_OS_NAME" == "osx" ]]; then export CXX="clang++" CC="clang"; fi
- which $CXX
- which $CC
- $CXX --version
- cmake --version
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
...@@ -4,27 +4,50 @@ ...@@ -4,27 +4,50 @@
# #
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("-Wconversion")
add_compile_options("-pedantic")
add_compile_options("-Wfatal-errors")
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 +70,10 @@ if(SPDLOG_BUILD_TESTING) ...@@ -47,6 +70,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
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
Very fast, header only, C++ logging library. [![Build Status](https://travis-ci.org/gabime/spdlog.svg?branch=master)](https://travis-ci.org/gabime/spdlog)  [![Build status](https://ci.appveyor.com/api/projects/status/d2jnxclg20vd0o50?svg=true)](https://ci.appveyor.com/project/gabime/spdlog) Very fast, header only, C++ logging library. [![Build Status](https://travis-ci.org/gabime/spdlog.svg?branch=master)](https://travis-ci.org/gabime/spdlog)  [![Build status](https://ci.appveyor.com/api/projects/status/d2jnxclg20vd0o50?svg=true)](https://ci.appveyor.com/project/gabime/spdlog)
## Install ## Install
#### Just copy the headers: #### Just copy the headers:
...@@ -28,7 +29,7 @@ Very fast, header only, C++ logging library. [![Build Status](https://travis-ci. ...@@ -28,7 +29,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 +54,28 @@ Below are some [benchmarks](https://github.com/gabime/spdlog/blob/v1.x/bench/ben ...@@ -53,27 +54,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
...@@ -157,6 +159,18 @@ void daily_example() ...@@ -157,6 +159,18 @@ void daily_example()
``` ```
---
#### Cloning loggers
```c++
// clone a logger and give it new name.
// Useful for creating subsystem loggers from some "root" logger
void clone_example()
{
auto network_logger = spdlog::get("root")->clone("network");
network_logger->info("Logging network stuff..");
}
```
--- ---
#### Periodic flush #### Periodic flush
```c++ ```c++
...@@ -166,22 +180,9 @@ spdlog::flush_every(std::chrono::seconds(3)); ...@@ -166,22 +180,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 +202,40 @@ void multi_sink_example() ...@@ -201,6 +202,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 +275,7 @@ void err_handler_example() ...@@ -240,7 +275,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.");
} }
``` ```
......
# *************************************************************************/
# * 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")
...@@ -35,8 +35,8 @@ int main(int argc, char *argv[]) ...@@ -35,8 +35,8 @@ int main(int argc, char *argv[])
int howmany = 1000000; int howmany = 1000000;
int queue_size = howmany + 2; int queue_size = howmany + 2;
int threads = 10; int threads = 10;
int file_size = 30 * 1024 * 1024; size_t file_size = 30 * 1024 * 1024;
int rotating_files = 5; size_t rotating_files = 5;
try try
{ {
...@@ -89,7 +89,7 @@ int main(int argc, char *argv[]) ...@@ -89,7 +89,7 @@ int main(int argc, char *argv[])
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
{ {
spdlog::init_thread_pool(queue_size, 1); spdlog::init_thread_pool(static_cast<size_t>(queue_size), 1);
auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true); auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true);
bench_mt(howmany, as, threads); bench_mt(howmany, as, threads);
spdlog::drop("async"); spdlog::drop("async");
......
...@@ -35,8 +35,8 @@ int main(int, char *[]) ...@@ -35,8 +35,8 @@ int main(int, char *[])
int howmany = 1000000; int howmany = 1000000;
int queue_size = howmany + 2; int queue_size = howmany + 2;
int threads = 10; int threads = 10;
int file_size = 30 * 1024 * 1024; size_t file_size = 30 * 1024 * 1024;
int rotating_files = 5; size_t rotating_files = 5;
try try
{ {
...@@ -82,7 +82,7 @@ int main(int, char *[]) ...@@ -82,7 +82,7 @@ int main(int, char *[])
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
{ {
spdlog::init_thread_pool(queue_size, 1); spdlog::init_thread_pool(static_cast<size_t>(queue_size), 1);
auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true); auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true);
bench_mt(howmany, as, threads); bench_mt(howmany, as, threads);
spdlog::drop("async"); spdlog::drop("async");
......
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()
...@@ -24,10 +24,7 @@ ...@@ -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) ...@@ -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)
CXX ?= g++ CXX ?= g++
CXX_FLAGS = -Wall -Wextra -pedantic -std=c++11 -pthread -I../include -fmax-errors=1 CXX_FLAGS = -Wall -Wextra -pedantic -std=c++11 -pthread -I../include -fmax-errors=1 -Wconversion
CXX_RELEASE_FLAGS = -O3 -march=native CXX_RELEASE_FLAGS = -O3 -march=native
CXX_DEBUG_FLAGS= -g CXX_DEBUG_FLAGS= -g
......
#-Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded
CXX ?= g++
CXX_FLAGS = -Wall -Wextra -pedantic -std=c++11 -pthread -I../include -fmax-errors=1 -Wconversion -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded -Wno-weak-vtables -Wno-global-constructors
CXX_RELEASE_FLAGS = -O3 -march=native
CXX_DEBUG_FLAGS= -g
all: example
debug: example-debug
example: example.cpp
$(CXX) example.cpp -o example $(CXX_FLAGS) $(CXX_RELEASE_FLAGS) $(CXXFLAGS)
example-debug: example.cpp
$(CXX) example.cpp -o example-debug $(CXX_FLAGS) $(CXX_DEBUG_FLAGS) $(CXXFLAGS)
clean:
rm -f *.o logs/*.txt example example-debug
rebuild: clean all
rebuild-debug: clean debug
...@@ -18,6 +18,7 @@ void multi_sink_example(); ...@@ -18,6 +18,7 @@ void multi_sink_example();
void user_defined_example(); void user_defined_example();
void err_handler_example(); void err_handler_example();
void syslog_example(); void syslog_example();
void clone_example();
#include "spdlog/spdlog.h" #include "spdlog/spdlog.h"
...@@ -34,6 +35,8 @@ int main(int, char *[]) ...@@ -34,6 +35,8 @@ int main(int, char *[])
rotating_example(); rotating_example();
daily_example(); daily_example();
clone_example();
// async logging using a backing thread pool // async logging using a backing thread pool
async_example(); async_example();
...@@ -122,6 +125,14 @@ void daily_example() ...@@ -122,6 +125,14 @@ void daily_example()
auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
} }
// clone a logger and give it new name.
// Useful for creating component/subsystem loggers from some "root" logger
void clone_example()
{
auto network_logger = spdlog::get("console")->clone("network");
network_logger->info("Logging network stuff..");
}
#include "spdlog/async.h" #include "spdlog/async.h"
void async_example() void async_example()
{ {
......
#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 *[]) ...@@ -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;
......
...@@ -42,7 +42,7 @@ struct async_factory_impl ...@@ -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)
{ {
......
...@@ -49,12 +49,14 @@ public: ...@@ -49,12 +49,14 @@ 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,
async_overflow_policy overflow_policy = async_overflow_policy::block); async_overflow_policy overflow_policy = async_overflow_policy::block);
std::shared_ptr<logger> clone(std::string new_name) override;
protected: protected:
void sink_it_(details::log_msg &msg) override; void sink_it_(details::log_msg &msg) override;
void flush_() override; void flush_() override;
......
...@@ -100,6 +100,7 @@ inline const char *to_short_c_str(spdlog::level::level_enum l) ...@@ -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 ...@@ -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_;
}; };
// //
...@@ -180,4 +174,17 @@ using filename_t = std::string; ...@@ -180,4 +174,17 @@ using filename_t = std::string;
{ \ { \
err_handler_("Unknown exeption in logger"); \ err_handler_("Unknown exeption in logger"); \
} }
//
// make_unique support
//
#if __cplusplus >= 201402L // C++14 and beyond
using std::make_unique;
#else
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args &&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
#endif
} // namespace spdlog } // namespace spdlog
...@@ -47,7 +47,7 @@ inline void spdlog::async_logger::sink_it_(details::log_msg &msg) ...@@ -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");
} }
} }
...@@ -98,3 +98,13 @@ inline void spdlog::async_logger::backend_flush_() ...@@ -98,3 +98,13 @@ inline void spdlog::async_logger::backend_flush_()
} }
SPDLOG_CATCH_AND_HANDLE SPDLOG_CATCH_AND_HANDLE
} }
inline std::shared_ptr<spdlog::logger> spdlog::async_logger::clone(std::string new_name)
{
auto cloned = std::make_shared<spdlog::async_logger>(std::move(new_name), sinks_.begin(), sinks_.end(), thread_pool_, overflow_policy_);
cloned->set_level(this->level());
cloned->flush_on(this->flush_level());
cloned->set_error_handler(this->error_handler());
return std::move(cloned);
}
...@@ -6,6 +6,8 @@ ...@@ -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: ...@@ -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: ...@@ -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
...@@ -5,14 +5,27 @@ ...@@ -5,14 +5,27 @@
// //
#include "spdlog/details/null_mutex.h" #include "spdlog/details/null_mutex.h"
#include "stdio.h" #include <cstdio>
#include <mutex> #include <mutex>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX // prevent windows redefining min/max
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif
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 +39,7 @@ struct console_stdout ...@@ -26,7 +39,7 @@ struct console_stdout
struct console_stderr struct console_stderr
{ {
static FILE *stream() static std::FILE *stream()
{ {
return stderr; return stderr;
} }
......
...@@ -5,13 +5,12 @@ ...@@ -5,13 +5,12 @@
#pragma once #pragma once
// Helper class for file sink // Helper class for file sinks.
// When failing to open a file, retry several times(5) with small delay between // When failing to open a file, retry several times(5) with a delay interval(10 ms).
// the tries(10 ms) // Throw spdlog_ex exception on errors.
// Throw spdlog_ex exception on errors
#include "../details/log_msg.h" #include "spdlog/details/log_msg.h"
#include "../details/os.h" #include "spdlog/details/os.h"
#include <cerrno> #include <cerrno>
#include <chrono> #include <chrono>
...@@ -136,7 +135,7 @@ public: ...@@ -136,7 +135,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());
} }
...@@ -146,7 +145,7 @@ public: ...@@ -146,7 +145,7 @@ public:
} }
private: private:
FILE *fd_{nullptr}; std::FILE *fd_{nullptr};
filename_t _filename; filename_t _filename;
}; };
} // namespace details } // namespace details
......
...@@ -22,12 +22,8 @@ inline void append_str(const std::string &str, fmt::basic_memory_buffer<char, Bu ...@@ -22,12 +22,8 @@ inline void append_str(const std::string &str, fmt::basic_memory_buffer<char, Bu
template<size_t Buffer_Size> template<size_t Buffer_Size>
inline void append_c_str(const char *c_str, fmt::basic_memory_buffer<char, Buffer_Size> &dest) inline void append_c_str(const char *c_str, fmt::basic_memory_buffer<char, Buffer_Size> &dest)
{ {
char ch; auto len = std::char_traits<char>::length(c_str);
while ((ch = *c_str) != '\0') dest.append(c_str, c_str + len);
{
dest.push_back(ch);
++c_str;
}
} }
template<size_t Buffer_Size1, size_t Buffer_Size2> template<size_t Buffer_Size1, size_t Buffer_Size2>
...@@ -54,14 +50,14 @@ inline void pad2(int n, fmt::basic_memory_buffer<char, Buffer_Size> &dest) ...@@ -54,14 +50,14 @@ inline void pad2(int n, fmt::basic_memory_buffer<char, Buffer_Size> &dest)
} }
if (n > 9) // 10-99 if (n > 9) // 10-99
{ {
dest.push_back('0' + static_cast<char>(n / 10)); dest.push_back(static_cast<char>('0' + n / 10));
dest.push_back('0' + static_cast<char>(n % 10)); dest.push_back(static_cast<char>('0' + n % 10));
return; return;
} }
if (n >= 0) // 0-9 if (n >= 0) // 0-9
{ {
dest.push_back('0'); dest.push_back('0');
dest.push_back('0' + static_cast<char>(n)); dest.push_back(static_cast<char>('0' + n));
return; return;
} }
// negatives (unlikely, but just in case, let fmt deal with it) // negatives (unlikely, but just in case, let fmt deal with it)
...@@ -86,15 +82,15 @@ inline void pad3(int n, fmt::basic_memory_buffer<char, Buffer_Size> &dest) ...@@ -86,15 +82,15 @@ inline void pad3(int n, fmt::basic_memory_buffer<char, Buffer_Size> &dest)
if (n > 9) // 10-99 if (n > 9) // 10-99
{ {
dest.push_back('0'); dest.push_back('0');
dest.push_back('0' + static_cast<char>(n / 10)); dest.push_back(static_cast<char>('0' + n / 10));
dest.push_back('0' + static_cast<char>(n % 10)); dest.push_back(static_cast<char>('0' + n % 10));
return; return;
} }
if (n >= 0) if (n >= 0)
{ {
dest.push_back('0'); dest.push_back('0');
dest.push_back('0'); dest.push_back('0');
dest.push_back('0' + static_cast<char>(n)); dest.push_back(static_cast<char>('0' + n));
return; return;
} }
// negatives (unlikely, but just in case let fmt deal with it) // negatives (unlikely, but just in case let fmt deal with it)
......
...@@ -16,17 +16,18 @@ namespace details { ...@@ -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;
......
...@@ -5,6 +5,8 @@ ...@@ -5,6 +5,8 @@
#pragma once #pragma once
#include "spdlog/details/fmt_helper.h"
#include <memory> #include <memory>
#include <string> #include <string>
...@@ -77,7 +79,7 @@ inline void spdlog::logger::log(level::level_enum lvl, const char *msg) ...@@ -77,7 +79,7 @@ inline void spdlog::logger::log(level::level_enum lvl, const char *msg)
try try
{ {
details::log_msg log_msg(&name_, lvl); details::log_msg log_msg(&name_, lvl);
fmt::format_to(log_msg.raw, "{}", msg); details::fmt_helper::append_c_str(msg, log_msg.raw);
sink_it_(log_msg); sink_it_(log_msg);
} }
SPDLOG_CATCH_AND_HANDLE SPDLOG_CATCH_AND_HANDLE
...@@ -268,6 +270,11 @@ inline void spdlog::logger::flush_on(level::level_enum log_level) ...@@ -268,6 +270,11 @@ inline void spdlog::logger::flush_on(level::level_enum log_level)
flush_level_.store(log_level); flush_level_.store(log_level);
} }
inline spdlog::level::level_enum spdlog::logger::flush_level() const
{
return static_cast<spdlog::level::level_enum>(flush_level_.load(std::memory_order_relaxed));
}
inline bool spdlog::logger::should_flush_(const details::log_msg &msg) inline bool spdlog::logger::should_flush_(const details::log_msg &msg)
{ {
auto flush_level = flush_level_.load(std::memory_order_relaxed); auto flush_level = flush_level_.load(std::memory_order_relaxed);
...@@ -343,3 +350,12 @@ inline std::vector<spdlog::sink_ptr> &spdlog::logger::sinks() ...@@ -343,3 +350,12 @@ inline std::vector<spdlog::sink_ptr> &spdlog::logger::sinks()
{ {
return sinks_; return sinks_;
} }
inline std::shared_ptr<spdlog::logger> spdlog::logger::clone(std::string logger_name)
{
auto cloned = std::make_shared<spdlog::logger>(std::move(logger_name), sinks_.begin(), sinks_.end());
cloned->set_level(this->level());
cloned->flush_on(this->flush_level());
cloned->set_error_handler(this->error_handler());
return cloned;
}
...@@ -105,6 +105,12 @@ public: ...@@ -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_;
......
...@@ -159,9 +159,9 @@ inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mod ...@@ -159,9 +159,9 @@ inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mod
{ {
#ifdef _WIN32 #ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES #ifdef SPDLOG_WCHAR_FILENAMES
*fp = _wfsopen((filename.c_str()), mode.c_str(), _SH_DENYWR); *fp = _wfsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
#else #else
*fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYWR); *fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
#endif #endif
#else // unix #else // unix
*fp = fopen((filename.c_str()), mode.c_str()); *fp = fopen((filename.c_str()), mode.c_str());
......
...@@ -69,7 +69,7 @@ static const char *ampm(const tm &t) ...@@ -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 ...@@ -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,9 +545,9 @@ public: ...@@ -545,9 +545,9 @@ 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 spdlog::make_unique<pattern_formatter>(pattern_, pattern_time_type_, eol_);
} }
void format(const details::log_msg &msg, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, fmt::memory_buffer &dest) override
...@@ -592,141 +592,141 @@ private: ...@@ -592,141 +592,141 @@ private:
{ {
// logger name // logger name
case 'n': case 'n':
formatters_.emplace_back(new details::name_formatter()); formatters_.push_back(spdlog::make_unique<details::name_formatter>());
break; break;
case 'l': case 'l':
formatters_.emplace_back(new details::level_formatter()); formatters_.push_back(spdlog::make_unique<details::level_formatter>());
break; break;
case 'L': case 'L':
formatters_.emplace_back(new details::short_level_formatter()); formatters_.push_back(spdlog::make_unique<details::short_level_formatter>());
break; break;
case ('t'): case ('t'):
formatters_.emplace_back(new details::t_formatter()); formatters_.push_back(spdlog::make_unique<details::t_formatter>());
break; break;
case ('v'): case ('v'):
formatters_.emplace_back(new details::v_formatter()); formatters_.push_back(spdlog::make_unique<details::v_formatter>());
break; break;
case ('a'): case ('a'):
formatters_.emplace_back(new details::a_formatter()); formatters_.push_back(spdlog::make_unique<details::a_formatter>());
break; break;
case ('A'): case ('A'):
formatters_.emplace_back(new details::A_formatter()); formatters_.push_back(spdlog::make_unique<details::A_formatter>());
break; break;
case ('b'): case ('b'):
case ('h'): case ('h'):
formatters_.emplace_back(new details::b_formatter()); formatters_.push_back(spdlog::make_unique<details::b_formatter>());
break; break;
case ('B'): case ('B'):
formatters_.emplace_back(new details::B_formatter()); formatters_.push_back(spdlog::make_unique<details::B_formatter>());
break; break;
case ('c'): case ('c'):
formatters_.emplace_back(new details::c_formatter()); formatters_.push_back(spdlog::make_unique<details::c_formatter>());
break; break;
case ('C'): case ('C'):
formatters_.emplace_back(new details::C_formatter()); formatters_.push_back(spdlog::make_unique<details::C_formatter>());
break; break;
case ('Y'): case ('Y'):
formatters_.emplace_back(new details::Y_formatter()); formatters_.push_back(spdlog::make_unique<details::Y_formatter>());
break; break;
case ('D'): case ('D'):
case ('x'): case ('x'):
formatters_.emplace_back(new details::D_formatter()); formatters_.push_back(spdlog::make_unique<details::D_formatter>());
break; break;
case ('m'): case ('m'):
formatters_.emplace_back(new details::m_formatter()); formatters_.push_back(spdlog::make_unique<details::m_formatter>());
break; break;
case ('d'): case ('d'):
formatters_.emplace_back(new details::d_formatter()); formatters_.push_back(spdlog::make_unique<details::d_formatter>());
break; break;
case ('H'): case ('H'):
formatters_.emplace_back(new details::H_formatter()); formatters_.push_back(spdlog::make_unique<details::H_formatter>());
break; break;
case ('I'): case ('I'):
formatters_.emplace_back(new details::I_formatter()); formatters_.push_back(spdlog::make_unique<details::I_formatter>());
break; break;
case ('M'): case ('M'):
formatters_.emplace_back(new details::M_formatter()); formatters_.push_back(spdlog::make_unique<details::M_formatter>());
break; break;
case ('S'): case ('S'):
formatters_.emplace_back(new details::S_formatter()); formatters_.push_back(spdlog::make_unique<details::S_formatter>());
break; break;
case ('e'): case ('e'):
formatters_.emplace_back(new details::e_formatter()); formatters_.push_back(spdlog::make_unique<details::e_formatter>());
break; break;
case ('f'): case ('f'):
formatters_.emplace_back(new details::f_formatter()); formatters_.push_back(spdlog::make_unique<details::f_formatter>());
break; break;
case ('F'): case ('F'):
formatters_.emplace_back(new details::F_formatter()); formatters_.push_back(spdlog::make_unique<details::F_formatter>());
break; break;
case ('E'): case ('E'):
formatters_.emplace_back(new details::E_formatter()); formatters_.push_back(spdlog::make_unique<details::E_formatter>());
break; break;
case ('p'): case ('p'):
formatters_.emplace_back(new details::p_formatter()); formatters_.push_back(spdlog::make_unique<details::p_formatter>());
break; break;
case ('r'): case ('r'):
formatters_.emplace_back(new details::r_formatter()); formatters_.push_back(spdlog::make_unique<details::r_formatter>());
break; break;
case ('R'): case ('R'):
formatters_.emplace_back(new details::R_formatter()); formatters_.push_back(spdlog::make_unique<details::R_formatter>());
break; break;
case ('T'): case ('T'):
case ('X'): case ('X'):
formatters_.emplace_back(new details::T_formatter()); formatters_.push_back(spdlog::make_unique<details::T_formatter>());
break; break;
case ('z'): case ('z'):
formatters_.emplace_back(new details::z_formatter()); formatters_.push_back(spdlog::make_unique<details::z_formatter>());
break; break;
case ('+'): case ('+'):
formatters_.emplace_back(new details::full_formatter()); formatters_.push_back(spdlog::make_unique<details::full_formatter>());
break; break;
case ('P'): case ('P'):
formatters_.emplace_back(new details::pid_formatter()); formatters_.push_back(spdlog::make_unique<details::pid_formatter>());
break; break;
case ('i'): case ('i'):
formatters_.emplace_back(new details::i_formatter()); formatters_.push_back(spdlog::make_unique<details::i_formatter>());
break; break;
case ('^'): case ('^'):
formatters_.emplace_back(new details::color_start_formatter()); formatters_.push_back(spdlog::make_unique<details::color_start_formatter>());
break; break;
case ('$'): case ('$'):
formatters_.emplace_back(new details::color_stop_formatter()); formatters_.push_back(spdlog::make_unique<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(spdlog::make_unique<details::ch_formatter>('%'));
formatters_.emplace_back(new details::ch_formatter(flag)); formatters_.push_back(spdlog::make_unique<details::ch_formatter>(flag));
break; break;
} }
} }
...@@ -744,7 +744,6 @@ private: ...@@ -744,7 +744,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);
...@@ -758,7 +757,7 @@ private: ...@@ -758,7 +757,7 @@ private:
{ {
if (!user_chars) if (!user_chars)
{ {
user_chars = std::unique_ptr<details::aggregate_formatter>(new details::aggregate_formatter()); user_chars = spdlog::make_unique<details::aggregate_formatter>();
} }
user_chars->add_ch(*it); user_chars->add_ch(*it);
} }
......
...@@ -23,7 +23,7 @@ namespace details { ...@@ -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_)
......
...@@ -35,7 +35,7 @@ public: ...@@ -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: ...@@ -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,8 +112,8 @@ public: ...@@ -112,8 +112,8 @@ 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_ = spdlog::make_unique<periodic_worker>(clbk, interval);
} }
void set_error_handler(log_err_handler handler) void set_error_handler(log_err_handler handler)
...@@ -126,7 +126,7 @@ public: ...@@ -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: ...@@ -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)
{ {
......
...@@ -64,8 +64,8 @@ struct async_msg ...@@ -64,8 +64,8 @@ struct async_msg
return *this; return *this;
} }
#else // (_MSC_VER) && _MSC_VER <= 1800 #else // (_MSC_VER) && _MSC_VER <= 1800
async_msg(async_msg &&other) = default; async_msg(async_msg &&) = default;
async_msg &operator=(async_msg &&other) = default; async_msg &operator=(async_msg &&) = default;
#endif #endif
// construct from log_msg with given type // construct from log_msg with given type
...@@ -122,7 +122,7 @@ public: ...@@ -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: ...@@ -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_;
...@@ -193,6 +198,13 @@ private: ...@@ -193,6 +198,13 @@ private:
switch (incoming_async_msg.msg_type) switch (incoming_async_msg.msg_type)
{ {
case async_msg_type::log:
{
log_msg msg;
incoming_async_msg.to_log_msg(msg);
incoming_async_msg.worker_ptr->backend_log_(msg);
return true;
}
case async_msg_type::flush: case async_msg_type::flush:
{ {
incoming_async_msg.worker_ptr->backend_flush_(); incoming_async_msg.worker_ptr->backend_flush_();
...@@ -203,16 +215,9 @@ private: ...@@ -203,16 +215,9 @@ private:
{ {
return false; return false;
} }
default:
{
log_msg msg;
incoming_async_msg.to_log_msg(msg);
incoming_async_msg.worker_ptr->backend_log_(msg);
return true;
} }
} assert(false && "Unexpected async_msg_type");
return true; // should not be reached return true;
} }
}; };
......
...@@ -120,16 +120,22 @@ public: ...@@ -120,16 +120,22 @@ public:
void set_formatter(std::unique_ptr<formatter> formatter); void set_formatter(std::unique_ptr<formatter> formatter);
void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local); void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local);
// flush functions
void flush(); void flush();
void flush_on(level::level_enum log_level); void flush_on(level::level_enum log_level);
level::level_enum flush_level() const;
// sinks
const std::vector<sink_ptr> &sinks() const; const std::vector<sink_ptr> &sinks() const;
std::vector<sink_ptr> &sinks(); std::vector<sink_ptr> &sinks();
// error handler
void set_error_handler(log_err_handler err_handler); void set_error_handler(log_err_handler err_handler);
log_err_handler error_handler(); log_err_handler error_handler();
// create new logger with same sinks and configuration.
virtual std::shared_ptr<logger> clone(std::string logger_name);
protected: protected:
virtual void sink_it_(details::log_msg &msg); virtual void sink_it_(details::log_msg &msg);
virtual void flush_(); virtual void flush_();
......
...@@ -30,8 +30,8 @@ template<typename Mutex> ...@@ -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: ...@@ -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();
......
...@@ -24,7 +24,7 @@ namespace sinks { ...@@ -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: ...@@ -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: ...@@ -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);
......
...@@ -30,7 +30,7 @@ public: ...@@ -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);
......
...@@ -40,6 +40,12 @@ public: ...@@ -40,6 +40,12 @@ public:
sinks_.erase(std::remove(sinks_.begin(), sinks_.end(), sink), sinks_.end()); sinks_.erase(std::remove(sinks_.begin(), sinks_.end(), sink), sinks_.end());
} }
void set_sinks(std::vector<std::shared_ptr<sink>> sinks)
{
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
sinks_ = std::move(sinks);
}
protected: protected:
void sink_it_(const details::log_msg &msg) override void sink_it_(const details::log_msg &msg) override
{ {
......
...@@ -30,7 +30,7 @@ protected: ...@@ -30,7 +30,7 @@ protected:
{ {
fmt::memory_buffer formatted; fmt::memory_buffer formatted;
sink::formatter_->format(msg, formatted); sink::formatter_->format(msg, formatted);
ostream_.write(formatted.data(), formatted.size()); ostream_.write(formatted.data(), static_cast<std::streamsize>(formatted.size()));
if (force_flush_) if (force_flush_)
ostream_.flush(); ostream_.flush();
} }
......
...@@ -20,9 +20,11 @@ public: ...@@ -20,9 +20,11 @@ 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))
{
}
virtual ~sink() = default; virtual ~sink() = default;
virtual void log(const details::log_msg &msg) = 0; virtual void log(const details::log_msg &msg) = 0;
......
...@@ -12,14 +12,13 @@ ...@@ -12,14 +12,13 @@
#include <cstdio> #include <cstdio>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <spdlog/details/console_globals.h>
namespace spdlog { 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 +27,7 @@ public: ...@@ -28,7 +27,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 +47,13 @@ public: ...@@ -48,13 +47,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);
......
...@@ -24,8 +24,8 @@ class syslog_sink : public base_sink<Mutex> ...@@ -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;
......
...@@ -64,7 +64,7 @@ inline void set_formatter(std::unique_ptr<spdlog::formatter> formatter) ...@@ -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) ...@@ -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
......
...@@ -6,7 +6,7 @@ ...@@ -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)
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
...@@ -14,11 +14,16 @@ set(SPDLOG_UTESTS_SOURCES ...@@ -14,11 +14,16 @@ set(SPDLOG_UTESTS_SOURCES
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})
CXX ?= g++ CXX ?= g++
CXXFLAGS = -Wall -pedantic -std=c++11 -pthread -O3 -I../include -fmax-errors=1 CXXFLAGS = -Wall -pedantic -std=c++11 -pthread -Wconversion -O3 -I../include -fmax-errors=1
LDPFALGS = -pthread LDPFALGS = -pthread
CPP_FILES := $(wildcard *.cpp) CPP_FILES := $(wildcard *.cpp)
......
...@@ -9,15 +9,15 @@ class failing_sink : public spdlog::sinks::base_sink<std::mutex> ...@@ -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: ...@@ -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";
......
...@@ -33,7 +33,7 @@ TEST_CASE("flush_on", "[flush_on]]") ...@@ -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);
} }
......
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
#include <cstdio> #include <cstdio>
#include <exception> #include <exception>
#include <fstream> #include <fstream>
#include <iostream>
#include <ostream> #include <ostream>
#include <string> #include <string>
......
#!/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
...@@ -9,7 +9,7 @@ TEST_CASE("register_drop", "[registry]") ...@@ -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" ...@@ -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" ...@@ -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;
...@@ -62,7 +62,7 @@ TEST_CASE("drop_all" ...@@ -62,7 +62,7 @@ TEST_CASE("drop_all"
spdlog::create<spdlog::sinks::null_sink_mt>(tested_logger_name2); spdlog::create<spdlog::sinks::null_sink_mt>(tested_logger_name2);
spdlog::drop_all(); spdlog::drop_all();
REQUIRE_FALSE(spdlog::get(tested_logger_name)); REQUIRE_FALSE(spdlog::get(tested_logger_name));
REQUIRE_FALSE(spdlog::get(tested_logger_name)); REQUIRE_FALSE(spdlog::get(tested_logger_name2));
} }
TEST_CASE("drop non existing" TEST_CASE("drop non existing"
......
...@@ -7,6 +7,7 @@ TEST_CASE("basic async test ", "[async]") ...@@ -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]") ...@@ -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]") ...@@ -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();
} }
......
...@@ -91,3 +91,46 @@ TEST_CASE("periodic flush", "[periodic_flush]") ...@@ -91,3 +91,46 @@ TEST_CASE("periodic flush", "[periodic_flush]")
spdlog::flush_every(std::chrono::seconds(0)); spdlog::flush_every(std::chrono::seconds(0));
spdlog::drop_all(); spdlog::drop_all();
} }
TEST_CASE("clone", "[clone]")
{
using namespace spdlog;
auto logger = spdlog::create<sinks::test_sink_mt>("orig");
auto cloned = logger->clone("clone");
REQUIRE(cloned->name() == "clone");
REQUIRE(logger->sinks() == cloned->sinks());
REQUIRE(logger->level() == cloned->level());
REQUIRE(logger->flush_level() == cloned->flush_level());
logger->info("Some message 1");
cloned->info("Some message 2");
auto test_sink = std::static_pointer_cast<sinks::test_sink_mt>(cloned->sinks()[0]);
REQUIRE(test_sink->msg_counter() == 2);
spdlog::drop_all();
}
TEST_CASE("clone async", "[clone]")
{
using namespace spdlog;
auto logger = spdlog::create_async<sinks::test_sink_mt>("orig");
auto cloned = logger->clone("clone");
REQUIRE(cloned->name() == "clone");
REQUIRE(logger->sinks() == cloned->sinks());
REQUIRE(logger->level() == cloned->level());
REQUIRE(logger->flush_level() == cloned->flush_level());
logger->info("Some message 1");
cloned->info("Some message 2");
spdlog::details::os::sleep_for_millis(10);
auto test_sink = std::static_pointer_cast<sinks::test_sink_mt>(cloned->sinks()[0]);
REQUIRE(test_sink->msg_counter() == 2);
spdlog::drop_all();
}
#include "includes.h"
using namespace std::chrono;
using std::chrono::milliseconds;
using test_clock = std::chrono::high_resolution_clock;
static milliseconds millis_from(const test_clock::time_point &tp0)
{
return std::chrono::duration_cast<milliseconds>(test_clock::now() - tp0);
}
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 start = test_clock::now();
auto rv = q.dequeue_for(popped_item, milliseconds::zero());
auto delta_ms = millis_from(start);
REQUIRE(rv == false);
INFO("Delta " << delta_ms.count() << " millis");
REQUIRE(delta_ms <= tolerance_wait);
}
TEST_CASE("dequeue-empty-wait", "[mpmc_blocking_q]")
{
size_t q_size = 100;
milliseconds wait_ms(250);
milliseconds tolerance_wait(100);
spdlog::details::mpmc_blocking_queue<int> q(q_size);
int popped_item;
auto start = test_clock::now();
auto rv = q.dequeue_for(popped_item, wait_ms);
auto delta_ms = millis_from(start);
REQUIRE(rv == false);
INFO("Delta " << delta_ms.count() << " millis");
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 start = test_clock::now();
q.enqueue_nowait(2);
auto delta_ms = millis_from(start);
INFO("Delta " << delta_ms.count() << " millis");
REQUIRE(delta_ms <= 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);
}
\ No newline at end of file
...@@ -21,11 +21,13 @@ class test_sink : public base_sink<Mutex> ...@@ -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_;
} }
......
...@@ -56,7 +56,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sinks", "sinks", "{093AE34A ...@@ -56,7 +56,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sinks", "sinks", "{093AE34A
..\include\spdlog\sinks\ansicolor_sink.h = ..\include\spdlog\sinks\ansicolor_sink.h ..\include\spdlog\sinks\ansicolor_sink.h = ..\include\spdlog\sinks\ansicolor_sink.h
..\include\spdlog\sinks\base_sink.h = ..\include\spdlog\sinks\base_sink.h ..\include\spdlog\sinks\base_sink.h = ..\include\spdlog\sinks\base_sink.h
..\include\spdlog\sinks\dist_sink.h = ..\include\spdlog\sinks\dist_sink.h ..\include\spdlog\sinks\dist_sink.h = ..\include\spdlog\sinks\dist_sink.h
..\include\spdlog\sinks\file_sinks.h = ..\include\spdlog\sinks\file_sinks.h
..\include\spdlog\sinks\msvc_sink.h = ..\include\spdlog\sinks\msvc_sink.h ..\include\spdlog\sinks\msvc_sink.h = ..\include\spdlog\sinks\msvc_sink.h
..\include\spdlog\sinks\null_sink.h = ..\include\spdlog\sinks\null_sink.h ..\include\spdlog\sinks\null_sink.h = ..\include\spdlog\sinks\null_sink.h
..\include\spdlog\sinks\ostream_sink.h = ..\include\spdlog\sinks\ostream_sink.h ..\include\spdlog\sinks\ostream_sink.h = ..\include\spdlog\sinks\ostream_sink.h
...@@ -65,7 +64,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sinks", "sinks", "{093AE34A ...@@ -65,7 +64,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sinks", "sinks", "{093AE34A
..\include\spdlog\sinks\stdout_sinks.h = ..\include\spdlog\sinks\stdout_sinks.h ..\include\spdlog\sinks\stdout_sinks.h = ..\include\spdlog\sinks\stdout_sinks.h
..\include\spdlog\sinks\syslog_sink.h = ..\include\spdlog\sinks\syslog_sink.h ..\include\spdlog\sinks\syslog_sink.h = ..\include\spdlog\sinks\syslog_sink.h
..\include\spdlog\sinks\wincolor_sink.h = ..\include\spdlog\sinks\wincolor_sink.h ..\include\spdlog\sinks\wincolor_sink.h = ..\include\spdlog\sinks\wincolor_sink.h
..\include\spdlog\sinks\windebug_sink.h = ..\include\spdlog\sinks\windebug_sink.h
EndProjectSection EndProjectSection
EndProject EndProject
Global Global
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment