Merge pull request #1089 from gabime/static-lib

Static lib support using -DSPDLOG_COMPILED_LIB
This commit is contained in:
Gabi Melman 2019-05-25 23:14:32 +03:00 committed by GitHub
commit 5709cb10d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
98 changed files with 4068 additions and 4604 deletions

View File

@ -32,9 +32,9 @@ BraceWrapping:
BeforeCatch: true BeforeCatch: true
BeforeElse: true BeforeElse: true
IndentBraces: false IndentBraces: false
SplitEmptyFunction: true SplitEmptyFunction: false
SplitEmptyRecord: true SplitEmptyRecord: false
SplitEmptyNamespace: true SplitEmptyNamespace: false
BreakBeforeBinaryOperators: None BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom BreakBeforeBraces: Custom
BreakBeforeInheritanceComma: false BreakBeforeInheritanceComma: false

View File

@ -1,6 +1,6 @@
Checks: 'modernize-*,modernize-use-override,google-*,-google-runtime-references,misc-*,clang-analyzer-*' Checks: 'modernize-*,modernize-use-override,google-*,-google-runtime-references,misc-*,clang-analyzer-*'
WarningsAsErrors: '' WarningsAsErrors: ''
HeaderFilterRegex: 'async.h|async_logger.h|common.h|details|formatter.h|logger.h|sinks|spdlog.h|tweakme.h|version.h' HeaderFilterRegex: 'async.h|async_logger.h|common.h|details|formatter.h|logger.h|sinks|spdlog.h|tweakme.h|version.h|spdlite.h'
AnalyzeTemporaryDtors: false AnalyzeTemporaryDtors: false
FormatStyle: none FormatStyle: none

1
.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
* text=false

5
.gitignore vendored
View File

@ -1,5 +1,5 @@
# Auto generated files # Auto generated files
build/* build/*
*.slo *.slo
*.lo *.lo
*.o *.o
@ -65,4 +65,5 @@ install_manifest.txt
/tests/logs/* /tests/logs/*
# idea # idea
.idea/ .idea/
cmake-build-*/

View File

@ -46,7 +46,7 @@ matrix:
- env: GCC_VERSION=4.8 BUILD_TYPE=Release CPP=11 - env: GCC_VERSION=4.8 BUILD_TYPE=Release CPP=11
os: linux os: linux
addons: *gcc48 addons: *gcc48
- env: GCC_VERSION=7 BUILD_TYPE=Release CPP=11 - env: GCC_VERSION=7 BUILD_TYPE=Release CPP=11
os: linux os: linux
addons: *gcc7 addons: *gcc7
@ -64,24 +64,15 @@ matrix:
- env: CLANG_VERSION=6.0 BUILD_TYPE=Debug CPP=11 ASAN=On TSAN=Off - env: CLANG_VERSION=6.0 BUILD_TYPE=Debug CPP=11 ASAN=On TSAN=Off
os: linux os: linux
addons: *clang6 addons: *clang6
- env: CLANG_VERSION=6.0 BUILD_TYPE=Release CPP=11 ASAN=On TSAN=Off - env: CLANG_VERSION=6.0 BUILD_TYPE=Release CPP=11 ASAN=On TSAN=Off
os: linux os: linux
addons: *clang6 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
# osx # osx
- env: BUILD_TYPE=Release CPP=11 ASAN=Off TSAN=Off - env: BUILD_TYPE=Release CPP=11 ASAN=Off TSAN=Off
os: osx os: osx

View File

@ -1,7 +1,5 @@
# # Copyright(c) 2019 spdlog authors
# Copyright(c) 2015 Ruslan Baratov.
# Distributed under the MIT License (http://opensource.org/licenses/MIT) # Distributed under the MIT License (http://opensource.org/licenses/MIT)
#
cmake_minimum_required(VERSION 3.1) cmake_minimum_required(VERSION 3.1)
project(spdlog VERSION 1.3.1 LANGUAGES CXX) project(spdlog VERSION 1.3.1 LANGUAGES CXX)
@ -15,8 +13,6 @@ if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE) set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE)
endif() endif()
message(STATUS "Build type: " ${CMAKE_BUILD_TYPE})
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
# compiler config # compiler config
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
@ -24,61 +20,83 @@ set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_EXTENSIONS OFF)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
add_compile_options("-Wall")
add_compile_options("-Wextra")
add_compile_options("-Wconversion")
add_compile_options("-pedantic")
add_compile_options("-Wfatal-errors")
endif()
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
# address sanitizers check # Set SPDLOG_MASTER_PROJECT to ON if we are building spdlog
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
include(cmake/sanitizers.cmake) # Check if spdlog is being used directly or via add_subdirectory, but allow overriding
if (NOT DEFINED SPDLOG_MASTER_PROJECT)
#--------------------------------------------------------------------------------------- if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
# spdlog target set(SPDLOG_MASTER_PROJECT ON)
#---------------------------------------------------------------------------------------
add_library(spdlog INTERFACE)
add_library(spdlog::spdlog ALIAS spdlog)
# Check if spdlog is being used directly or via add_subdirectory
set(SPDLOG_MASTER_PROJECT OFF)
if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
set(SPDLOG_MASTER_PROJECT ON)
endif()
option(SPDLOG_BUILD_EXAMPLES "Build examples" ${SPDLOG_MASTER_PROJECT})
option(SPDLOG_BUILD_BENCH "Build benchmarks (Requires https://github.com/google/benchmark.git to be installed)" OFF)
option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT})
option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF)
option(SPDLOG_FMT_HEADER_ONLY "Use header-only variant of external fmt library" ON)
option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT})
target_include_directories(
spdlog
INTERFACE
"$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>"
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
)
if(SPDLOG_FMT_EXTERNAL)
target_compile_definitions(spdlog INTERFACE SPDLOG_FMT_EXTERNAL)
if(NOT TARGET fmt::fmt)
find_package(fmt REQUIRED CONFIG)
endif()
if(SPDLOG_FMT_HEADER_ONLY)
target_link_libraries(spdlog INTERFACE fmt::fmt-header-only)
else() else()
target_link_libraries(spdlog INTERFACE fmt::fmt) set(SPDLOG_MASTER_PROJECT OFF)
endif() endif()
endif ()
option(SPDLOG_BUILD_EXAMPLES "Build examples" ON)
option(SPDLOG_BUILD_BENCH "Build benchmarks (Requires https://github.com/google/benchmark.git to be installed)" OFF)
option(SPDLOG_BUILD_TESTS "Build tests" OFF)
option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT})
option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF)
message(STATUS "Build type: " ${CMAKE_BUILD_TYPE})
find_package(Threads REQUIRED)
#---------------------------------------------------------------------------------------
# Static library version
#---------------------------------------------------------------------------------------
add_library(spdlog STATIC src/spdlog.cpp)
target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB)
target_include_directories(spdlog PUBLIC
"$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>"
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>")
target_link_libraries(spdlog PUBLIC Threads::Threads)
#---------------------------------------------------------------------------------------
# Header only version
#---------------------------------------------------------------------------------------
add_library(spdlog_header_only INTERFACE)
target_include_directories(spdlog_header_only INTERFACE
"$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>"
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>")
target_link_libraries(spdlog_header_only INTERFACE Threads::Threads)
#---------------------------------------------------------------------------------------
# Turn on compiler warnings and sanitizers if we build our own project
#---------------------------------------------------------------------------------------
if(SPDLOG_MASTER_PROJECT)
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|AppleClang")
target_compile_options( spdlog PUBLIC -Wall -Wextra -Wconversion -pedantic -Wfatal-errors)
target_compile_options( spdlog_header_only INTERFACE -Wall -Wextra -Wconversion -pedantic -Wfatal-errors)
endif()
if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
target_compile_options( spdlog PUBLIC /W3 /WX )
target_compile_options( spdlog_header_only INTERFACE /W3 /WX)
endif()
include(cmake/sanitizers.cmake)
endif() endif()
set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include") #---------------------------------------------------------------------------------------
# use fmt package if using exertnal fmt
#---------------------------------------------------------------------------------------
if(SPDLOG_FMT_EXTERNAL)
if (NOT TARGET fmt::fmt)
find_package(fmt REQUIRED)
endif ()
target_compile_definitions(spdlog PUBLIC SPDLOG_FMT_EXTERNAL)
target_link_libraries(spdlog PUBLIC fmt::fmt)
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_FMT_EXTERNAL)
target_link_libraries(spdlog_header_only INTERFACE fmt::fmt)
endif()
#---------------------------------------------------------------------------------------
# build binries
#---------------------------------------------------------------------------------------
if(SPDLOG_BUILD_EXAMPLES) if(SPDLOG_BUILD_EXAMPLES)
add_subdirectory(example) add_subdirectory(example)
endif() endif()
@ -93,74 +111,40 @@ if(SPDLOG_BUILD_BENCH)
endif() endif()
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
# Install/export targets and files # install
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
if(SPDLOG_INSTALL) if (SPDLOG_INSTALL)
# set files and directories set(project_config_in "${CMAKE_CURRENT_LIST_DIR}/cmake/spdlogConfig.cmake.in")
set(config_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") set(project_config_out "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfig.cmake")
set(include_install_dir "${CMAKE_INSTALL_INCLUDEDIR}") set(config_targets_file "spdlogConfigTargets.cmake")
set(pkgconfig_install_dir "${CMAKE_INSTALL_LIBDIR}/pkgconfig") set(version_config_file "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfigVersion.cmake")
set(version_config "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake") set(export_dest_dir "${CMAKE_INSTALL_LIBDIR}/spdlog/cmake")
set(project_config "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake")
set(targets_config "${PROJECT_NAME}Targets.cmake") #---------------------------------------------------------------------------------------
set(pkg_config "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc") # include files
set(targets_export_name "${PROJECT_NAME}Targets") #---------------------------------------------------------------------------------------
set(namespace "${PROJECT_NAME}::") install(DIRECTORY include/ DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
install(TARGETS spdlog spdlog_header_only EXPORT spdlog DESTINATION "${CMAKE_INSTALL_LIBDIR}/spdlog")
#---------------------------------------------------------------------------------------
# package and version files
#---------------------------------------------------------------------------------------
install(EXPORT spdlog
DESTINATION ${export_dest_dir}
NAMESPACE spdlog::
FILE ${config_targets_file})
# generate package version file
include(CMakePackageConfigHelpers) include(CMakePackageConfigHelpers)
write_basic_package_version_file( configure_file("${project_config_in}" "${project_config_out}" @ONLY)
"${version_config}" COMPATIBILITY SameMajorVersion write_basic_package_version_file("${version_config_file}" COMPATIBILITY SameMajorVersion)
) install(FILES
"${project_config_out}"
"${version_config_file}" DESTINATION "${export_dest_dir}")
# configure pkg config file #---------------------------------------------------------------------------------------
configure_file("cmake/spdlog.pc.in" "${pkg_config}" @ONLY) # Support creation of installable packages
# configure spdlogConfig.cmake file #---------------------------------------------------------------------------------------
configure_file("cmake/Config.cmake.in" "${project_config}" @ONLY) include(cmake/SpdlogCPack.cmake)
# install targets endif ()
install(
TARGETS spdlog
EXPORT "${targets_export_name}"
)
# install headers
install(
DIRECTORY "${HEADER_BASE}/${PROJECT_NAME}"
DESTINATION "${include_install_dir}"
)
# install project config and version file
install(
FILES "${project_config}" "${version_config}"
DESTINATION "${config_install_dir}"
)
# install pkg config file
install(
FILES "${pkg_config}"
DESTINATION "${pkgconfig_install_dir}"
)
# install targets config file
install(
EXPORT "${targets_export_name}"
NAMESPACE "${namespace}"
DESTINATION "${config_install_dir}"
FILE ${targets_config}
)
# export build directory targets file
export(
EXPORT ${targets_export_name}
NAMESPACE "${namespace}"
FILE ${targets_config}
)
# register project in CMake user registry
export(PACKAGE ${PROJECT_NAME})
endif()
file(GLOB_RECURSE spdlog_include_SRCS "${HEADER_BASE}/*.h")
add_custom_target(spdlog_headers_for_ide SOURCES ${spdlog_include_SRCS})

View File

@ -26,7 +26,7 @@ build_script:
set PATH=C:\mingw-w64\i686-5.3.0-posix-dwarf-rt_v4-rev0\mingw32\bin;%PATH% set PATH=C:\mingw-w64\i686-5.3.0-posix-dwarf-rt_v4-rev0\mingw32\bin;%PATH%
cmake .. -G %GENERATOR% -DCMAKE_BUILD_TYPE=%BUILD_TYPE% -DSPDLOG_BUILD_BENCH=OFF cmake .. -G %GENERATOR% -DCMAKE_BUILD_TYPE=%BUILD_TYPE% -DSPDLOG_BUILD_EXAMPLES=ON -DSPDLOG_BUILD_TESTS=ON
cmake --build . --config %BUILD_TYPE% cmake --build . --config %BUILD_TYPE%

View File

@ -1,25 +1,5 @@
# *************************************************************************/ # Copyright(c) 2019 spdlog authors
# * Copyright (c) 2015 Ruslan Baratov. */ # Distributed under the MIT License (http://opensource.org/licenses/MIT)
# * */
# * 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) cmake_minimum_required(VERSION 3.1)
project(SpdlogBench CXX) project(SpdlogBench CXX)
@ -33,16 +13,16 @@ find_package(Threads REQUIRED)
find_package(benchmark CONFIG REQUIRED) find_package(benchmark CONFIG REQUIRED)
add_executable(bench bench.cpp) add_executable(bench bench.cpp)
target_link_libraries(bench PRIVATE spdlog::spdlog Threads::Threads) target_link_libraries(bench PRIVATE spdlog::spdlog)
add_executable(async_bench async_bench.cpp) add_executable(async_bench async_bench.cpp)
target_link_libraries(async_bench PRIVATE spdlog::spdlog Threads::Threads) target_link_libraries(async_bench PRIVATE spdlog::spdlog)
add_executable(latency latency.cpp) add_executable(latency latency.cpp)
target_link_libraries(latency PRIVATE benchmark::benchmark spdlog::spdlog Threads::Threads) target_link_libraries(latency PRIVATE benchmark::benchmark spdlog::spdlog)
add_executable(formatter-bench formatter-bench.cpp) add_executable(formatter-bench formatter-bench.cpp)
target_link_libraries(formatter-bench PRIVATE benchmark::benchmark spdlog::spdlog Threads::Threads) target_link_libraries(formatter-bench PRIVATE benchmark::benchmark spdlog::spdlog)
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs")

View File

@ -1,31 +0,0 @@
CXX ?= g++
CXXFLAGS = -march=native -Wall -Wextra -pedantic -Wconversion -std=c++11 -pthread -I../include -fmax-errors=1
CXX_RELEASE_FLAGS = -O3 -flto -Wl,--no-as-needed
binaries=bench async_bench latency formatter-bench
all: $(binaries)
bench: bench.cpp
$(CXX) bench.cpp -o bench $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
async_bench: async_bench.cpp
$(CXX) async_bench.cpp -o async_bench $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
latency: latency.cpp
$(CXX) latency.cpp -o latency $(CXXFLAGS) $(CXX_RELEASE_FLAGS) -lbenchmark
formatter-bench: formatter-bench.cpp
$(CXX) formatter-bench.cpp -o formatter-bench $(CXXFLAGS) $(CXX_RELEASE_FLAGS) -lbenchmark
.PHONY: clean
clean:
rm -f *.o logs/* latecy_logs $(binaries)
rebuild: clean all

View File

@ -8,19 +8,6 @@
#include "spdlog/spdlog.h" #include "spdlog/spdlog.h"
#include "spdlog/details/pattern_formatter.h" #include "spdlog/details/pattern_formatter.h"
void bench_scoped_pad(benchmark::State &state, size_t wrapped_size, spdlog::details::padding_info padinfo)
{
fmt::memory_buffer dest;
for (auto _ : state)
{
{
spdlog::details::scoped_pad p(wrapped_size, padinfo, dest);
benchmark::DoNotOptimize(p);
dest.clear();
}
}
}
void bench_formatter(benchmark::State &state, std::string pattern) void bench_formatter(benchmark::State &state, std::string pattern)
{ {
auto formatter = spdlog::details::make_unique<spdlog::pattern_formatter>(pattern); auto formatter = spdlog::details::make_unique<spdlog::pattern_formatter>(pattern);

View File

@ -1,2 +1,2 @@
#!/bin/bash #!/bin/bash
clang-tidy example/example.cpp -- -I ./include clang-tidy example/example.cpp -- -I ./include

View File

@ -1,31 +0,0 @@
# *************************************************************************/
# * 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. */
# *************************************************************************/
set(SPDLOG_FMT_EXTERNAL @SPDLOG_FMT_EXTERNAL@)
include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake")
if(SPDLOG_FMT_EXTERNAL)
include(CMakeFindDependencyMacro)
find_dependency(fmt CONFIG)
endif()

26
cmake/SpdlogCPack.cmake Normal file
View File

@ -0,0 +1,26 @@
set(CPACK_GENERATOR
TGZ
ZIP
)
set(CPACK_INCLUDE_TOPLEVEL_DIRECTORY 0)
set(CPACK_INSTALL_CMAKE_PROJECTS
"${CMAKE_BINARY_DIR}"
"${PROJECT_NAME}"
ALL
.
)
set(CPACK_PROJECT_URL "https://github.com/gabime/spdlog")
set(CPACK_PACKAGE_VENDOR "Gabi Melman")
set(CPACK_PACKAGE_CONTACT "Gabi Melman <gmelman1@gmail.com>")
set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR})
set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR})
set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH})
set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH})
if (PROJECT_VERSION_TWEAK)
set(CPACK_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION}.${PROJECT_VERSION_TWEAK})
endif ()
set(CPACK_PACKAGE_RELOCATABLE ON)
include(CPack)

View File

@ -1,6 +0,0 @@
prefix=@CMAKE_INSTALL_PREFIX@
includedir=${prefix}/include
Name: @PROJECT_NAME@
Description: Super fast C++ logging library.
Version: @PROJECT_VERSION@

View File

@ -0,0 +1,15 @@
# Copyright(c) 2019 spdlog authors
# Distributed under the MIT License (http://opensource.org/licenses/MIT)
find_package(Threads REQUIRED)
set(SPDLOG_FMT_EXTERNAL @SPDLOG_FMT_EXTERNAL@)
set(config_targets_file @config_targets_file@)
if(SPDLOG_FMT_EXTERNAL)
include(CMakeFindDependencyMacro)
find_dependency(fmt CONFIG)
endif()
include("${CMAKE_CURRENT_LIST_DIR}/${config_targets_file}")

View File

@ -1,49 +1,31 @@
# *************************************************************************/ # Copyright(c) 2019 spdlog authors
# * Copyright (c) 2015 Ruslan Baratov. */ # Distributed under the MIT License (http://opensource.org/licenses/MIT)
# * */
# * 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) cmake_minimum_required(VERSION 3.1)
project(SpdlogExamples CXX) project(SpdlogExamples CXX)
if(NOT TARGET spdlog) if(TARGET spdlog)
# Stand-alone build # If we're running this example as part of the primary spdlog applciation
find_package(spdlog CONFIG REQUIRED) # then add an alias. This allows us to use the same "spdlog::spdlog"
endif() # below that a user would use (with the namespace)
add_library(spdlog::spdlog ALIAS spdlog)
find_package(Threads REQUIRED) add_library(spdlog::spdlog_header_only ALIAS spdlog_header_only)
add_executable(example example.cpp)
if(CMAKE_SYSTEM_NAME STREQUAL "Android")
find_library(log-lib log)
target_link_libraries(example spdlog::spdlog Threads::Threads log)
else() else()
target_link_libraries(example spdlog::spdlog Threads::Threads) # Stand-alone build
find_package(spdlog REQUIRED)
endif() endif()
#---------------------------------------------------------------------------------------
# Example of using pre-compiled library
#---------------------------------------------------------------------------------------
add_executable(example example.cpp)
target_link_libraries(example spdlog::spdlog)
add_executable(multisink multisink.cpp) #---------------------------------------------------------------------------------------
target_link_libraries(multisink spdlog::spdlog Threads::Threads) # Example of using header-only library
#---------------------------------------------------------------------------------------
add_executable(example_header_only example.cpp)
target_link_libraries(example_header_only spdlog::spdlog_header_only)
# Create logs directory
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs")
enable_testing()
add_test(NAME example COMMAND example)

View File

@ -1,21 +0,0 @@
CXX ?= g++
CXX_FLAGS = -Wall -Wextra -pedantic -std=c++11 -pthread -I../include -fmax-errors=1 -Wconversion
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

View File

@ -1,22 +0,0 @@
#-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

View File

@ -1,26 +0,0 @@
CXX = clang++
CXXFLAGS = -march=native -Wall -Wextra -Wshadow -pedantic -std=c++11 -pthread -I../include
CXX_RELEASE_FLAGS = -O2
CXX_DEBUG_FLAGS= -g
all: example
debug: example-debug
example: example.cpp
$(CXX) example.cpp -o example-clang $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
example-debug: example.cpp
$(CXX) example.cpp -o example-clang-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS)
clean:
rm -f *.o logs/*.txt example-clang example-clang-debug
rebuild: clean all
rebuild-debug: clean debug

View File

@ -1,25 +0,0 @@
CXX ?= g++
CXXFLAGS = -D_WIN32_WINNT=0x600 -march=native -Wall -Wextra -pedantic -std=gnu++0x -pthread -Wl,--no-as-needed -I../include
CXX_RELEASE_FLAGS = -O3
CXX_DEBUG_FLAGS= -g
all: example
debug: example-debug
example: example.cpp
$(CXX) example.cpp -o example $(CXXFLAGS) $(CXX_RELEASE_FLAGS)
example-debug: example.cpp
$(CXX) example.cpp -o example-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS)
clean:
rm -f *.o logs/*.txt example example-debug
rebuild: clean all
rebuild-debug: clean debug

View File

@ -1,11 +1,8 @@
// //
// Copyright(c) 2015 Gabi Melman. // Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// spdlog usage example // spdlog usage example
//
//
#include <cstdio> #include <cstdio>
@ -26,7 +23,7 @@ void clone_example();
int main(int, char *[]) int main(int, char *[])
{ {
spdlog::info("Welcome to spdlog version {}.{}.{} !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR, SPDLOG_VER_PATCH); spdlog::info("Welcome to spdlog version {}.{}.{} !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR, SPDLOG_VER_PATCH);
spdlog::warn("Easy padding in numbers like {:08d}", 12); spdlog::warn("Easy padding in numbers like {:08d}", 12);
spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
spdlog::info("Support for floats {:03.2f}", 1.23456); spdlog::info("Support for floats {:03.2f}", 1.23456);

View File

@ -1,106 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27703.2018
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example", "example.vcxproj", "{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "spdlog", "spdlog", "{7FC6AB76-AD88-4135-888C-0568E81475AF}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\async.h = ..\include\spdlog\async.h
..\include\spdlog\async_logger.h = ..\include\spdlog\async_logger.h
..\include\spdlog\common.h = ..\include\spdlog\common.h
..\include\spdlog\formatter.h = ..\include\spdlog\formatter.h
..\include\spdlog\logger.h = ..\include\spdlog\logger.h
..\include\spdlog\spdlog.h = ..\include\spdlog\spdlog.h
..\include\spdlog\tweakme.h = ..\include\spdlog\tweakme.h
..\include\spdlog\version.h = ..\include\spdlog\version.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "details", "details", "{08E93803-E650-42D9-BBB4-3C16979F850E}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\details\async_logger_impl.h = ..\include\spdlog\details\async_logger_impl.h
..\include\spdlog\details\circular_q.h = ..\include\spdlog\details\circular_q.h
..\include\spdlog\details\console_globals.h = ..\include\spdlog\details\console_globals.h
..\include\spdlog\details\file_helper.h = ..\include\spdlog\details\file_helper.h
..\include\spdlog\details\fmt_helper.h = ..\include\spdlog\details\fmt_helper.h
..\include\spdlog\details\log_msg.h = ..\include\spdlog\details\log_msg.h
..\include\spdlog\details\logger_impl.h = ..\include\spdlog\details\logger_impl.h
..\include\spdlog\details\mpmc_blocking_q.h = ..\include\spdlog\details\mpmc_blocking_q.h
..\include\spdlog\details\null_mutex.h = ..\include\spdlog\details\null_mutex.h
..\include\spdlog\details\os.h = ..\include\spdlog\details\os.h
..\include\spdlog\details\pattern_formatter.h = ..\include\spdlog\details\pattern_formatter.h
..\include\spdlog\details\periodic_worker.h = ..\include\spdlog\details\periodic_worker.h
..\include\spdlog\details\registry.h = ..\include\spdlog\details\registry.h
..\include\spdlog\details\spdlog_impl.h = ..\include\spdlog\details\spdlog_impl.h
..\include\spdlog\details\thread_pool.h = ..\include\spdlog\details\thread_pool.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "fmt", "fmt", "{82378DE1-8463-4F91-91A0-C2C40E2AEA2A}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\fmt\fmt.h = ..\include\spdlog\fmt\fmt.h
..\include\spdlog\fmt\ostr.h = ..\include\spdlog\fmt\ostr.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "bundled", "bundled", "{D9CA4494-80D1-48D1-A897-D3564F7B27FF}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\fmt\bundled\format.cc = ..\include\spdlog\fmt\bundled\format.cc
..\include\spdlog\fmt\bundled\format.h = ..\include\spdlog\fmt\bundled\format.h
..\include\spdlog\fmt\bundled\LICENSE.rst = ..\include\spdlog\fmt\bundled\LICENSE.rst
..\include\spdlog\fmt\bundled\ostream.cc = ..\include\spdlog\fmt\bundled\ostream.cc
..\include\spdlog\fmt\bundled\ostream.h = ..\include\spdlog\fmt\bundled\ostream.h
..\include\spdlog\fmt\bundled\posix.cc = ..\include\spdlog\fmt\bundled\posix.cc
..\include\spdlog\fmt\bundled\posix.h = ..\include\spdlog\fmt\bundled\posix.h
..\include\spdlog\fmt\bundled\printf.cc = ..\include\spdlog\fmt\bundled\printf.cc
..\include\spdlog\fmt\bundled\printf.h = ..\include\spdlog\fmt\bundled\printf.h
..\include\spdlog\fmt\bundled\time.h = ..\include\spdlog\fmt\bundled\time.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sinks", "sinks", "{27D16BB9-2B81-4F61-80EC-0C7A777248E4}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\sinks\android_sink.h = ..\include\spdlog\sinks\android_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\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\null_sink.h = ..\include\spdlog\sinks\null_sink.h
..\include\spdlog\sinks\ostream_sink.h = ..\include\spdlog\sinks\ostream_sink.h
..\include\spdlog\sinks\sink.h = ..\include\spdlog\sinks\sink.h
..\include\spdlog\sinks\stdout_color_sinks.h = ..\include\spdlog\sinks\stdout_color_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\wincolor_sink.h = ..\include\spdlog\sinks\wincolor_sink.h
..\include\spdlog\sinks\windebug_sink.h = ..\include\spdlog\sinks\windebug_sink.h
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Debug|Win32.ActiveCfg = Debug|Win32
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Debug|Win32.Build.0 = Debug|Win32
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Debug|x64.ActiveCfg = Debug|x64
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Debug|x64.Build.0 = Debug|x64
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Release|Win32.ActiveCfg = Release|Win32
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Release|Win32.Build.0 = Release|Win32
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Release|x64.ActiveCfg = Release|x64
{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{08E93803-E650-42D9-BBB4-3C16979F850E} = {7FC6AB76-AD88-4135-888C-0568E81475AF}
{82378DE1-8463-4F91-91A0-C2C40E2AEA2A} = {7FC6AB76-AD88-4135-888C-0568E81475AF}
{D9CA4494-80D1-48D1-A897-D3564F7B27FF} = {82378DE1-8463-4F91-91A0-C2C40E2AEA2A}
{27D16BB9-2B81-4F61-80EC-0C7A777248E4} = {7FC6AB76-AD88-4135-888C-0568E81475AF}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1BF53532-C5DC-4236-B195-9E17CBE40A48}
EndGlobalSection
EndGlobal

View File

@ -1,167 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="example.cpp" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>.</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PrecompiledHeaderFile />
<PrecompiledHeaderOutputFile />
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PrecompiledHeaderFile>
</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>
</PrecompiledHeaderOutputFile>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PrecompiledHeaderFile />
<PrecompiledHeaderOutputFile />
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PrecompiledHeaderFile>
</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>
</PrecompiledHeaderOutputFile>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,15 +0,0 @@
# Setup a project
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := example
LOCAL_SRC_FILES := example.cpp
LOCAL_CPPFLAGS += -Wall -Wshadow -Wextra -pedantic -std=c++11 -fPIE -pie
LOCAL_LDFLAGS += -fPIE -pie
# Add exception support and set path for spdlog's headers
LOCAL_CPPFLAGS += -fexceptions -I../include
# Use android's log library
LOCAL_LDFLAGS += -llog
include $(BUILD_EXECUTABLE)

View File

@ -1,2 +0,0 @@
# Exceptions are used in spdlog. Link to an exception-ready C++ runtime.
APP_STL = gnustl_static

View File

@ -1,157 +0,0 @@
//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// spdlog usage example
//
//
#define SPDLOG_TRACE_ON
#define SPDLOG_DEBUG_ON
#include "spdlog/spdlog.h"
#include <iostream>
#include <memory>
void async_example();
void syslog_example();
void android_example();
void user_defined_example();
void err_handler_example();
namespace spd = spdlog;
int main(int, char *[])
{
try
{
// Console logger with color
auto console = spd::stdout_color_mt("console");
console->info("Welcome to spdlog!");
console->error("Some error message with arg{}..", 1);
// Formatting examples
console->warn("Easy padding in numbers like {:08d}", 12);
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
console->info("Support for floats {:03.2f}", 1.23456);
console->info("Positional args are {1} {0}..", "too", "supported");
console->info("{:<30}", "left aligned");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
// Create basic file logger (not rotated)
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt");
my_logger->info("Some log message");
// Create a file rotating logger with 5mb size max and 3 rotated files
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
for (int i = 0; i < 10; ++i)
rotating_logger->info("{} * {} equals {:>10}", i, i, i * i);
// Create a daily logger - a new file is created every day on 2:30am
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
// trigger flush if the log severity is error or higher
daily_logger->flush_on(spd::level::err);
daily_logger->info(123.44);
// Customize msg format for all messages
spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
rotating_logger->info("This is another message with custom format");
// Runtime log levels
spd::set_level(spd::level::info); // Set global log level to info
console->debug("This message should not be displayed!");
console->set_level(spd::level::debug); // Set specific logger's log level
console->debug("This message should be displayed..");
// Compile time log levels
// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
// Asynchronous logging is very fast..
// Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
async_example();
// syslog example. linux/osx only
syslog_example();
// android example. compile with NDK
android_example();
// Log user-defined types example
user_defined_example();
// Change default log error handler
err_handler_example();
// Apply a function on all registered loggers
spd::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
// Release and close all loggers
spdlog::drop_all();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
catch (const spd::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
return 1;
}
}
void async_example()
{
size_t q_size = 4096; // queue size must be power of 2
spdlog::set_async_mode(q_size);
auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
for (int i = 0; i < 100; ++i)
async_file->info("Async message #{}", i);
}
// syslog example (linux/osx/freebsd)
void syslog_example()
{
#ifdef SPDLOG_ENABLE_SYSLOG
std::string ident = "spdlog-example";
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog.");
#endif
}
// Android example
void android_example()
{
#if defined(__ANDROID__)
std::string tag = "spdlog-android";
auto android_logger = spd::android_logger("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
#endif
}
// user defined types logging by implementing operator<<
struct my_type
{
int i;
template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c)
{
return os << "[my_type i=" << c.i << "]";
}
};
#include "spdlog/fmt/ostr.h" // must be included
void user_defined_example()
{
spd::get("console")->info("user defined type: {}", my_type{14});
}
//
// custom error handler
//
void err_handler_example()
{
// can be set globaly or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { std::cerr << "my err handler: " << msg << std::endl; });
spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
}

View File

@ -1 +0,0 @@
*.txt

View File

@ -1,47 +0,0 @@
#include "spdlog/spdlog.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/stdout_sinks.h"
#include <iostream>
#include <memory>
int main(int, char *[])
{
bool enable_debug = true;
try
{
// This other example use a single logger with multiple sinks.
// This means that the same log_msg is forwarded to multiple sinks;
// Each sink can have it's own log level and a message will be logged.
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_mt>());
sinks.push_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>("./log_regular_file.txt"));
sinks.push_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>("./log_debug_file.txt"));
spdlog::logger console_multisink("multisink", sinks.begin(), sinks.end());
console_multisink.set_level(spdlog::level::warn);
sinks[0]->set_level(spdlog::level::trace); // console. Allow everything. Default value
sinks[1]->set_level(spdlog::level::trace); // regular file. Allow everything. Default value
sinks[2]->set_level(spdlog::level::off); // regular file. Ignore everything.
console_multisink.warn("warn: will print only on console and regular file");
if (enable_debug)
{
console_multisink.set_level(spdlog::level::debug); // level of the logger
sinks[1]->set_level(spdlog::level::debug); // regular file
sinks[2]->set_level(spdlog::level::debug); // debug file
}
console_multisink.debug("Debug: you should see this on console and both files");
// Release and close all loggers
spdlog::drop_all();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
catch (const spdlog::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
return 1;
}
}

View File

@ -1,34 +0,0 @@
//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
#include <iomanip>
#include <locale>
#include <sstream>
namespace utils {
template<typename T>
inline std::string format(const T &value)
{
static std::locale loc("");
std::stringstream ss;
ss.imbue(loc);
ss << value;
return ss.str();
}
template<>
inline std::string format(const double &value)
{
static std::locale loc("");
std::stringstream ss;
ss.imbue(loc);
ss << std::fixed << std::setprecision(1) << value;
return ss.str();
}
} // namespace utils

View File

@ -1,8 +1,5 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
//
// Copyright(c) 2018 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once

View File

@ -1,13 +1,13 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
// async logger implementation #ifndef SPDLOG_HEADER_ONLY
// uses a thread pool to perform the actual logging #include "spdlog/async_logger.h"
#endif
#include "spdlog/sinks/sink.h"
#include "spdlog/details/thread_pool.h" #include "spdlog/details/thread_pool.h"
#include <chrono> #include <chrono>
@ -15,32 +15,26 @@
#include <string> #include <string>
template<typename It> template<typename It>
inline spdlog::async_logger::async_logger( SPDLOG_INLINE spdlog::async_logger::async_logger(
std::string logger_name, It begin, It end, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy) std::string logger_name, It begin, It end, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
: logger(std::move(logger_name), begin, end) : logger(std::move(logger_name), begin, end)
, thread_pool_(std::move(tp)) , thread_pool_(std::move(tp))
, overflow_policy_(overflow_policy) , overflow_policy_(overflow_policy)
{ {}
}
inline spdlog::async_logger::async_logger( SPDLOG_INLINE spdlog::async_logger::async_logger(
std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy) std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
: async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), std::move(tp), overflow_policy) : async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), std::move(tp), overflow_policy)
{ {}
}
inline spdlog::async_logger::async_logger( SPDLOG_INLINE spdlog::async_logger::async_logger(
std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy) std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
: async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy) : async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy)
{ {}
}
// send the log message to the thread pool // send the log message to the thread pool
inline void spdlog::async_logger::sink_it_(details::log_msg &msg) SPDLOG_INLINE void spdlog::async_logger::sink_it_(details::log_msg &msg)
{ {
#if defined(SPDLOG_ENABLE_MESSAGE_COUNTER)
incr_msg_counter_(msg);
#endif
if (auto pool_ptr = thread_pool_.lock()) if (auto pool_ptr = thread_pool_.lock())
{ {
pool_ptr->post_log(shared_from_this(), msg, overflow_policy_); pool_ptr->post_log(shared_from_this(), msg, overflow_policy_);
@ -52,7 +46,7 @@ inline void spdlog::async_logger::sink_it_(details::log_msg &msg)
} }
// send flush request to the thread pool // send flush request to the thread pool
inline void spdlog::async_logger::flush_() SPDLOG_INLINE void spdlog::async_logger::flush_()
{ {
if (auto pool_ptr = thread_pool_.lock()) if (auto pool_ptr = thread_pool_.lock())
{ {
@ -67,7 +61,7 @@ inline void spdlog::async_logger::flush_()
// //
// backend functions - called from the thread pool to do the actual job // backend functions - called from the thread pool to do the actual job
// //
inline void spdlog::async_logger::backend_log_(const details::log_msg &incoming_log_msg) SPDLOG_INLINE void spdlog::async_logger::backend_log_(const details::log_msg &incoming_log_msg)
{ {
try try
{ {
@ -79,7 +73,14 @@ inline void spdlog::async_logger::backend_log_(const details::log_msg &incoming_
} }
} }
} }
SPDLOG_CATCH_AND_HANDLE catch (const std::exception &ex)
{
err_handler_(ex.what());
}
catch (...)
{
err_handler_("Unknown exception in logger");
}
if (should_flush_(incoming_log_msg)) if (should_flush_(incoming_log_msg))
{ {
@ -87,7 +88,7 @@ inline void spdlog::async_logger::backend_log_(const details::log_msg &incoming_
} }
} }
inline void spdlog::async_logger::backend_flush_() SPDLOG_INLINE void spdlog::async_logger::backend_flush_()
{ {
try try
{ {
@ -96,15 +97,22 @@ inline void spdlog::async_logger::backend_flush_()
sink->flush(); sink->flush();
} }
} }
SPDLOG_CATCH_AND_HANDLE catch (const std::exception &ex)
{
err_handler_(ex.what());
}
catch (...)
{
err_handler_("Unknown exception in logger");
}
} }
inline std::shared_ptr<spdlog::logger> spdlog::async_logger::clone(std::string new_name) SPDLOG_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_); 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->set_level(this->level());
cloned->flush_on(this->flush_level()); cloned->flush_on(this->flush_level());
cloned->set_error_handler(this->error_handler()); cloned->set_error_handler(this->custom_err_handler_);
return std::move(cloned); return std::move(cloned);
} }

View File

@ -1,31 +1,21 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
// Very fast asynchronous logger (millions of logs per second on an average // Fast asynchronous logger.
// desktop) // Uses pre allocated queue.
// Uses pre allocated lockfree queue for maximum throughput even under large
// number of threads.
// Creates a single back thread to pop messages from the queue and log them. // Creates a single back thread to pop messages from the queue and log them.
// //
// Upon each log write the logger: // Upon each log write the logger:
// 1. Checks if its log level is enough to log the message // 1. Checks if its log level is enough to log the message
// 2. Push a new copy of the message to a queue (or block the caller until // 2. Push a new copy of the message to a queue (or block the caller until
// space is available in the queue) // space is available in the queue)
// 3. will throw spdlog_ex upon log exceptions
// Upon destruction, logs all remaining messages in the queue before // Upon destruction, logs all remaining messages in the queue before
// destructing.. // destructing..
#include "spdlog/common.h"
#include "spdlog/logger.h" #include "spdlog/logger.h"
#include <chrono>
#include <memory>
#include <string>
namespace spdlog { namespace spdlog {
// Async overflow policy - block by default. // Async overflow policy - block by default.
@ -70,4 +60,6 @@ private:
}; };
} // namespace spdlog } // namespace spdlog
#include "details/async_logger_impl.h" #ifdef SPDLOG_HEADER_ONLY
#include "async_logger-inl.h"
#endif

View File

@ -0,0 +1,57 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/common.h"
#endif
namespace spdlog {
namespace level {
static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES;
static const char *short_level_names[] SPDLOG_SHORT_LEVEL_NAMES;
SPDLOG_INLINE string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT
{
return level_string_views[l];
}
SPDLOG_INLINE const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT
{
return short_level_names[l];
}
SPDLOG_INLINE spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT
{
int level = 0;
for (const auto &level_str : level_string_views)
{
if (level_str == name)
{
return static_cast<level::level_enum>(level);
}
level++;
}
return level::off;
}
} // namespace level
SPDLOG_INLINE spdlog_ex::spdlog_ex(std::string msg)
: msg_(std::move(msg))
{}
SPDLOG_INLINE spdlog_ex::spdlog_ex(const std::string &msg, int last_errno)
{
fmt::memory_buffer outbuf;
fmt::format_system_error(outbuf, last_errno, msg);
msg_ = fmt::to_string(outbuf);
}
SPDLOG_INLINE const char *spdlog_ex::what() const SPDLOG_NOEXCEPT
{
return msg_.c_str();
}
} // namespace spdlog

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -9,21 +7,25 @@
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
#include <functional>
#include <initializer_list> #include <initializer_list>
#include <memory> #include <memory>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <cstring>
#include <type_traits> #include <type_traits>
#include <unordered_map> #include <functional>
#if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) #if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
#include <codecvt> #include <codecvt>
#include <locale> #include <locale>
#endif #endif
#include "spdlog/details/null_mutex.h" #ifdef SPDLOG_COMPILED_LIB
#undef SPDLOG_HEADER_ONLY
#define SPDLOG_INLINE
#else
#define SPDLOG_HEADER_ONLY
#define SPDLOG_INLINE inline
#endif
#include "spdlog/fmt/fmt.h" #include "spdlog/fmt/fmt.h"
@ -76,10 +78,23 @@ namespace sinks {
class sink; class sink;
} }
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
using filename_t = std::wstring;
#define SPDLOG_FILENAME_T(s) L##s
inline std::string filename_to_str(const filename_t &filename)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> c;
return c.to_bytes(filename);
}
#else
using filename_t = std::string;
#define SPDLOG_FILENAME_T(s) s
#endif
using log_clock = std::chrono::system_clock; using log_clock = std::chrono::system_clock;
using sink_ptr = std::shared_ptr<sinks::sink>; using sink_ptr = std::shared_ptr<sinks::sink>;
using sinks_init_list = std::initializer_list<sink_ptr>; using sinks_init_list = std::initializer_list<sink_ptr>;
using log_err_handler = std::function<void(const std::string &err_msg)>; using err_handler = std::function<void(const std::string &err_msg)>;
// string_view type - either std::string_view or fmt::string_view (pre c++17) // string_view type - either std::string_view or fmt::string_view (pre c++17)
#if defined(FMT_USE_STD_STRING_VIEW) #if defined(FMT_USE_STD_STRING_VIEW)
@ -125,36 +140,18 @@ enum level_enum
"trace", "debug", "info", "warning", "error", "critical", "off" \ "trace", "debug", "info", "warning", "error", "critical", "off" \
} }
#endif #endif
static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES;
#if !defined(SPDLOG_SHORT_LEVEL_NAMES) #if !defined(SPDLOG_SHORT_LEVEL_NAMES)
#define SPDLOG_SHORT_LEVEL_NAMES {"T", "D", "I", "W", "E", "C", "O"}
#endif
static const char *short_level_names[] SPDLOG_SHORT_LEVEL_NAMES;
inline string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT #define SPDLOG_SHORT_LEVEL_NAMES \
{ { \
return level_string_views[l]; "T", "D", "I", "W", "E", "C", "O" \
}
inline const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT
{
return short_level_names[l];
}
inline spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT
{
int level = 0;
for (const auto &level_str : level_string_views)
{
if (level_str == name)
{
return static_cast<level::level_enum>(level);
}
level++;
} }
return level::off; #endif
}
string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT;
using level_hasher = std::hash<int>; using level_hasher = std::hash<int>;
} // namespace level } // namespace level
@ -185,58 +182,30 @@ enum class pattern_time_type
class spdlog_ex : public std::exception class spdlog_ex : public std::exception
{ {
public: public:
explicit spdlog_ex(std::string msg) explicit spdlog_ex(std::string msg);
: msg_(std::move(msg)) spdlog_ex(const std::string &msg, int last_errno);
{ const char *what() const SPDLOG_NOEXCEPT override;
}
spdlog_ex(const std::string &msg, int 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
{
return msg_.c_str();
}
private: private:
std::string msg_; std::string msg_;
}; };
//
// wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined)
//
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
using filename_t = std::wstring;
#else
using filename_t = std::string;
#endif
struct source_loc struct source_loc
{ {
SPDLOG_CONSTEXPR source_loc() SPDLOG_CONSTEXPR source_loc() = default;
: filename{""}
, line{0}
, funcname{""}
{
}
SPDLOG_CONSTEXPR source_loc(const char *filename_in, int line_in, const char *funcname_in) SPDLOG_CONSTEXPR source_loc(const char *filename_in, int line_in, const char *funcname_in)
: filename{filename_in} : filename{filename_in}
, line{static_cast<uint32_t>(line_in)} , line{line_in}
, funcname{funcname_in} , funcname{funcname_in}
{ {}
}
SPDLOG_CONSTEXPR bool empty() const SPDLOG_NOEXCEPT SPDLOG_CONSTEXPR bool empty() const SPDLOG_NOEXCEPT
{ {
return line == 0; return line == 0;
} }
const char *filename; const char *filename{nullptr};
uint32_t line; int line{0};
const char *funcname; const char *funcname{nullptr};
}; };
namespace details { namespace details {
@ -254,3 +223,7 @@ std::unique_ptr<T> make_unique(Args &&... args)
#endif #endif
} // namespace details } // namespace details
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "common-inl.h"
#endif

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2018 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
// cirucal q view of std::vector. // cirucal q view of std::vector.
#pragma once #pragma once
@ -19,8 +17,7 @@ public:
explicit circular_q(size_t max_items) explicit circular_q(size_t max_items)
: max_items_(max_items + 1) // one item is reserved as marker for full q : max_items_(max_items + 1) // one item is reserved as marker for full q
, v_(max_items_) , v_(max_items_)
{ {}
}
// push back, overrun (oldest) item if no room left // push back, overrun (oldest) item if no room left
void push_back(T &&item) void push_back(T &&item)

View File

@ -1,8 +1,7 @@
#pragma once // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
//
// Copyright(c) 2018 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
#include "spdlog/details/null_mutex.h" #include "spdlog/details/null_mutex.h"
#include <cstdio> #include <cstdio>

View File

@ -0,0 +1,132 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/details/file_helper.h"
#endif
#include "spdlog/details/os.h"
#include <cerrno>
#include <chrono>
#include <cstdio>
#include <string>
#include <thread>
#include <tuple>
namespace spdlog {
namespace details {
SPDLOG_INLINE file_helper::~file_helper()
{
close();
}
SPDLOG_INLINE void file_helper::open(const filename_t &fname, bool truncate)
{
close();
auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab");
_filename = fname;
for (int tries = 0; tries < open_tries; ++tries)
{
if (!os::fopen_s(&fd_, fname, mode))
{
return;
}
details::os::sleep_for_millis(open_interval);
}
throw spdlog_ex("Failed opening file " + os::filename_to_str(_filename) + " for writing", errno);
}
SPDLOG_INLINE void file_helper::reopen(bool truncate)
{
if (_filename.empty())
{
throw spdlog_ex("Failed re opening file - was not opened before");
}
open(_filename, truncate);
}
SPDLOG_INLINE void file_helper::flush()
{
std::fflush(fd_);
}
SPDLOG_INLINE void file_helper::close()
{
if (fd_ != nullptr)
{
std::fclose(fd_);
fd_ = nullptr;
}
}
SPDLOG_INLINE void file_helper::write(const fmt::memory_buffer &buf)
{
size_t msg_size = buf.size();
auto data = buf.data();
if (std::fwrite(data, 1, msg_size, fd_) != msg_size)
{
throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno);
}
}
SPDLOG_INLINE size_t file_helper::size() const
{
if (fd_ == nullptr)
{
throw spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(_filename));
}
return os::filesize(fd_);
}
SPDLOG_INLINE const filename_t &file_helper::filename() const
{
return _filename;
}
SPDLOG_INLINE bool file_helper::file_exists(const filename_t &fname)
{
return os::file_exists(fname);
}
//
// return file path and its extension:
//
// "mylog.txt" => ("mylog", ".txt")
// "mylog" => ("mylog", "")
// "mylog." => ("mylog.", "")
// "/dir1/dir2/mylog.txt" => ("/dir1/dir2/mylog", ".txt")
//
// the starting dot in filenames is ignored (hidden files):
//
// ".mylog" => (".mylog". "")
// "my_folder/.mylog" => ("my_folder/.mylog", "")
// "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt")
SPDLOG_INLINE std::tuple<filename_t, filename_t> file_helper::split_by_extension(const filename_t &fname)
{
auto ext_index = fname.rfind('.');
// no valid extension found - return whole path and empty string as
// extension
if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1)
{
return std::make_tuple(fname, filename_t());
}
// treat casese like "/etc/rc.d/somelogfile or "/abc/.hiddenfile"
auto folder_index = fname.rfind(details::os::folder_sep);
if (folder_index != filename_t::npos && folder_index >= ext_index - 1)
{
return std::make_tuple(fname, filename_t());
}
// finally - return a valid base and extension tuple
return std::make_tuple(fname.substr(0, ext_index), fname.substr(ext_index));
}
} // namespace details
} // namespace spdlog

View File

@ -1,113 +1,37 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
// Helper class for file sinks. #include "spdlog/common.h"
// When failing to open a file, retry several times(5) with a delay interval(10 ms).
// Throw spdlog_ex exception on errors.
#include "spdlog/details/log_msg.h"
#include "spdlog/details/os.h"
#include <cerrno>
#include <chrono>
#include <cstdio>
#include <string>
#include <thread>
#include <tuple> #include <tuple>
namespace spdlog { namespace spdlog {
namespace details { namespace details {
// Helper class for file sinks.
// When failing to open a file, retry several times(5) with a delay interval(10 ms).
// Throw spdlog_ex exception on errors.
class file_helper class file_helper
{ {
public: public:
const int open_tries = 5; const int open_tries = 5;
const int open_interval = 10; const int open_interval = 10;
explicit file_helper() = default; explicit file_helper() = default;
file_helper(const file_helper &) = delete; file_helper(const file_helper &) = delete;
file_helper &operator=(const file_helper &) = delete; file_helper &operator=(const file_helper &) = delete;
~file_helper();
~file_helper() void open(const filename_t &fname, bool truncate = false);
{ void reopen(bool truncate);
close(); void flush();
} void close();
void write(const fmt::memory_buffer &buf);
void open(const filename_t &fname, bool truncate = false) size_t size() const;
{ const filename_t &filename() const;
close(); static bool file_exists(const filename_t &fname);
auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab");
_filename = fname;
for (int tries = 0; tries < open_tries; ++tries)
{
if (!os::fopen_s(&fd_, fname, mode))
{
return;
}
details::os::sleep_for_millis(open_interval);
}
throw spdlog_ex("Failed opening file " + os::filename_to_str(_filename) + " for writing", errno);
}
void reopen(bool truncate)
{
if (_filename.empty())
{
throw spdlog_ex("Failed re opening file - was not opened before");
}
open(_filename, truncate);
}
void flush()
{
std::fflush(fd_);
}
void close()
{
if (fd_ != nullptr)
{
std::fclose(fd_);
fd_ = nullptr;
}
}
void write(const fmt::memory_buffer &buf)
{
size_t msg_size = buf.size();
auto data = buf.data();
if (std::fwrite(data, 1, msg_size, fd_) != msg_size)
{
throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno);
}
}
size_t size() const
{
if (fd_ == nullptr)
{
throw spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(_filename));
}
return os::filesize(fd_);
}
const filename_t &filename() const
{
return _filename;
}
static bool file_exists(const filename_t &fname)
{
return os::file_exists(fname);
}
// //
// return file path and its extension: // return file path and its extension:
@ -122,27 +46,7 @@ public:
// ".mylog" => (".mylog". "") // ".mylog" => (".mylog". "")
// "my_folder/.mylog" => ("my_folder/.mylog", "") // "my_folder/.mylog" => ("my_folder/.mylog", "")
// "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt") // "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt")
static std::tuple<filename_t, filename_t> split_by_extension(const spdlog::filename_t &fname) static std::tuple<filename_t, filename_t> split_by_extension(const filename_t &fname);
{
auto ext_index = fname.rfind('.');
// no valid extension found - return whole path and empty string as
// extension
if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1)
{
return std::make_tuple(fname, spdlog::filename_t());
}
// treat casese like "/etc/rc.d/somelogfile or "/abc/.hiddenfile"
auto folder_index = fname.rfind(details::os::folder_sep);
if (folder_index != filename_t::npos && folder_index >= ext_index - 1)
{
return std::make_tuple(fname, spdlog::filename_t());
}
// finally - return a valid base and extension tuple
return std::make_tuple(fname.substr(0, ext_index), fname.substr(ext_index));
}
private: private:
std::FILE *fd_{nullptr}; std::FILE *fd_{nullptr};
@ -150,3 +54,7 @@ private:
}; };
} // namespace details } // namespace details
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "file_helper-inl.h"
#endif

View File

@ -1,12 +1,11 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Created by gabi on 6/15/18. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
#include <chrono> #include <chrono>
#include <type_traits> #include <type_traits>
#include "spdlog/fmt/fmt.h" #include "spdlog/fmt/fmt.h"
#include "spdlog/common.h"
// Some fmt helpers to efficiently format and pad ints and strings // Some fmt helpers to efficiently format and pad ints and strings
namespace spdlog { namespace spdlog {

View File

@ -0,0 +1,36 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/details/log_msg.h"
#endif
#include "spdlog/details/os.h"
#include "spdlog/sinks/sink.h"
namespace spdlog {
namespace details {
SPDLOG_INLINE log_msg::log_msg(
spdlog::source_loc loc, const std::string *loggers_name, spdlog::level::level_enum lvl, spdlog::string_view_t view)
: logger_name(loggers_name)
, level(lvl)
#ifndef SPDLOG_NO_DATETIME
, time(os::now())
#endif
#ifndef SPDLOG_NO_THREAD_ID
, thread_id(os::thread_id())
#endif
, source(loc)
, payload(view)
{}
SPDLOG_INLINE log_msg::log_msg(const std::string *loggers_name, spdlog::level::level_enum lvl, spdlog::string_view_t view)
: log_msg(source_loc{}, loggers_name, lvl, view)
{}
} // namespace details
} // namespace spdlog

View File

@ -1,41 +1,17 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
#include "spdlog/common.h" #include "spdlog/common.h"
#include "spdlog/details/os.h"
#include <string> #include <string>
#include <utility>
namespace spdlog { namespace spdlog {
namespace details { namespace details {
struct log_msg struct log_msg
{ {
log_msg(source_loc loc, const std::string *loggers_name, level::level_enum lvl, string_view_t view);
log_msg(source_loc loc, const std::string *loggers_name, level::level_enum lvl, string_view_t view) log_msg(const std::string *loggers_name, level::level_enum lvl, string_view_t view);
: logger_name(loggers_name)
, level(lvl)
#ifndef SPDLOG_NO_DATETIME
, time(os::now())
#endif
#ifndef SPDLOG_NO_THREAD_ID
, thread_id(os::thread_id())
#endif
, source(loc)
, payload(view)
{
}
log_msg(const std::string *loggers_name, level::level_enum lvl, string_view_t view)
: log_msg(source_loc{}, loggers_name, lvl, view)
{
}
log_msg(const log_msg &other) = default; log_msg(const log_msg &other) = default;
const std::string *logger_name{nullptr}; const std::string *logger_name{nullptr};
@ -53,3 +29,7 @@ struct log_msg
}; };
} // namespace details } // namespace details
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "log_msg-inl.h"
#endif

View File

@ -1,435 +0,0 @@
//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
#include "spdlog/details/fmt_helper.h"
#include <memory>
#include <string>
#define SPDLOG_CATCH_AND_HANDLE \
catch (const std::exception &ex) \
{ \
err_handler_(ex.what()); \
} \
catch (...) \
{ \
err_handler_("Unknown exception in logger"); \
}
// create logger with given name, sinks and the default pattern formatter
// all other ctors will call this one
template<typename It>
inline spdlog::logger::logger(std::string logger_name, It begin, It end)
: name_(std::move(logger_name))
, sinks_(begin, end)
{
}
// ctor with sinks as init list
inline spdlog::logger::logger(std::string logger_name, sinks_init_list sinks_list)
: logger(std::move(logger_name), sinks_list.begin(), sinks_list.end())
{
}
// ctor with single sink
inline spdlog::logger::logger(std::string logger_name, spdlog::sink_ptr single_sink)
: logger(std::move(logger_name), {std::move(single_sink)})
{
}
inline spdlog::logger::~logger() = default;
inline void spdlog::logger::set_formatter(std::unique_ptr<spdlog::formatter> f)
{
for (auto &sink : sinks_)
{
sink->set_formatter(f->clone());
}
}
inline void spdlog::logger::set_pattern(std::string pattern, pattern_time_type time_type)
{
auto new_formatter = details::make_unique<spdlog::pattern_formatter>(std::move(pattern), time_type);
set_formatter(std::move(new_formatter));
}
template<typename... Args>
inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const char *fmt, const Args &... args)
{
if (!should_log(lvl))
{
return;
}
try
{
using details::fmt_helper::to_string_view;
fmt::memory_buffer buf;
fmt::format_to(buf, fmt, args...);
details::log_msg log_msg(source, &name_, lvl, to_string_view(buf));
sink_it_(log_msg);
}
SPDLOG_CATCH_AND_HANDLE
}
template<typename... Args>
inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args)
{
log(source_loc{}, lvl, fmt, args...);
}
inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const char *msg)
{
if (!should_log(lvl))
{
return;
}
try
{
details::log_msg log_msg(source, &name_, lvl, spdlog::string_view_t(msg));
sink_it_(log_msg);
}
SPDLOG_CATCH_AND_HANDLE
}
inline void spdlog::logger::log(level::level_enum lvl, const char *msg)
{
log(source_loc{}, lvl, msg);
}
template<class T>
inline void spdlog::logger::log(level::level_enum lvl, const T &msg)
{
log(source_loc{}, lvl, msg);
}
template<class T, typename std::enable_if<std::is_convertible<T, spdlog::string_view_t>::value, T>::type *>
inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const T &msg)
{
if (!should_log(lvl))
{
return;
}
try
{
details::log_msg log_msg(source, &name_, lvl, msg);
sink_it_(log_msg);
}
SPDLOG_CATCH_AND_HANDLE
}
template<class T, typename std::enable_if<!std::is_convertible<T, spdlog::string_view_t>::value, T>::type *>
inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const T &msg)
{
if (!should_log(lvl))
{
return;
}
try
{
using details::fmt_helper::to_string_view;
fmt::memory_buffer buf;
fmt::format_to(buf, "{}", msg);
details::log_msg log_msg(source, &name_, lvl, to_string_view(buf));
sink_it_(log_msg);
}
SPDLOG_CATCH_AND_HANDLE
}
template<typename... Args>
inline void spdlog::logger::trace(const char *fmt, const Args &... args)
{
log(level::trace, fmt, args...);
}
template<typename... Args>
inline void spdlog::logger::debug(const char *fmt, const Args &... args)
{
log(level::debug, fmt, args...);
}
template<typename... Args>
inline void spdlog::logger::info(const char *fmt, const Args &... args)
{
log(level::info, fmt, args...);
}
template<typename... Args>
inline void spdlog::logger::warn(const char *fmt, const Args &... args)
{
log(level::warn, fmt, args...);
}
template<typename... Args>
inline void spdlog::logger::error(const char *fmt, const Args &... args)
{
log(level::err, fmt, args...);
}
template<typename... Args>
inline void spdlog::logger::critical(const char *fmt, const Args &... args)
{
log(level::critical, fmt, args...);
}
template<typename T>
inline void spdlog::logger::trace(const T &msg)
{
log(level::trace, msg);
}
template<typename T>
inline void spdlog::logger::debug(const T &msg)
{
log(level::debug, msg);
}
template<typename T>
inline void spdlog::logger::info(const T &msg)
{
log(level::info, msg);
}
template<typename T>
inline void spdlog::logger::warn(const T &msg)
{
log(level::warn, msg);
}
template<typename T>
inline void spdlog::logger::error(const T &msg)
{
log(level::err, msg);
}
template<typename T>
inline void spdlog::logger::critical(const T &msg)
{
log(level::critical, msg);
}
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target)
{
int wbuf_size = static_cast<int>(wbuf.size());
if (wbuf_size == 0)
{
return;
}
auto result_size = ::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), wbuf_size, NULL, 0, NULL, NULL);
if (result_size > 0)
{
target.resize(result_size);
::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), wbuf_size, &target.data()[0], result_size, NULL, NULL);
}
else
{
throw spdlog::spdlog_ex(fmt::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError()));
}
}
template<typename... Args>
inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const wchar_t *fmt, const Args &... args)
{
if (!should_log(lvl))
{
return;
}
try
{
// format to wmemory_buffer and convert to utf8
using details::fmt_helper::to_string_view;
fmt::wmemory_buffer wbuf;
fmt::format_to(wbuf, fmt, args...);
fmt::memory_buffer buf;
wbuf_to_utf8buf(wbuf, buf);
details::log_msg log_msg(source, &name_, lvl, to_string_view(buf));
sink_it_(log_msg);
}
SPDLOG_CATCH_AND_HANDLE
}
template<typename... Args>
inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args)
{
log(source_loc{}, lvl, fmt, args...);
}
template<typename... Args>
inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args)
{
log(level::trace, fmt, args...);
}
template<typename... Args>
inline void spdlog::logger::debug(const wchar_t *fmt, const Args &... args)
{
log(level::debug, fmt, args...);
}
template<typename... Args>
inline void spdlog::logger::info(const wchar_t *fmt, const Args &... args)
{
log(level::info, fmt, args...);
}
template<typename... Args>
inline void spdlog::logger::warn(const wchar_t *fmt, const Args &... args)
{
log(level::warn, fmt, args...);
}
template<typename... Args>
inline void spdlog::logger::error(const wchar_t *fmt, const Args &... args)
{
log(level::err, fmt, args...);
}
template<typename... Args>
inline void spdlog::logger::critical(const wchar_t *fmt, const Args &... args)
{
log(level::critical, fmt, args...);
}
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
//
// name and level
//
inline const std::string &spdlog::logger::name() const
{
return name_;
}
inline void spdlog::logger::set_level(spdlog::level::level_enum log_level)
{
level_.store(log_level);
}
inline void spdlog::logger::set_error_handler(spdlog::log_err_handler err_handler)
{
err_handler_ = std::move(err_handler);
}
inline spdlog::log_err_handler spdlog::logger::error_handler() const
{
return err_handler_;
}
inline void spdlog::logger::flush()
{
try
{
flush_();
}
SPDLOG_CATCH_AND_HANDLE
}
inline void spdlog::logger::flush_on(level::level_enum 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)
{
auto flush_level = flush_level_.load(std::memory_order_relaxed);
return (msg.level >= flush_level) && (msg.level != level::off);
}
inline spdlog::level::level_enum spdlog::logger::default_level()
{
return static_cast<spdlog::level::level_enum>(SPDLOG_ACTIVE_LEVEL);
}
inline spdlog::level::level_enum spdlog::logger::level() const
{
return static_cast<spdlog::level::level_enum>(level_.load(std::memory_order_relaxed));
}
inline bool spdlog::logger::should_log(spdlog::level::level_enum msg_level) const
{
return msg_level >= level_.load(std::memory_order_relaxed);
}
//
// protected virtual called at end of each user log call (if enabled) by the
// line_logger
//
inline void spdlog::logger::sink_it_(details::log_msg &msg)
{
#if defined(SPDLOG_ENABLE_MESSAGE_COUNTER)
incr_msg_counter_(msg);
#endif
for (auto &sink : sinks_)
{
if (sink->should_log(msg.level))
{
sink->log(msg);
}
}
if (should_flush_(msg))
{
flush_();
}
}
inline void spdlog::logger::flush_()
{
for (auto &sink : sinks_)
{
sink->flush();
}
}
inline void spdlog::logger::default_err_handler_(const std::string &msg)
{
auto now = time(nullptr);
if (now - last_err_time_ < 60)
{
return;
}
last_err_time_ = now;
auto tm_time = details::os::localtime(now);
char date_buf[100];
std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", &tm_time);
fmt::print(stderr, "[*** LOG ERROR ***] [{}] [{}] {}\n", date_buf, name(), msg);
}
inline void spdlog::logger::incr_msg_counter_(details::log_msg &msg)
{
msg.msg_id = msg_counter_.fetch_add(1, std::memory_order_relaxed);
}
inline const std::vector<spdlog::sink_ptr> &spdlog::logger::sinks() const
{
return sinks_;
}
inline std::vector<spdlog::sink_ptr> &spdlog::logger::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;
}

View File

@ -1,9 +1,7 @@
#pragma once // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
//
// Copyright(c) 2018 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
// multi producer-multi consumer blocking queue. // multi producer-multi consumer blocking queue.
// enqueue(..) - will block until room found to put the new message. // enqueue(..) - will block until room found to put the new message.
@ -27,8 +25,7 @@ public:
using item_type = T; using item_type = T;
explicit mpmc_blocking_queue(size_t max_items) explicit mpmc_blocking_queue(size_t max_items)
: q_(max_items) : q_(max_items)
{ {}
}
#ifndef __MINGW32__ #ifndef __MINGW32__
// try to enqueue and block if no room left // try to enqueue and block if no room left

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -27,8 +25,7 @@ struct null_atomic_int
explicit null_atomic_int(int val) explicit null_atomic_int(int val)
: value(val) : value(val)
{ {}
}
int load(std::memory_order) const int load(std::memory_order) const
{ {

View File

@ -0,0 +1,425 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/details/os.h"
#endif
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <string>
#include <thread>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX // prevent windows redefining min/max
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <io.h> // _get_osfhandle and _isatty support
#include <process.h> // _get_pid support
#include <windows.h>
#ifdef __MINGW32__
#include <share.h>
#endif
#else // unix
#include <fcntl.h>
#include <unistd.h>
#ifdef __linux__
#include <sys/syscall.h> //Use gettid() syscall under linux to get thread id
#elif __FreeBSD__
#include <sys/thr.h> //Use thr_self() syscall under FreeBSD to get thread id
#endif
#endif // unix
#ifndef __has_feature // Clang - feature checking macros.
#define __has_feature(x) 0 // Compatibility with non-clang compilers.
#endif
namespace spdlog {
namespace details {
namespace os {
SPDLOG_INLINE spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT
{
#if defined __linux__ && defined SPDLOG_CLOCK_COARSE
timespec ts;
::clock_gettime(CLOCK_REALTIME_COARSE, &ts);
return std::chrono::time_point<log_clock, typename log_clock::duration>(
std::chrono::duration_cast<typename log_clock::duration>(std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec)));
#else
return log_clock::now();
#endif
}
SPDLOG_INLINE std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
{
#ifdef _WIN32
std::tm tm;
localtime_s(&tm, &time_tt);
#else
std::tm tm;
localtime_r(&time_tt, &tm);
#endif
return tm;
}
SPDLOG_INLINE std::tm localtime() SPDLOG_NOEXCEPT
{
std::time_t now_t = time(nullptr);
return localtime(now_t);
}
SPDLOG_INLINE std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
{
#ifdef _WIN32
std::tm tm;
gmtime_s(&tm, &time_tt);
#else
std::tm tm;
gmtime_r(&time_tt, &tm);
#endif
return tm;
}
SPDLOG_INLINE std::tm gmtime() SPDLOG_NOEXCEPT
{
std::time_t now_t = time(nullptr);
return gmtime(now_t);
}
SPDLOG_INLINE void prevent_child_fd(FILE *f)
{
#ifdef _WIN32
#if !defined(__cplusplus_winrt)
auto file_handle = (HANDLE)_get_osfhandle(_fileno(f));
if (!::SetHandleInformation(file_handle, HANDLE_FLAG_INHERIT, 0))
throw spdlog_ex("SetHandleInformation failed", errno);
#endif
#else
auto fd = fileno(f);
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
{
throw spdlog_ex("fcntl with FD_CLOEXEC failed", errno);
}
#endif
}
// fopen_s on non windows for writing
SPDLOG_INLINE bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode)
{
#ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES
*fp = _wfsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
#else
*fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
#endif
#else // unix
*fp = fopen((filename.c_str()), mode.c_str());
#endif
#ifdef SPDLOG_PREVENT_CHILD_FD
if (*fp != nullptr)
{
prevent_child_fd(*fp);
}
#endif
return *fp == nullptr;
}
SPDLOG_INLINE int remove(const filename_t &filename) SPDLOG_NOEXCEPT
{
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
return _wremove(filename.c_str());
#else
return std::remove(filename.c_str());
#endif
}
SPDLOG_INLINE int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT
{
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
return _wrename(filename1.c_str(), filename2.c_str());
#else
return std::rename(filename1.c_str(), filename2.c_str());
#endif
}
// Return if file exists
SPDLOG_INLINE bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT
{
#ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES
auto attribs = GetFileAttributesW(filename.c_str());
#else
auto attribs = GetFileAttributesA(filename.c_str());
#endif
return (attribs != INVALID_FILE_ATTRIBUTES && !(attribs & FILE_ATTRIBUTE_DIRECTORY));
#else // common linux/unix all have the stat system call
struct stat buffer;
return (::stat(filename.c_str(), &buffer) == 0);
#endif
}
// Return file size according to open FILE* object
SPDLOG_INLINE size_t filesize(FILE *f)
{
if (f == nullptr)
{
throw spdlog_ex("Failed getting file size. fd is null");
}
#if defined(_WIN32) && !defined(__CYGWIN__)
int fd = _fileno(f);
#if _WIN64 // 64 bits
__int64 ret = _filelengthi64(fd);
if (ret >= 0)
{
return static_cast<size_t>(ret);
}
#else // windows 32 bits
long ret = _filelength(fd);
if (ret >= 0)
{
return static_cast<size_t>(ret);
}
#endif
#else // unix
int fd = fileno(f);
// 64 bits(but not in osx or cygwin, where fstat64 is deprecated)
#if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__)
struct stat64 st;
if (fstat64(fd, &st) == 0)
{
return static_cast<size_t>(st.st_size);
}
#else // unix 32 bits or cygwin
struct stat st;
if (::fstat(fd, &st) == 0)
{
return static_cast<size_t>(st.st_size);
}
#endif
#endif
throw spdlog_ex("Failed getting file size from fd", errno);
}
// Return utc offset in minutes or throw spdlog_ex on failure
SPDLOG_INLINE int utc_minutes_offset(const std::tm &tm)
{
#ifdef _WIN32
#if _WIN32_WINNT < _WIN32_WINNT_WS08
TIME_ZONE_INFORMATION tzinfo;
auto rv = GetTimeZoneInformation(&tzinfo);
#else
DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
auto rv = GetDynamicTimeZoneInformation(&tzinfo);
#endif
if (rv == TIME_ZONE_ID_INVALID)
throw spdlog::spdlog_ex("Failed getting timezone info. ", errno);
int offset = -tzinfo.Bias;
if (tm.tm_isdst)
{
offset -= tzinfo.DaylightBias;
}
else
{
offset -= tzinfo.StandardBias;
}
return offset;
#else
#if defined(sun) || defined(__sun) || defined(_AIX)
// 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
struct helper
{
static long int calculate_gmt_offset(const std::tm &localtm = details::os::localtime(), const std::tm &gmtm = details::os::gmtime())
{
int local_year = localtm.tm_year + (1900 - 1);
int gmt_year = gmtm.tm_year + (1900 - 1);
long int days = (
// difference in day of year
localtm.tm_yday -
gmtm.tm_yday
// + intervening leap days
+ ((local_year >> 2) - (gmt_year >> 2)) - (local_year / 100 - gmt_year / 100) +
((local_year / 100 >> 2) - (gmt_year / 100 >> 2))
// + difference in years * 365 */
+ (long int)(local_year - gmt_year) * 365);
long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour);
long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min);
long int secs = (60 * mins) + (localtm.tm_sec - gmtm.tm_sec);
return secs;
}
};
auto offset_seconds = helper::calculate_gmt_offset(tm);
#else
auto offset_seconds = tm.tm_gmtoff;
#endif
return static_cast<int>(offset_seconds / 60);
#endif
}
// Return current thread id as size_t
// It exists because the std::this_thread::get_id() is much slower(especially
// under VS 2013)
SPDLOG_INLINE size_t _thread_id() SPDLOG_NOEXCEPT
{
#ifdef _WIN32
return static_cast<size_t>(::GetCurrentThreadId());
#elif __linux__
#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
#define SYS_gettid __NR_gettid
#endif
return static_cast<size_t>(syscall(SYS_gettid));
#elif __FreeBSD__
long tid;
thr_self(&tid);
return static_cast<size_t>(tid);
#elif __APPLE__
uint64_t tid;
pthread_threadid_np(nullptr, &tid);
return static_cast<size_t>(tid);
#else // Default to standard C++11 (other Unix)
return static_cast<size_t>(std::hash<std::thread::id>()(std::this_thread::get_id()));
#endif
}
// Return current thread id as size_t (from thread local storage)
SPDLOG_INLINE size_t thread_id() SPDLOG_NOEXCEPT
{
#if defined(SPDLOG_NO_TLS)
return _thread_id();
#else // cache thread id in tls
static thread_local const size_t tid = _thread_id();
return tid;
#endif
}
// This is avoid msvc issue in sleep_for that happens if the clock changes.
// See https://github.com/gabime/spdlog/issues/609
SPDLOG_INLINE void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT
{
#if defined(_WIN32)
::Sleep(milliseconds);
#else
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
#endif
}
// wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined)
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) SPDLOG_NOEXCEPT
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> c;
return c.to_bytes(filename);
}
#else
SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) SPDLOG_NOEXCEPT
{
return filename;
}
#endif
SPDLOG_INLINE int pid() SPDLOG_NOEXCEPT
{
#ifdef _WIN32
return static_cast<int>(::GetCurrentProcessId());
#else
return static_cast<int>(::getpid());
#endif
}
// Determine if the terminal supports colors
// Source: https://github.com/agauniyal/rang/
SPDLOG_INLINE bool is_color_terminal() SPDLOG_NOEXCEPT
{
#ifdef _WIN32
return true;
#else
static constexpr const char *Terms[] = {
"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"};
const char *env_p = std::getenv("TERM");
if (env_p == nullptr)
{
return false;
}
static const bool result =
std::any_of(std::begin(Terms), std::end(Terms), [&](const char *term) { return std::strstr(env_p, term) != nullptr; });
return result;
#endif
}
// Detrmine if the terminal attached
// Source: https://github.com/agauniyal/rang/
SPDLOG_INLINE bool in_terminal(FILE *file) SPDLOG_NOEXCEPT
{
#ifdef _WIN32
return _isatty(_fileno(file)) != 0;
#else
return isatty(fileno(file)) != 0;
#endif
}
#if defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) && defined(_WIN32)
SPDLOG_INLINE void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target)
{
int wbuf_size = static_cast<int>(wbuf.size());
if (wbuf_size == 0)
{
return;
}
auto result_size = ::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), wbuf_size, NULL, 0, NULL, NULL);
if (result_size > 0)
{
target.resize(result_size);
::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), wbuf_size, &target.data()[0], result_size, NULL, NULL);
}
else
{
throw spdlog::spdlog_ex(fmt::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError()));
}
}
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT) && _WIN32
} // namespace os
} // namespace details
} // namespace spdlog

View File

@ -1,112 +1,24 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
#include "../common.h" #include "spdlog/common.h"
#include <ctime> // std::time_t
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <functional>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <thread>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX // prevent windows redefining min/max
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <io.h> // _get_osfhandle and _isatty support
#include <process.h> // _get_pid support
#include <windows.h>
#ifdef __MINGW32__
#include <share.h>
#endif
#else // unix
#include <fcntl.h>
#include <unistd.h>
#ifdef __linux__
#include <sys/syscall.h> //Use gettid() syscall under linux to get thread id
#elif __FreeBSD__
#include <sys/thr.h> //Use thr_self() syscall under FreeBSD to get thread id
#endif
#endif // unix
#ifndef __has_feature // Clang - feature checking macros.
#define __has_feature(x) 0 // Compatibility with non-clang compilers.
#endif
namespace spdlog { namespace spdlog {
namespace details { namespace details {
namespace os { namespace os {
inline spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT;
{
#if defined __linux__ && defined SPDLOG_CLOCK_COARSE std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT;
timespec ts;
::clock_gettime(CLOCK_REALTIME_COARSE, &ts);
return std::chrono::time_point<log_clock, typename log_clock::duration>(
std::chrono::duration_cast<typename log_clock::duration>(std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec)));
#else std::tm localtime() SPDLOG_NOEXCEPT;
return log_clock::now();
#endif
}
inline std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
{
#ifdef _WIN32 std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT;
std::tm tm;
localtime_s(&tm, &time_tt);
#else
std::tm tm;
localtime_r(&time_tt, &tm);
#endif
return tm;
}
inline std::tm localtime() SPDLOG_NOEXCEPT std::tm gmtime() SPDLOG_NOEXCEPT;
{
std::time_t now_t = time(nullptr);
return localtime(now_t);
}
inline std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
{
#ifdef _WIN32
std::tm tm;
gmtime_s(&tm, &time_tt);
#else
std::tm tm;
gmtime_r(&time_tt, &tm);
#endif
return tm;
}
inline std::tm gmtime() SPDLOG_NOEXCEPT
{
std::time_t now_t = time(nullptr);
return gmtime(now_t);
}
// eol definition // eol definition
#if !defined(SPDLOG_EOL) #if !defined(SPDLOG_EOL)
@ -121,301 +33,61 @@ SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL;
// folder separator // folder separator
#ifdef _WIN32 #ifdef _WIN32
SPDLOG_CONSTEXPR static const char folder_sep = '\\'; const char folder_sep = '\\';
#else #else
SPDLOG_CONSTEXPR static const char folder_sep = '/'; SPDLOG_CONSTEXPR static const char folder_sep = '/';
#endif #endif
inline void prevent_child_fd(FILE *f) void prevent_child_fd(FILE *f);
{
#ifdef _WIN32
#if !defined(__cplusplus_winrt)
auto file_handle = (HANDLE)_get_osfhandle(_fileno(f));
if (!::SetHandleInformation(file_handle, HANDLE_FLAG_INHERIT, 0))
throw spdlog_ex("SetHandleInformation failed", errno);
#endif
#else
auto fd = fileno(f);
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
{
throw spdlog_ex("fcntl with FD_CLOEXEC failed", errno);
}
#endif
}
// fopen_s on non windows for writing // fopen_s on non windows for writing
inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode) bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode);
{
#ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES
*fp = _wfsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
#else
*fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
#endif
#else // unix
*fp = fopen((filename.c_str()), mode.c_str());
#endif
#ifdef SPDLOG_PREVENT_CHILD_FD int remove(const filename_t &filename) SPDLOG_NOEXCEPT;
if (*fp != nullptr)
{
prevent_child_fd(*fp);
}
#endif
return *fp == nullptr;
}
inline int remove(const filename_t &filename) SPDLOG_NOEXCEPT int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT;
{
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
return _wremove(filename.c_str());
#else
return std::remove(filename.c_str());
#endif
}
inline int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT
{
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
return _wrename(filename1.c_str(), filename2.c_str());
#else
return std::rename(filename1.c_str(), filename2.c_str());
#endif
}
// Return if file exists // Return if file exists
inline bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT;
{
#ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES
auto attribs = GetFileAttributesW(filename.c_str());
#else
auto attribs = GetFileAttributesA(filename.c_str());
#endif
return (attribs != INVALID_FILE_ATTRIBUTES && !(attribs & FILE_ATTRIBUTE_DIRECTORY));
#else // common linux/unix all have the stat system call
struct stat buffer;
return (::stat(filename.c_str(), &buffer) == 0);
#endif
}
// Return file size according to open FILE* object // Return file size according to open FILE* object
inline size_t filesize(FILE *f) size_t filesize(FILE *f);
{
if (f == nullptr)
{
throw spdlog_ex("Failed getting file size. fd is null");
}
#if defined(_WIN32) && !defined(__CYGWIN__)
int fd = _fileno(f);
#if _WIN64 // 64 bits
__int64 ret = _filelengthi64(fd);
if (ret >= 0)
{
return static_cast<size_t>(ret);
}
#else // windows 32 bits
long ret = _filelength(fd);
if (ret >= 0)
{
return static_cast<size_t>(ret);
}
#endif
#else // unix
int fd = fileno(f);
// 64 bits(but not in osx or cygwin, where fstat64 is deprecated)
#if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__)
struct stat64 st;
if (::fstat64(fd, &st) == 0)
{
return static_cast<size_t>(st.st_size);
}
#else // unix 32 bits or cygwin
struct stat st;
if (::fstat(fd, &st) == 0)
{
return static_cast<size_t>(st.st_size);
}
#endif
#endif
throw spdlog_ex("Failed getting file size from fd", errno);
}
// Return utc offset in minutes or throw spdlog_ex on failure // Return utc offset in minutes or throw spdlog_ex on failure
inline int utc_minutes_offset(const std::tm &tm = details::os::localtime()) int utc_minutes_offset(const std::tm &tm = details::os::localtime());
{
#ifdef _WIN32
#if _WIN32_WINNT < _WIN32_WINNT_WS08
TIME_ZONE_INFORMATION tzinfo;
auto rv = GetTimeZoneInformation(&tzinfo);
#else
DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
auto rv = GetDynamicTimeZoneInformation(&tzinfo);
#endif
if (rv == TIME_ZONE_ID_INVALID)
throw spdlog::spdlog_ex("Failed getting timezone info. ", errno);
int offset = -tzinfo.Bias;
if (tm.tm_isdst)
{
offset -= tzinfo.DaylightBias;
}
else
{
offset -= tzinfo.StandardBias;
}
return offset;
#else
#if defined(sun) || defined(__sun) || defined(_AIX)
// 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
struct helper
{
static long int calculate_gmt_offset(const std::tm &localtm = details::os::localtime(), const std::tm &gmtm = details::os::gmtime())
{
int local_year = localtm.tm_year + (1900 - 1);
int gmt_year = gmtm.tm_year + (1900 - 1);
long int days = (
// difference in day of year
localtm.tm_yday -
gmtm.tm_yday
// + intervening leap days
+ ((local_year >> 2) - (gmt_year >> 2)) - (local_year / 100 - gmt_year / 100) +
((local_year / 100 >> 2) - (gmt_year / 100 >> 2))
// + difference in years * 365 */
+ (long int)(local_year - gmt_year) * 365);
long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour);
long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min);
long int secs = (60 * mins) + (localtm.tm_sec - gmtm.tm_sec);
return secs;
}
};
auto offset_seconds = helper::calculate_gmt_offset(tm);
#else
auto offset_seconds = tm.tm_gmtoff;
#endif
return static_cast<int>(offset_seconds / 60);
#endif
}
// Return current thread id as size_t // Return current thread id as size_t
// It exists because the std::this_thread::get_id() is much slower(especially // It exists because the std::this_thread::get_id() is much slower(especially
// under VS 2013) // under VS 2013)
inline size_t _thread_id() SPDLOG_NOEXCEPT size_t _thread_id() SPDLOG_NOEXCEPT;
{
#ifdef _WIN32
return static_cast<size_t>(::GetCurrentThreadId());
#elif __linux__
#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
#define SYS_gettid __NR_gettid
#endif
return static_cast<size_t>(syscall(SYS_gettid));
#elif __FreeBSD__
long tid;
thr_self(&tid);
return static_cast<size_t>(tid);
#elif __APPLE__
uint64_t tid;
pthread_threadid_np(nullptr, &tid);
return static_cast<size_t>(tid);
#else // Default to standard C++11 (other Unix)
return static_cast<size_t>(std::hash<std::thread::id>()(std::this_thread::get_id()));
#endif
}
// Return current thread id as size_t (from thread local storage) // Return current thread id as size_t (from thread local storage)
inline size_t thread_id() SPDLOG_NOEXCEPT size_t thread_id() SPDLOG_NOEXCEPT;
{
#if defined(SPDLOG_NO_TLS)
return _thread_id();
#else // cache thread id in tls
static thread_local const size_t tid = _thread_id();
return tid;
#endif
}
// This is avoid msvc issue in sleep_for that happens if the clock changes. // This is avoid msvc issue in sleep_for that happens if the clock changes.
// See https://github.com/gabime/spdlog/issues/609 // See https://github.com/gabime/spdlog/issues/609
inline void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT;
{
#if defined(_WIN32)
::Sleep(milliseconds);
#else
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
#endif
}
// wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined) std::string filename_to_str(const filename_t &filename) SPDLOG_NOEXCEPT;
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
#define SPDLOG_FILENAME_T(s) L##s
inline std::string filename_to_str(const filename_t &filename)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> c;
return c.to_bytes(filename);
}
#else
#define SPDLOG_FILENAME_T(s) s
inline std::string filename_to_str(const filename_t &filename)
{
return filename;
}
#endif
inline int pid() int pid() SPDLOG_NOEXCEPT;
{
#ifdef _WIN32
return static_cast<int>(::GetCurrentProcessId());
#else
return static_cast<int>(::getpid());
#endif
}
// Determine if the terminal supports colors // Determine if the terminal supports colors
// Source: https://github.com/agauniyal/rang/ // Source: https://github.com/agauniyal/rang/
inline bool is_color_terminal() SPDLOG_NOEXCEPT bool is_color_terminal() SPDLOG_NOEXCEPT;
{
#ifdef _WIN32
return true;
#else
static constexpr const char *Terms[] = {
"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"};
const char *env_p = std::getenv("TERM");
if (env_p == nullptr)
{
return false;
}
static const bool result =
std::any_of(std::begin(Terms), std::end(Terms), [&](const char *term) { return std::strstr(env_p, term) != nullptr; });
return result;
#endif
}
// Detrmine if the terminal attached // Detrmine if the terminal attached
// Source: https://github.com/agauniyal/rang/ // Source: https://github.com/agauniyal/rang/
inline bool in_terminal(FILE *file) SPDLOG_NOEXCEPT bool in_terminal(FILE *file) SPDLOG_NOEXCEPT;
{
#ifdef _WIN32 #if defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) && defined(_WIN32)
return _isatty(_fileno(file)) != 0; void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target);
#else
return isatty(fileno(file)) != 0;
#endif #endif
}
} // namespace os } // namespace os
} // namespace details } // namespace details
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "os-inl.h"
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,49 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/details/periodic_worker.h"
#endif
namespace spdlog {
namespace details {
SPDLOG_INLINE periodic_worker::periodic_worker(const std::function<void()> &callback_fun, std::chrono::seconds interval)
{
active_ = (interval > std::chrono::seconds::zero());
if (!active_)
{
return;
}
worker_thread_ = std::thread([this, callback_fun, interval]() {
for (;;)
{
std::unique_lock<std::mutex> lock(this->mutex_);
if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; }))
{
return; // active_ == false, so exit this thread
}
callback_fun();
}
});
}
// stop the worker thread and join it
SPDLOG_INLINE periodic_worker::~periodic_worker()
{
if (worker_thread_.joinable())
{
{
std::lock_guard<std::mutex> lock(mutex_);
active_ = false;
}
cv_.notify_one();
worker_thread_.join();
}
}
} // namespace details
} // namespace spdlog

View File

@ -1,8 +1,5 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
//
// Copyright(c) 2018 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -23,43 +20,11 @@ namespace details {
class periodic_worker class periodic_worker
{ {
public: public:
periodic_worker(const 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());
if (!active_)
{
return;
}
worker_thread_ = std::thread([this, callback_fun, interval]() {
for (;;)
{
std::unique_lock<std::mutex> lock(this->mutex_);
if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; }))
{
return; // active_ == false, so exit this thread
}
callback_fun();
}
});
}
periodic_worker(const periodic_worker &) = delete; periodic_worker(const periodic_worker &) = delete;
periodic_worker &operator=(const periodic_worker &) = delete; periodic_worker &operator=(const periodic_worker &) = delete;
// stop the worker thread and join it // stop the worker thread and join it
~periodic_worker() ~periodic_worker();
{
if (worker_thread_.joinable())
{
{
std::lock_guard<std::mutex> lock(mutex_);
active_ = false;
}
cv_.notify_one();
worker_thread_.join();
}
}
private: private:
bool active_; bool active_;
@ -69,3 +34,7 @@ private:
}; };
} // namespace details } // namespace details
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "periodic_worker-inl.h"
#endif

View File

@ -0,0 +1,259 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/details/registry.h"
#endif
#include "spdlog/common.h"
#include "spdlog/details/periodic_worker.h"
#include "spdlog/logger.h"
#include "spdlog/details/pattern_formatter.h"
#ifndef SPDLOG_DISABLE_DEFAULT_LOGGER
// support for the default stdout color logger
#ifdef _WIN32
#include "spdlog/sinks/wincolor_sink.h"
#else
#include "spdlog/sinks/ansicolor_sink.h"
#endif
#endif // SPDLOG_DISABLE_DEFAULT_LOGGER
#include <chrono>
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
namespace spdlog {
namespace details {
SPDLOG_INLINE registry::registry()
: formatter_(new pattern_formatter())
, level_(spdlog::logger::default_level())
{
#ifndef SPDLOG_DISABLE_DEFAULT_LOGGER
// create default logger (ansicolor_stdout_sink_mt or wincolor_stdout_sink_mt in windows).
#ifdef _WIN32
auto color_sink = std::make_shared<sinks::wincolor_stdout_sink_mt>();
#else
auto color_sink = std::make_shared<sinks::ansicolor_stdout_sink_mt>();
#endif
const char *default_logger_name = "";
default_logger_ = std::make_shared<spdlog::logger>(default_logger_name, std::move(color_sink));
loggers_[default_logger_name] = default_logger_;
#endif // SPDLOG_DISABLE_DEFAULT_LOGGER
}
SPDLOG_INLINE void registry::register_logger(std::shared_ptr<logger> new_logger)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
register_logger_(std::move(new_logger));
}
SPDLOG_INLINE void registry::initialize_logger(std::shared_ptr<logger> new_logger)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
new_logger->set_formatter(formatter_->clone());
if (err_handler_)
{
new_logger->set_error_handler(err_handler_);
}
new_logger->set_level(level_);
new_logger->flush_on(flush_level_);
if (automatic_registration_)
{
register_logger_(std::move(new_logger));
}
}
SPDLOG_INLINE std::shared_ptr<logger> registry::get(const std::string &logger_name)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
auto found = loggers_.find(logger_name);
return found == loggers_.end() ? nullptr : found->second;
}
SPDLOG_INLINE std::shared_ptr<logger> registry::default_logger()
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
return default_logger_;
}
// Return raw ptr to the default logger.
// To be used directly by the spdlog default api (e.g. spdlog::info)
// This make the default API faster, but cannot be used concurrently with set_default_logger().
// e.g do not call set_default_logger() from one thread while calling spdlog::info() from another.
SPDLOG_INLINE logger *registry::get_default_raw()
{
return default_logger_.get();
}
// set default logger.
// default logger is stored in default_logger_ (for faster retrieval) and in the loggers_ map.
SPDLOG_INLINE void registry::set_default_logger(std::shared_ptr<logger> new_default_logger)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
// remove previous default logger from the map
if (default_logger_ != nullptr)
{
loggers_.erase(default_logger_->name());
}
if (new_default_logger != nullptr)
{
loggers_[new_default_logger->name()] = new_default_logger;
}
default_logger_ = std::move(new_default_logger);
}
SPDLOG_INLINE void registry::set_tp(std::shared_ptr<thread_pool> tp)
{
std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
tp_ = std::move(tp);
}
SPDLOG_INLINE std::shared_ptr<thread_pool> registry::get_tp()
{
std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
return tp_;
}
// Set global formatter. Each sink in each logger will get a clone of this object
SPDLOG_INLINE void registry::set_formatter(std::unique_ptr<formatter> formatter)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
formatter_ = std::move(formatter);
for (auto &l : loggers_)
{
l.second->set_formatter(formatter_->clone());
}
}
SPDLOG_INLINE void registry::set_level(level::level_enum log_level)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
l.second->set_level(log_level);
}
level_ = log_level;
}
SPDLOG_INLINE void registry::flush_on(level::level_enum log_level)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
l.second->flush_on(log_level);
}
flush_level_ = log_level;
}
SPDLOG_INLINE void registry::flush_every(std::chrono::seconds interval)
{
std::lock_guard<std::mutex> lock(flusher_mutex_);
std::function<void()> clbk = std::bind(&registry::flush_all, this);
periodic_flusher_ = details::make_unique<periodic_worker>(clbk, interval);
}
SPDLOG_INLINE void registry::set_error_handler(void (*handler)(const std::string &msg))
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
l.second->set_error_handler(handler);
}
err_handler_ = handler;
}
SPDLOG_INLINE void registry::apply_all(const std::function<void(const std::shared_ptr<logger>)> &fun)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
fun(l.second);
}
}
SPDLOG_INLINE void registry::flush_all()
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
l.second->flush();
}
}
SPDLOG_INLINE void registry::drop(const std::string &logger_name)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
loggers_.erase(logger_name);
if (default_logger_ && default_logger_->name() == logger_name)
{
default_logger_.reset();
}
}
SPDLOG_INLINE void registry::drop_all()
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
loggers_.clear();
default_logger_.reset();
}
// clean all resources and threads started by the registry
SPDLOG_INLINE void registry::shutdown()
{
{
std::lock_guard<std::mutex> lock(flusher_mutex_);
periodic_flusher_.reset();
}
drop_all();
{
std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
tp_.reset();
}
}
SPDLOG_INLINE std::recursive_mutex &registry::tp_mutex()
{
return tp_mutex_;
}
SPDLOG_INLINE void registry::set_automatic_registration(bool automatic_regsistration)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
automatic_registration_ = automatic_regsistration;
}
SPDLOG_INLINE registry &registry::instance()
{
static registry s_instance;
return s_instance;
}
SPDLOG_INLINE void registry::throw_if_exists_(const std::string &logger_name)
{
if (loggers_.find(logger_name) != loggers_.end())
{
throw spdlog_ex("logger with name '" + logger_name + "' already exists");
}
}
SPDLOG_INLINE void registry::register_logger_(std::shared_ptr<logger> new_logger)
{
auto logger_name = new_logger->name();
throw_if_exists_(logger_name);
loggers_[logger_name] = std::move(new_logger);
}
} // namespace details
} // namespace spdlog

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -11,27 +9,20 @@
// This class is thread safe // This class is thread safe
#include "spdlog/common.h" #include "spdlog/common.h"
#include "spdlog/details/periodic_worker.h"
#include "spdlog/logger.h"
#ifndef SPDLOG_DISABLE_DEFAULT_LOGGER
// support for the default stdout color logger
#ifdef _WIN32
#include "spdlog/sinks/wincolor_sink.h"
#else
#include "spdlog/sinks/ansicolor_sink.h"
#endif
#endif // SPDLOG_DISABLE_DEFAULT_LOGGER
#include <chrono> #include <chrono>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <mutex>
namespace spdlog { namespace spdlog {
class logger;
namespace details { namespace details {
class thread_pool; class thread_pool;
class periodic_worker;
class registry class registry
{ {
@ -39,242 +30,66 @@ public:
registry(const registry &) = delete; registry(const registry &) = delete;
registry &operator=(const registry &) = delete; registry &operator=(const registry &) = delete;
void register_logger(std::shared_ptr<logger> new_logger) void register_logger(std::shared_ptr<logger> new_logger);
{ void initialize_logger(std::shared_ptr<logger> new_logger);
std::lock_guard<std::mutex> lock(logger_map_mutex_); std::shared_ptr<logger> get(const std::string &logger_name);
register_logger_(std::move(new_logger)); std::shared_ptr<logger> default_logger();
}
void initialize_logger(std::shared_ptr<logger> new_logger)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
new_logger->set_formatter(formatter_->clone());
if (err_handler_)
{
new_logger->set_error_handler(err_handler_);
}
new_logger->set_level(level_);
new_logger->flush_on(flush_level_);
if (automatic_registration_)
{
register_logger_(std::move(new_logger));
}
}
std::shared_ptr<logger> get(const std::string &logger_name)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
auto found = loggers_.find(logger_name);
return found == loggers_.end() ? nullptr : found->second;
}
std::shared_ptr<logger> default_logger()
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
return default_logger_;
}
// Return raw ptr to the default logger. // Return raw ptr to the default logger.
// To be used directly by the spdlog default api (e.g. spdlog::info) // To be used directly by the spdlog default api (e.g. spdlog::info)
// This make the default API faster, but cannot be used concurrently with set_default_logger(). // This make the default API faster, but cannot be used concurrently with set_default_logger().
// e.g do not call set_default_logger() from one thread while calling spdlog::info() from another. // e.g do not call set_default_logger() from one thread while calling spdlog::info() from another.
logger *get_default_raw() logger *get_default_raw();
{
return default_logger_.get();
}
// set default logger. // set default logger.
// default logger is stored in default_logger_ (for faster retrieval) and in the loggers_ map. // default logger is stored in default_logger_ (for faster retrieval) and in the loggers_ map.
void set_default_logger(std::shared_ptr<logger> new_default_logger) void set_default_logger(std::shared_ptr<logger> new_default_logger);
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
// remove previous default logger from the map
if (default_logger_ != nullptr)
{
loggers_.erase(default_logger_->name());
}
if (new_default_logger != nullptr)
{
loggers_[new_default_logger->name()] = new_default_logger;
}
default_logger_ = std::move(new_default_logger);
}
void set_tp(std::shared_ptr<thread_pool> tp) void set_tp(std::shared_ptr<thread_pool> tp);
{
std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
tp_ = std::move(tp);
}
std::shared_ptr<thread_pool> get_tp() std::shared_ptr<thread_pool> get_tp();
{
std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
return tp_;
}
// Set global formatter. Each sink in each logger will get a clone of this object // Set global formatter. Each sink in each logger will get a clone of this object
void set_formatter(std::unique_ptr<formatter> formatter) void set_formatter(std::unique_ptr<formatter> formatter);
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
formatter_ = std::move(formatter);
for (auto &l : loggers_)
{
l.second->set_formatter(formatter_->clone());
}
}
void set_level(level::level_enum log_level) void set_level(level::level_enum log_level);
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
l.second->set_level(log_level);
}
level_ = log_level;
}
void flush_on(level::level_enum log_level) void flush_on(level::level_enum log_level);
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
l.second->flush_on(log_level);
}
flush_level_ = log_level;
}
void flush_every(std::chrono::seconds interval) void flush_every(std::chrono::seconds interval);
{
std::lock_guard<std::mutex> lock(flusher_mutex_);
std::function<void()> clbk = std::bind(&registry::flush_all, this);
periodic_flusher_ = details::make_unique<periodic_worker>(clbk, interval);
}
void set_error_handler(log_err_handler handler) void set_error_handler(void (*handler)(const std::string &msg));
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
l.second->set_error_handler(handler);
}
err_handler_ = handler;
}
void apply_all(const std::function<void(const 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_);
for (auto &l : loggers_)
{
fun(l.second);
}
}
void flush_all() void flush_all();
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
l.second->flush();
}
}
void drop(const std::string &logger_name) void drop(const std::string &logger_name);
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
loggers_.erase(logger_name);
if (default_logger_ && default_logger_->name() == logger_name)
{
default_logger_.reset();
}
}
void drop_all() void drop_all();
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
loggers_.clear();
default_logger_.reset();
}
// clean all resources and threads started by the registry // clean all resources and threads started by the registry
void shutdown() void shutdown();
{
{
std::lock_guard<std::mutex> lock(flusher_mutex_);
periodic_flusher_.reset();
}
drop_all(); std::recursive_mutex &tp_mutex();
{ void set_automatic_registration(bool automatic_regsistration);
std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
tp_.reset();
}
}
std::recursive_mutex &tp_mutex() static registry &instance();
{
return tp_mutex_;
}
void set_automatic_registration(bool automatic_regsistration)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
automatic_registration_ = automatic_regsistration;
}
static registry &instance()
{
static registry s_instance;
return s_instance;
}
private: private:
registry() registry();
: formatter_(new pattern_formatter())
{
#ifndef SPDLOG_DISABLE_DEFAULT_LOGGER
// create default logger (ansicolor_stdout_sink_mt or wincolor_stdout_sink_mt in windows).
#ifdef _WIN32
auto color_sink = std::make_shared<sinks::wincolor_stdout_sink_mt>();
#else
auto color_sink = std::make_shared<sinks::ansicolor_stdout_sink_mt>();
#endif
const char *default_logger_name = "";
default_logger_ = std::make_shared<spdlog::logger>(default_logger_name, std::move(color_sink));
loggers_[default_logger_name] = default_logger_;
#endif // SPDLOG_DISABLE_DEFAULT_LOGGER
}
~registry() = default; ~registry() = default;
void throw_if_exists_(const std::string &logger_name) void throw_if_exists_(const std::string &logger_name);
{ void register_logger_(std::shared_ptr<logger> new_logger);
if (loggers_.find(logger_name) != loggers_.end())
{
throw spdlog_ex("logger with name '" + logger_name + "' already exists");
}
}
void register_logger_(std::shared_ptr<logger> new_logger)
{
auto logger_name = new_logger->name();
throw_if_exists_(logger_name);
loggers_[logger_name] = std::move(new_logger);
}
std::mutex logger_map_mutex_, flusher_mutex_; std::mutex logger_map_mutex_, flusher_mutex_;
std::recursive_mutex tp_mutex_; std::recursive_mutex tp_mutex_;
std::unordered_map<std::string, std::shared_ptr<logger>> loggers_; std::unordered_map<std::string, std::shared_ptr<logger>> loggers_;
std::unique_ptr<formatter> formatter_; std::unique_ptr<formatter> formatter_;
level::level_enum level_ = spdlog::logger::default_level(); level::level_enum level_ = level::info;
level::level_enum flush_level_ = level::off; level::level_enum flush_level_ = level::off;
log_err_handler err_handler_; void (*err_handler_)(const std::string &msg);
std::shared_ptr<thread_pool> tp_; std::shared_ptr<thread_pool> tp_;
std::unique_ptr<periodic_worker> periodic_flusher_; std::unique_ptr<periodic_worker> periodic_flusher_;
std::shared_ptr<logger> default_logger_; std::shared_ptr<logger> default_logger_;
@ -283,3 +98,7 @@ private:
} // namespace details } // namespace details
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "registry-inl.h"
#endif

View File

@ -0,0 +1,116 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/details/thread_pool.h"
#endif
#include "spdlog/common.h"
namespace spdlog {
namespace details {
SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n)
: q_(q_max_items)
{
if (threads_n == 0 || threads_n > 1000)
{
throw spdlog_ex("spdlog::thread_pool(): invalid threads_n param (valid "
"range is 1-1000)");
}
for (size_t i = 0; i < threads_n; i++)
{
threads_.emplace_back(&thread_pool::worker_loop_, this);
}
}
// message all threads to terminate gracefully join them
SPDLOG_INLINE thread_pool::~thread_pool()
{
try
{
for (size_t i = 0; i < threads_.size(); i++)
{
post_async_msg_(async_msg(async_msg_type::terminate), async_overflow_policy::block);
}
for (auto &t : threads_)
{
t.join();
}
}
catch (...)
{}
}
void SPDLOG_INLINE thread_pool::post_log(async_logger_ptr &&worker_ptr, details::log_msg &msg, async_overflow_policy overflow_policy)
{
async_msg async_m(std::move(worker_ptr), async_msg_type::log, msg);
post_async_msg_(std::move(async_m), overflow_policy);
}
void SPDLOG_INLINE thread_pool::post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy overflow_policy)
{
post_async_msg_(async_msg(std::move(worker_ptr), async_msg_type::flush), overflow_policy);
}
size_t SPDLOG_INLINE thread_pool::overrun_counter()
{
return q_.overrun_counter();
}
void SPDLOG_INLINE thread_pool::post_async_msg_(async_msg &&new_msg, async_overflow_policy overflow_policy)
{
if (overflow_policy == async_overflow_policy::block)
{
q_.enqueue(std::move(new_msg));
}
else
{
q_.enqueue_nowait(std::move(new_msg));
}
}
void SPDLOG_INLINE thread_pool::worker_loop_()
{
while (process_next_msg_()) {};
}
// process next message in the queue
// return true if this thread should still be active (while no terminate msg
// was received)
bool SPDLOG_INLINE thread_pool::process_next_msg_()
{
async_msg incoming_async_msg;
bool dequeued = q_.dequeue_for(incoming_async_msg, std::chrono::seconds(10));
if (!dequeued)
{
return true;
}
switch (incoming_async_msg.msg_type)
{
case async_msg_type::log:
{
auto msg = incoming_async_msg.to_log_msg();
incoming_async_msg.worker_ptr->backend_log_(msg);
return true;
}
case async_msg_type::flush:
{
incoming_async_msg.worker_ptr->backend_flush_();
return true;
}
case async_msg_type::terminate:
{
return false;
}
}
assert(false && "Unexpected async_msg_type");
return true;
}
} // namespace details
} // namespace spdlog

View File

@ -1,6 +1,8 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once #pragma once
#include "spdlog/details/fmt_helper.h"
#include "spdlog/details/log_msg.h" #include "spdlog/details/log_msg.h"
#include "spdlog/details/mpmc_blocking_q.h" #include "spdlog/details/mpmc_blocking_q.h"
#include "spdlog/details/os.h" #include "spdlog/details/os.h"
@ -11,6 +13,8 @@
#include <vector> #include <vector>
namespace spdlog { namespace spdlog {
class async_logger;
namespace details { namespace details {
using async_logger_ptr = std::shared_ptr<spdlog::async_logger>; using async_logger_ptr = std::shared_ptr<spdlog::async_logger>;
@ -52,8 +56,7 @@ struct async_msg
msg_id(other.msg_id), msg_id(other.msg_id),
source(other.source), source(other.source),
worker_ptr(std::move(other.worker_ptr)) worker_ptr(std::move(other.worker_ptr))
{ {}
}
async_msg &operator=(async_msg &&other) SPDLOG_NOEXCEPT async_msg &operator=(async_msg &&other) SPDLOG_NOEXCEPT
{ {
@ -82,7 +85,7 @@ struct async_msg
, source(m.source) , source(m.source)
, worker_ptr(std::move(worker)) , worker_ptr(std::move(worker))
{ {
fmt_helper::append_string_view(m.payload, raw); raw.append(m.payload.data(), m.payload.data() + m.payload.size());
} }
async_msg(async_logger_ptr &&worker, async_msg_type the_type) async_msg(async_logger_ptr &&worker, async_msg_type the_type)
@ -93,13 +96,11 @@ struct async_msg
, msg_id(0) , msg_id(0)
, source() , source()
, worker_ptr(std::move(worker)) , worker_ptr(std::move(worker))
{ {}
}
explicit async_msg(async_msg_type the_type) explicit async_msg(async_msg_type the_type)
: async_msg(nullptr, the_type) : async_msg(nullptr, the_type)
{ {}
}
// copy into log_msg // copy into log_msg
log_msg to_log_msg() log_msg to_log_msg()
@ -121,118 +122,34 @@ public:
using item_type = async_msg; using item_type = async_msg;
using q_type = details::mpmc_blocking_queue<item_type>; using q_type = details::mpmc_blocking_queue<item_type>;
thread_pool(size_t q_max_items, size_t threads_n) thread_pool(size_t q_max_items, size_t threads_n);
: q_(q_max_items)
{
// std::cout << "thread_pool() q_size_bytes: " << q_size_bytes <<
// "\tthreads_n: " << threads_n << std::endl;
if (threads_n == 0 || threads_n > 1000)
{
throw spdlog_ex("spdlog::thread_pool(): invalid threads_n param (valid "
"range is 1-1000)");
}
for (size_t i = 0; i < threads_n; i++)
{
threads_.emplace_back(&thread_pool::worker_loop_, this);
}
}
// message all threads to terminate gracefully join them // message all threads to terminate gracefully join them
~thread_pool() ~thread_pool();
{
try
{
for (size_t i = 0; i < threads_.size(); i++)
{
post_async_msg_(async_msg(async_msg_type::terminate), async_overflow_policy::block);
}
for (auto &t : threads_)
{
t.join();
}
}
catch (...)
{
}
}
thread_pool(const thread_pool &) = delete; thread_pool(const thread_pool &) = delete;
thread_pool &operator=(thread_pool &&) = delete; thread_pool &operator=(thread_pool &&) = delete;
void post_log(async_logger_ptr &&worker_ptr, details::log_msg &msg, async_overflow_policy overflow_policy) void post_log(async_logger_ptr &&worker_ptr, details::log_msg &msg, async_overflow_policy overflow_policy);
{ void post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy overflow_policy);
async_msg async_m(std::move(worker_ptr), async_msg_type::log, msg); size_t overrun_counter();
post_async_msg_(std::move(async_m), overflow_policy);
}
void post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy overflow_policy)
{
post_async_msg_(async_msg(std::move(worker_ptr), async_msg_type::flush), overflow_policy);
}
size_t overrun_counter()
{
return q_.overrun_counter();
}
private: private:
q_type q_; q_type q_;
std::vector<std::thread> threads_; std::vector<std::thread> threads_;
void post_async_msg_(async_msg &&new_msg, async_overflow_policy overflow_policy) void post_async_msg_(async_msg &&new_msg, async_overflow_policy overflow_policy);
{ void worker_loop_();
if (overflow_policy == async_overflow_policy::block)
{
q_.enqueue(std::move(new_msg));
}
else
{
q_.enqueue_nowait(std::move(new_msg));
}
}
void worker_loop_()
{
while (process_next_msg_()) {};
}
// process next message in the queue // process next message in the queue
// return true if this thread should still be active (while no terminate msg // return true if this thread should still be active (while no terminate msg
// was received) // was received)
bool process_next_msg_() bool process_next_msg_();
{
async_msg incoming_async_msg;
bool dequeued = q_.dequeue_for(incoming_async_msg, std::chrono::seconds(10));
if (!dequeued)
{
return true;
}
switch (incoming_async_msg.msg_type)
{
case async_msg_type::log:
{
auto msg = incoming_async_msg.to_log_msg();
incoming_async_msg.worker_ptr->backend_log_(msg);
return true;
}
case async_msg_type::flush:
{
incoming_async_msg.worker_ptr->backend_flush_();
return true;
}
case async_msg_type::terminate:
{
return false;
}
}
assert(false && "Unexpected async_msg_type");
return true;
}
}; };
} // namespace details } // namespace details
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "thread_pool-inl.h"
#endif

View File

@ -31,8 +31,7 @@ public:
bytes_range(It range_begin, It range_end) bytes_range(It range_begin, It range_end)
: begin_(range_begin) : begin_(range_begin)
, end_(range_end) , end_(range_end)
{ {}
}
It begin() const It begin() const
{ {

View File

@ -11,15 +11,17 @@
// //
#if !defined(SPDLOG_FMT_EXTERNAL) #if !defined(SPDLOG_FMT_EXTERNAL)
#ifdef SPDLOG_HEADER_ONLY
#ifndef FMT_HEADER_ONLY #ifndef FMT_HEADER_ONLY
#define FMT_HEADER_ONLY #define FMT_HEADER_ONLY
#endif #endif
#endif
#ifndef FMT_USE_WINDOWS_H #ifndef FMT_USE_WINDOWS_H
#define FMT_USE_WINDOWS_H 0 #define FMT_USE_WINDOWS_H 0
#endif #endif
#include "bundled/core.h" #include "bundled/core.h"
#include "bundled/format.h" #include "bundled/format.h"
#else // external fmtlib #else // SPDLOG_FMT_EXTERNAL is defined - use external fmtlib
#include <fmt/core.h> #include "fmt/core.h"
#include <fmt/format.h> #include "fmt/format.h"
#endif #endif

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once

182
include/spdlog/logger-inl.h Normal file
View File

@ -0,0 +1,182 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/logger.h"
#endif
#include "spdlog/sinks/sink.h"
#include "spdlog/details/pattern_formatter.h"
namespace spdlog {
// public methods
SPDLOG_INLINE void logger::log(source_loc loc, level::level_enum lvl, const char *msg)
{
if (!should_log(lvl))
{
return;
}
try
{
details::log_msg log_msg(loc, &name_, lvl, string_view_t(msg));
sink_it_(log_msg);
}
catch (const std::exception &ex)
{
err_handler_(ex.what());
}
catch (...)
{
err_handler_("Unknown exception in logger");
}
}
SPDLOG_INLINE void logger::log(level::level_enum lvl, const char *msg)
{
log(source_loc{}, lvl, msg);
}
SPDLOG_INLINE bool logger::should_log(level::level_enum msg_level) const
{
return msg_level >= level_.load(std::memory_order_relaxed);
}
SPDLOG_INLINE void logger::set_level(level::level_enum log_level)
{
level_.store(log_level);
}
SPDLOG_INLINE level::level_enum logger::default_level()
{
return static_cast<level::level_enum>(SPDLOG_ACTIVE_LEVEL);
}
SPDLOG_INLINE level::level_enum logger::level() const
{
return static_cast<level::level_enum>(level_.load(std::memory_order_relaxed));
}
SPDLOG_INLINE const std::string &logger::name() const
{
return name_;
}
// set formatting for the sinks in this logger.
// each sink will get a seperate instance of the formatter object.
SPDLOG_INLINE void logger::set_formatter(std::unique_ptr<formatter> f)
{
for (auto &sink : sinks_)
{
sink->set_formatter(f->clone());
}
}
SPDLOG_INLINE void logger::set_pattern(std::string pattern, pattern_time_type time_type)
{
auto new_formatter = details::make_unique<pattern_formatter>(std::move(pattern), time_type);
set_formatter(std::move(new_formatter));
}
// flush functions
SPDLOG_INLINE void logger::flush()
{
try
{
flush_();
}
catch (const std::exception &ex)
{
err_handler_(ex.what());
}
catch (...)
{
err_handler_("Unknown exception in logger");
}
}
SPDLOG_INLINE void logger::flush_on(level::level_enum log_level)
{
flush_level_.store(log_level);
}
SPDLOG_INLINE level::level_enum logger::flush_level() const
{
return static_cast<level::level_enum>(flush_level_.load(std::memory_order_relaxed));
}
// sinks
SPDLOG_INLINE const std::vector<sink_ptr> &logger::sinks() const
{
return sinks_;
}
SPDLOG_INLINE std::vector<sink_ptr> &logger::sinks()
{
return sinks_;
}
// error handler
SPDLOG_INLINE void logger::set_error_handler(err_handler handler)
{
custom_err_handler_ = handler;
}
// create new logger with same sinks and configuration.
SPDLOG_INLINE std::shared_ptr<logger> logger::clone(std::string logger_name)
{
auto cloned = std::make_shared<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->custom_err_handler_);
return cloned;
}
// protected methods
SPDLOG_INLINE void logger::sink_it_(details::log_msg &msg)
{
for (auto &sink : sinks_)
{
if (sink->should_log(msg.level))
{
sink->log(msg);
}
}
if (should_flush_(msg))
{
flush_();
}
}
SPDLOG_INLINE void logger::flush_()
{
for (auto &sink : sinks_)
{
sink->flush();
}
}
SPDLOG_INLINE bool logger::should_flush_(const details::log_msg &msg)
{
auto flush_level = flush_level_.load(std::memory_order_relaxed);
return (msg.level >= flush_level) && (msg.level != level::off);
}
SPDLOG_INLINE void logger::err_handler_(const std::string &msg)
{
if (custom_err_handler_)
{
custom_err_handler_(msg);
}
else
{
auto tm_time = details::os::localtime();
char date_buf[64];
std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", &tm_time);
fmt::print(stderr, "[*** LOG ERROR ***] [{}] [{}] {}\n", date_buf, name(), msg);
}
}
} // namespace spdlog

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015-2108 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -15,130 +13,292 @@
// and send to its destination. // and send to its destination.
// //
// The use of private formatter per sink provides the opportunity to cache some // The use of private formatter per sink provides the opportunity to cache some
// formatted data, // formatted data, and support for different format per sink.
// and support customize format per each sink.
#include "spdlog/common.h" #include "spdlog/common.h"
#include "spdlog/formatter.h" #include "spdlog/details/log_msg.h"
#include "spdlog/sinks/sink.h"
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
#include "spdlog/details/os.h"
#endif
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
#include <functional>
namespace spdlog { namespace spdlog {
class logger class logger
{ {
public: public:
logger(std::string name, sink_ptr single_sink);
logger(std::string name, sinks_init_list sinks);
template<typename It> template<typename It>
logger(std::string name, It begin, It end); logger(std::string name, It begin, It end)
: name_(std::move(name))
, sinks_(begin, end)
{}
virtual ~logger(); logger(std::string name, sink_ptr single_sink)
: logger(std::move(name), {std::move(single_sink)})
{}
logger(std::string name, sinks_init_list sinks)
: logger(std::move(name), sinks.begin(), sinks.end())
{}
virtual ~logger() = default;
logger(const logger &) = delete; logger(const logger &) = delete;
logger &operator=(const logger &) = delete; logger &operator=(const logger &) = delete;
template<typename... Args> template<typename... Args>
void log(level::level_enum lvl, const char *fmt, const Args &... args); void log(source_loc loc, level::level_enum lvl, const char *fmt, const Args &... args)
{
if (!should_log(lvl))
{
return;
}
try
{
fmt::memory_buffer buf;
fmt::format_to(buf, fmt, args...);
details::log_msg log_msg(loc, &name_, lvl, string_view_t(buf.data(), buf.size()));
sink_it_(log_msg);
}
catch (const std::exception &ex)
{
err_handler_(ex.what());
}
catch (...)
{
err_handler_("Unknown exception in logger");
}
}
template<typename... Args> template<typename... Args>
void log(source_loc loc, level::level_enum lvl, const char *fmt, const Args &... args); void log(level::level_enum lvl, const char *fmt, const Args &... args)
{
void log(level::level_enum lvl, const char *msg); log(source_loc{}, lvl, fmt, args...);
}
void log(source_loc loc, level::level_enum lvl, const char *msg); void log(source_loc loc, level::level_enum lvl, const char *msg);
void log(level::level_enum lvl, const char *msg);
template<typename... Args> template<typename... Args>
void trace(const char *fmt, const Args &... args); void trace(const char *fmt, const Args &... args)
{
log(level::trace, fmt, args...);
}
template<typename... Args> template<typename... Args>
void debug(const char *fmt, const Args &... args); void debug(const char *fmt, const Args &... args)
{
log(level::debug, fmt, args...);
}
template<typename... Args> template<typename... Args>
void info(const char *fmt, const Args &... args); void info(const char *fmt, const Args &... args)
{
log(level::info, fmt, args...);
}
template<typename... Args> template<typename... Args>
void warn(const char *fmt, const Args &... args); void warn(const char *fmt, const Args &... args)
{
log(level::warn, fmt, args...);
}
template<typename... Args> template<typename... Args>
void error(const char *fmt, const Args &... args); void error(const char *fmt, const Args &... args)
{
log(level::err, fmt, args...);
}
template<typename... Args> template<typename... Args>
void critical(const char *fmt, const Args &... args); void critical(const char *fmt, const Args &... args)
{
log(level::critical, fmt, args...);
}
template<typename T>
void log(level::level_enum lvl, const T &msg)
{
log(source_loc{}, lvl, msg);
}
// T can be statically converted to string_view
template<class T, typename std::enable_if<std::is_convertible<T, spdlog::string_view_t>::value, T>::type * = nullptr>
void log(source_loc loc, level::level_enum lvl, const T &msg)
{
if (!should_log(lvl))
{
return;
}
try
{
details::log_msg log_msg(loc, &name_, lvl, msg);
sink_it_(log_msg);
}
catch (const std::exception &ex)
{
err_handler_(ex.what());
}
catch (...)
{
err_handler_("Unknown exception in logger");
}
}
// T cannot be statically converted to string_view
template<class T, typename std::enable_if<!std::is_convertible<T, spdlog::string_view_t>::value, T>::type * = nullptr>
void log(source_loc loc, level::level_enum lvl, const T &msg)
{
if (!should_log(lvl))
{
return;
}
try
{
fmt::memory_buffer buf;
fmt::format_to(buf, "{}", msg);
details::log_msg log_msg(loc, &name_, lvl, string_view_t(buf.data(), buf.size()));
sink_it_(log_msg);
}
catch (const std::exception &ex)
{
err_handler_(ex.what());
}
catch (...)
{
err_handler_("Unknown exception in logger");
}
}
template<typename T>
void trace(const T &msg)
{
log(level::trace, msg);
}
template<typename T>
void debug(const T &msg)
{
log(level::debug, msg);
}
template<typename T>
void info(const T &msg)
{
log(level::info, msg);
}
template<typename T>
void warn(const T &msg)
{
log(level::warn, msg);
}
template<typename T>
void error(const T &msg)
{
log(level::err, msg);
}
template<typename T>
void critical(const T &msg)
{
log(level::critical, msg);
}
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
#ifndef _WIN32 #ifndef _WIN32
#error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows #error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows
#else #else
template<typename... Args> template<typename... Args>
void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); void log(source_loc source, level::level_enum lvl, const wchar_t *fmt, const Args &... args)
{
if (!should_log(lvl))
{
return;
}
try
{
// format to wmemory_buffer and convert to utf8
fmt::wmemory_buffer wbuf;
fmt::format_to(wbuf, fmt, args...);
fmt::memory_buffer buf;
details::os::wbuf_to_utf8buf(wbuf, buf);
details::log_msg log_msg(source, &name_, lvl, string_view_t(buf.data(), buf.size()));
sink_it_(log_msg);
}
catch (const std::exception &ex)
{
err_handler_(ex.what());
}
catch (...)
{
err_handler_("Unknown exception in logger");
}
}
template<typename... Args> template<typename... Args>
void log(source_loc source, level::level_enum lvl, const wchar_t *fmt, const Args &... args); void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args)
{
log(source_loc{}, lvl, fmt, args...);
}
template<typename... Args> template<typename... Args>
void trace(const wchar_t *fmt, const Args &... args); void trace(const wchar_t *fmt, const Args &... args)
{
log(level::trace, fmt, args...);
}
template<typename... Args> template<typename... Args>
void debug(const wchar_t *fmt, const Args &... args); void debug(const wchar_t *fmt, const Args &... args)
{
log(level::debug, fmt, args...);
}
template<typename... Args> template<typename... Args>
void info(const wchar_t *fmt, const Args &... args); void info(const wchar_t *fmt, const Args &... args)
{
log(level::info, fmt, args...);
}
template<typename... Args> template<typename... Args>
void warn(const wchar_t *fmt, const Args &... args); void warn(const wchar_t *fmt, const Args &... args)
{
log(level::warn, fmt, args...);
}
template<typename... Args> template<typename... Args>
void error(const wchar_t *fmt, const Args &... args); void error(const wchar_t *fmt, const Args &... args)
{
log(level::err, fmt, args...);
}
template<typename... Args> template<typename... Args>
void critical(const wchar_t *fmt, const Args &... args); void critical(const wchar_t *fmt, const Args &... args)
{
log(level::critical, fmt, args...);
}
#endif // _WIN32 #endif // _WIN32
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
template<class T>
void log(level::level_enum lvl, const T &);
// T can be statically converted to string_view
template<class T, typename std::enable_if<std::is_convertible<T, spdlog::string_view_t>::value, T>::type * = nullptr>
void log(source_loc loc, level::level_enum lvl, const T &);
// T cannot be statically converted to string_view
template<class T, typename std::enable_if<!std::is_convertible<T, spdlog::string_view_t>::value, T>::type * = nullptr>
void log(source_loc loc, level::level_enum lvl, const T &);
template<typename T>
void trace(const T &msg);
template<typename T>
void debug(const T &msg);
template<typename T>
void info(const T &msg);
template<typename T>
void warn(const T &msg);
template<typename T>
void error(const T &msg);
template<typename T>
void critical(const T &msg);
bool should_log(level::level_enum msg_level) const; bool should_log(level::level_enum msg_level) const;
void set_level(level::level_enum log_level); void set_level(level::level_enum log_level);
static level::level_enum default_level(); static level::level_enum default_level();
level::level_enum level() const; level::level_enum level() const;
const std::string &name() const; const std::string &name() const;
// set formatting for the sinks in this logger. // set formatting for the sinks in this logger.
// each sink will get a seperate instance of the formatter object. // each sink will get a seperate instance of the formatter object.
void set_formatter(std::unique_ptr<formatter> formatter); void set_formatter(std::unique_ptr<formatter> f);
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 // flush functions
@ -148,36 +308,33 @@ public:
// sinks // 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 // error handler
void set_error_handler(log_err_handler err_handler); void set_error_handler(err_handler);
log_err_handler error_handler() const;
// create new logger with same sinks and configuration. // create new logger with same sinks and configuration.
virtual std::shared_ptr<logger> clone(std::string logger_name); 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_();
bool should_flush_(const details::log_msg &msg); bool should_flush_(const details::log_msg &msg);
// default error handler. // default error handler.
// print the error to stderr with the max rate of 1 message/minute. // print the error to stderr with the max rate of 1 message/minute.
void default_err_handler_(const std::string &msg); void err_handler_(const std::string &msg);
// increment the message count (only if defined(SPDLOG_ENABLE_MESSAGE_COUNTER))
void incr_msg_counter_(details::log_msg &msg);
const std::string name_; const std::string name_;
std::vector<sink_ptr> sinks_; std::vector<sink_ptr> sinks_;
spdlog::level_t level_{spdlog::logger::default_level()}; spdlog::level_t level_{spdlog::logger::default_level()};
spdlog::level_t flush_level_{level::off}; spdlog::level_t flush_level_{level::off};
log_err_handler err_handler_{[this](const std::string &msg) { this->default_err_handler_(msg); }}; err_handler custom_err_handler_{nullptr};
std::atomic<time_t> last_err_time_{0};
std::atomic<size_t> msg_counter_{1};
}; };
} // namespace spdlog } // namespace spdlog
#include "details/logger_impl.h" #ifdef SPDLOG_HEADER_ONLY
#include "logger-inl.h"
#endif

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -37,8 +35,7 @@ public:
explicit android_sink(std::string tag = "spdlog", bool use_raw_msg = false) explicit android_sink(std::string tag = "spdlog", bool use_raw_msg = false)
: tag_(std::move(tag)) : tag_(std::move(tag))
, use_raw_msg_(use_raw_msg) , use_raw_msg_(use_raw_msg)
{ {}
}
protected: protected:
void sink_it_(const details::log_msg &msg) override void sink_it_(const details::log_msg &msg) override

View File

@ -0,0 +1,119 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/sinks/ansicolor_sink.h"
#endif
#include "spdlog/details/os.h"
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE spdlog::sinks::ansicolor_sink<TargetStream, ConsoleMutex>::ansicolor_sink(color_mode mode)
: target_file_(TargetStream::stream())
, mutex_(ConsoleMutex::mutex())
{
set_color_mode(mode);
colors_[level::trace] = white;
colors_[level::debug] = cyan;
colors_[level::info] = green;
colors_[level::warn] = yellow + bold;
colors_[level::err] = red + bold;
colors_[level::critical] = bold + on_red;
colors_[level::off] = reset;
}
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE void spdlog::sinks::ansicolor_sink<TargetStream, ConsoleMutex>::set_color(
level::level_enum color_level, const std::string &color)
{
std::lock_guard<mutex_t> lock(mutex_);
colors_[color_level] = color;
}
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE void spdlog::sinks::ansicolor_sink<TargetStream, ConsoleMutex>::log(const details::log_msg &msg)
{
// Wrap the originally formatted message in color codes.
// If color is not supported in the terminal, log as is instead.
std::lock_guard<mutex_t> lock(mutex_);
fmt::memory_buffer formatted;
formatter_->format(msg, formatted);
if (should_do_colors_ && msg.color_range_end > msg.color_range_start)
{
// before color range
print_range_(formatted, 0, msg.color_range_start);
// in color range
print_ccode_(colors_[msg.level]);
print_range_(formatted, msg.color_range_start, msg.color_range_end);
print_ccode_(reset);
// after color range
print_range_(formatted, msg.color_range_end, formatted.size());
}
else // no color
{
print_range_(formatted, 0, formatted.size());
}
fflush(target_file_);
}
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE void spdlog::sinks::ansicolor_sink<TargetStream, ConsoleMutex>::flush()
{
std::lock_guard<mutex_t> lock(mutex_);
fflush(target_file_);
}
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE void spdlog::sinks::ansicolor_sink<TargetStream, ConsoleMutex>::set_pattern(const std::string &pattern)
{
std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));
}
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE void spdlog::sinks::ansicolor_sink<TargetStream, ConsoleMutex>::set_formatter(
std::unique_ptr<spdlog::formatter> sink_formatter)
{
std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::move(sink_formatter);
}
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE bool spdlog::sinks::ansicolor_sink<TargetStream, ConsoleMutex>::should_color()
{
return should_do_colors_;
}
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE void spdlog::sinks::ansicolor_sink<TargetStream, ConsoleMutex>::set_color_mode(color_mode mode)
{
switch (mode)
{
case color_mode::always:
should_do_colors_ = true;
return;
case color_mode::automatic:
should_do_colors_ = details::os::in_terminal(target_file_) && details::os::is_color_terminal();
return;
case color_mode::never:
should_do_colors_ = false;
return;
}
}
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE void spdlog::sinks::ansicolor_sink<TargetStream, ConsoleMutex>::print_ccode_(const std::string &color_code)
{
fwrite(color_code.data(), sizeof(char), color_code.size(), target_file_);
}
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE void spdlog::sinks::ansicolor_sink<TargetStream, ConsoleMutex>::print_range_(
const fmt::memory_buffer &formatted, size_t start, size_t end)
{
fwrite(formatted.data() + start, sizeof(char), end - start, target_file_);
}

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2017 spdlog authors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -11,9 +9,7 @@
#include "spdlog/details/console_globals.h" #include "spdlog/details/console_globals.h"
#include "spdlog/details/null_mutex.h" #include "spdlog/details/null_mutex.h"
#include "spdlog/details/os.h"
#include "spdlog/sinks/sink.h" #include "spdlog/sinks/sink.h"
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <string> #include <string>
@ -28,36 +24,23 @@ namespace sinks {
* of the message. * of the message.
* 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, typename ConsoleMutex>
class ansicolor_sink final : public sink class ansicolor_sink final : public sink
{ {
public: public:
using mutex_t = typename ConsoleMutex::mutex_t; using mutex_t = typename ConsoleMutex::mutex_t;
ansicolor_sink(color_mode mode = color_mode::automatic) ansicolor_sink(color_mode mode = color_mode::automatic);
: target_file_(TargetStream::stream())
, mutex_(ConsoleMutex::mutex())
{
set_color_mode_(mode);
colors_[level::trace] = white;
colors_[level::debug] = cyan;
colors_[level::info] = green;
colors_[level::warn] = yellow + bold;
colors_[level::err] = red + bold;
colors_[level::critical] = bold + on_red;
colors_[level::off] = reset;
}
~ansicolor_sink() override = default; ~ansicolor_sink() override = default;
ansicolor_sink(const ansicolor_sink &other) = delete; ansicolor_sink(const ansicolor_sink &other) = delete;
ansicolor_sink &operator=(const ansicolor_sink &other) = delete; ansicolor_sink &operator=(const ansicolor_sink &other) = delete;
void set_color(level::level_enum color_level, const std::string &color);
void set_color(level::level_enum color_level, const std::string &color) void log(const details::log_msg &msg) override;
{ void flush() override;
std::lock_guard<mutex_t> lock(mutex_); void set_pattern(const std::string &pattern) final;
colors_[color_level] = color; void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override;
} bool should_color();
void set_color_mode(color_mode mode);
/// Formatting codes /// Formatting codes
const std::string reset = "\033[m"; const std::string reset = "\033[m";
@ -89,93 +72,13 @@ 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) override
{
// Wrap the originally formatted message in color codes.
// If color is not supported in the terminal, log as is instead.
std::lock_guard<mutex_t> lock(mutex_);
fmt::memory_buffer formatted;
formatter_->format(msg, formatted);
if (should_do_colors_ && msg.color_range_end > msg.color_range_start)
{
// before color range
print_range_(formatted, 0, msg.color_range_start);
// in color range
print_ccode_(colors_[msg.level]);
print_range_(formatted, msg.color_range_start, msg.color_range_end);
print_ccode_(reset);
// after color range
print_range_(formatted, msg.color_range_end, formatted.size());
}
else // no color
{
print_range_(formatted, 0, formatted.size());
}
fflush(target_file_);
}
void flush() override
{
std::lock_guard<mutex_t> lock(mutex_);
fflush(target_file_);
}
void set_pattern(const std::string &pattern) final
{
std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));
}
void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override
{
std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::move(sink_formatter);
}
bool should_color()
{
std::lock_guard<mutex_t> lock(mutex_);
return should_do_colors_;
}
void set_color_mode(color_mode mode)
{
std::lock_guard<mutex_t> lock(mutex_);
set_color_mode_(mode);
}
private: private:
void set_color_mode_(color_mode mode)
{
switch (mode)
{
case color_mode::always:
should_do_colors_ = true;
break;
case color_mode::automatic:
should_do_colors_ = details::os::in_terminal(target_file_) && details::os::is_color_terminal();
break;
case color_mode::never:
should_do_colors_ = false;
break;
}
}
void print_ccode_(const std::string &color_code)
{
fwrite(color_code.data(), sizeof(char), color_code.size(), target_file_);
}
void print_range_(const fmt::memory_buffer &formatted, size_t start, size_t end)
{
fwrite(formatted.data() + start, sizeof(char), end - start, target_file_);
}
FILE *target_file_; FILE *target_file_;
mutex_t &mutex_; mutex_t &mutex_;
bool should_do_colors_; bool should_do_colors_;
std::unordered_map<level::level_enum, std::string, level::level_hasher> colors_; std::unordered_map<level::level_enum, std::string, level::level_hasher> colors_;
void print_ccode_(const std::string &color_code);
void print_range_(const fmt::memory_buffer &formatted, size_t start, size_t end);
}; };
using ansicolor_stdout_sink_mt = ansicolor_sink<details::console_stdout, details::console_mutex>; using ansicolor_stdout_sink_mt = ansicolor_sink<details::console_stdout, details::console_mutex>;
@ -185,5 +88,8 @@ using ansicolor_stderr_sink_mt = ansicolor_sink<details::console_stderr, details
using ansicolor_stderr_sink_st = ansicolor_sink<details::console_stderr, details::console_nullmutex>; using ansicolor_stderr_sink_st = ansicolor_sink<details::console_stderr, details::console_nullmutex>;
} // namespace sinks } // namespace sinks
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "ansicolor_sink-inl.h"
#endif

View File

@ -0,0 +1,51 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/sinks/base_sink.h"
#endif
#include "spdlog/common.h"
#include "spdlog/details/pattern_formatter.h"
template<typename Mutex>
void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::log(const details::log_msg &msg)
{
std::lock_guard<Mutex> lock(mutex_);
sink_it_(msg);
}
template<typename Mutex>
void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::flush()
{
std::lock_guard<Mutex> lock(mutex_);
flush_();
}
template<typename Mutex>
void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_pattern(const std::string &pattern)
{
std::lock_guard<Mutex> lock(mutex_);
set_pattern_(pattern);
}
template<typename Mutex>
void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter)
{
std::lock_guard<Mutex> lock(mutex_);
set_formatter_(std::move(sink_formatter));
}
template<typename Mutex>
void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_pattern_(const std::string &pattern)
{
set_formatter_(details::make_unique<spdlog::pattern_formatter>(pattern));
}
template<typename Mutex>
void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter)
{
formatter_ = std::move(sink_formatter);
}

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
// //
@ -13,7 +11,6 @@
#include "spdlog/common.h" #include "spdlog/common.h"
#include "spdlog/details/log_msg.h" #include "spdlog/details/log_msg.h"
#include "spdlog/formatter.h"
#include "spdlog/sinks/sink.h" #include "spdlog/sinks/sink.h"
namespace spdlog { namespace spdlog {
@ -25,45 +22,21 @@ public:
base_sink() = default; base_sink() = default;
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) final;
void log(const details::log_msg &msg) final void flush() final;
{ void set_pattern(const std::string &pattern) final;
std::lock_guard<Mutex> lock(mutex_); void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) final;
sink_it_(msg);
}
void flush() final
{
std::lock_guard<Mutex> lock(mutex_);
flush_();
}
void set_pattern(const std::string &pattern) final
{
std::lock_guard<Mutex> lock(mutex_);
set_pattern_(pattern);
}
void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) final
{
std::lock_guard<Mutex> lock(mutex_);
set_formatter_(std::move(sink_formatter));
}
protected: protected:
virtual void sink_it_(const details::log_msg &msg) = 0; virtual void sink_it_(const details::log_msg &msg) = 0;
virtual void flush_() = 0; virtual void flush_() = 0;
virtual void set_pattern_(const std::string &pattern);
virtual void set_pattern_(const std::string &pattern) virtual void set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter);
{
set_formatter_(details::make_unique<spdlog::pattern_formatter>(pattern));
}
virtual void set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter)
{
formatter_ = std::move(sink_formatter);
}
Mutex mutex_; Mutex mutex_;
}; };
} // namespace sinks } // namespace sinks
} // namespace spdlog } // namespace spdlog
#ifndef SPDLOG_COMPILED_LIB
#include "base_sink-inl.h"
#endif

View File

@ -0,0 +1,43 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/sinks/basic_file_sink.h"
#endif
#include "spdlog/common.h"
#include "spdlog/details/os.h"
namespace spdlog {
namespace sinks {
template<typename Mutex>
SPDLOG_INLINE basic_file_sink<Mutex>::basic_file_sink(const filename_t &filename, bool truncate)
{
file_helper_.open(filename, truncate);
}
template<typename Mutex>
SPDLOG_INLINE const filename_t &basic_file_sink<Mutex>::filename() const
{
return file_helper_.filename();
}
template<typename Mutex>
SPDLOG_INLINE void basic_file_sink<Mutex>::sink_it_(const details::log_msg &msg)
{
fmt::memory_buffer formatted;
sink::formatter_->format(msg, formatted);
file_helper_.write(formatted);
}
template<typename Mutex>
SPDLOG_INLINE void basic_file_sink<Mutex>::flush_()
{
file_helper_.flush();
}
} // namespace sinks
} // namespace spdlog

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015-2018 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -25,28 +23,12 @@ template<typename Mutex>
class basic_file_sink final : public base_sink<Mutex> class basic_file_sink final : public base_sink<Mutex>
{ {
public: public:
explicit basic_file_sink(const filename_t &filename, bool truncate = false) explicit basic_file_sink(const filename_t &filename, bool truncate = false);
{ const filename_t &filename() const;
file_helper_.open(filename, truncate);
}
const filename_t &filename() const
{
return file_helper_.filename();
}
protected: protected:
void sink_it_(const details::log_msg &msg) override void sink_it_(const details::log_msg &msg) override;
{ void flush_() override;
fmt::memory_buffer formatted;
sink::formatter_->format(msg, formatted);
file_helper_.write(formatted);
}
void flush_() override
{
file_helper_.flush();
}
private: private:
details::file_helper file_helper_; details::file_helper file_helper_;
@ -73,3 +55,7 @@ inline std::shared_ptr<logger> basic_logger_st(const std::string &logger_name, c
} }
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "basic_file_sink-inl.h"
#endif

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -13,6 +11,7 @@
#include "spdlog/details/null_mutex.h" #include "spdlog/details/null_mutex.h"
#include "spdlog/fmt/fmt.h" #include "spdlog/fmt/fmt.h"
#include "spdlog/sinks/base_sink.h" #include "spdlog/sinks/base_sink.h"
#include "spdlog/details/os.h"
#include <chrono> #include <chrono>
#include <cstdio> #include <cstdio>

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright (c) 2015 David Schury, Gabi Melman
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once

View File

@ -1,7 +1,5 @@
//
// Copyright(c) 2016 Alexander Dalshov. // Copyright(c) 2016 Alexander Dalshov.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -24,8 +22,7 @@ public:
explicit ostream_sink(std::ostream &os, bool force_flush = false) explicit ostream_sink(std::ostream &os, bool force_flush = false)
: ostream_(os) : ostream_(os)
, force_flush_(force_flush) , force_flush_(force_flush)
{ {}
}
ostream_sink(const ostream_sink &) = delete; ostream_sink(const ostream_sink &) = delete;
ostream_sink &operator=(const ostream_sink &) = delete; ostream_sink &operator=(const ostream_sink &) = delete;

View File

@ -0,0 +1,133 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/sinks/rotating_file_sink.h"
#endif
#include "spdlog/common.h"
#include "spdlog/details/file_helper.h"
#include "spdlog/details/null_mutex.h"
#include "spdlog/fmt/fmt.h"
#include <cerrno>
#include <chrono>
#include <ctime>
#include <mutex>
#include <string>
#include <tuple>
namespace spdlog {
namespace sinks {
template<typename Mutex>
SPDLOG_INLINE rotating_file_sink<Mutex>::rotating_file_sink(
filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open)
: base_filename_(std::move(base_filename))
, max_size_(max_size)
, max_files_(max_files)
{
file_helper_.open(calc_filename(base_filename_, 0));
current_size_ = file_helper_.size(); // expensive. called only once
if (rotate_on_open && current_size_ > 0)
{
rotate_();
}
}
// calc filename according to index and file extension if exists.
// e.g. calc_filename("logs/mylog.txt, 3) => "logs/mylog.3.txt".
template<typename Mutex>
SPDLOG_INLINE filename_t rotating_file_sink<Mutex>::calc_filename(const filename_t &filename, std::size_t index)
{
typename std::conditional<std::is_same<filename_t::value_type, char>::value, fmt::memory_buffer, fmt::wmemory_buffer>::type w;
if (index != 0u)
{
filename_t basename, ext;
std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
fmt::format_to(w, SPDLOG_FILENAME_T("{}.{}{}"), basename, index, ext);
}
else
{
fmt::format_to(w, SPDLOG_FILENAME_T("{}"), filename);
}
return fmt::to_string(w);
}
template<typename Mutex>
SPDLOG_INLINE const filename_t &rotating_file_sink<Mutex>::filename() const
{
return file_helper_.filename();
}
template<typename Mutex>
SPDLOG_INLINE void rotating_file_sink<Mutex>::sink_it_(const details::log_msg &msg)
{
fmt::memory_buffer formatted;
sink::formatter_->format(msg, formatted);
current_size_ += formatted.size();
if (current_size_ > max_size_)
{
rotate_();
current_size_ = formatted.size();
}
file_helper_.write(formatted);
}
template<typename Mutex>
SPDLOG_INLINE void rotating_file_sink<Mutex>::flush_()
{
file_helper_.flush();
}
// Rotate files:
// log.txt -> log.1.txt
// log.1.txt -> log.2.txt
// log.2.txt -> log.3.txt
// log.3.txt -> delete
template<typename Mutex>
SPDLOG_INLINE void rotating_file_sink<Mutex>::rotate_()
{
using details::os::filename_to_str;
file_helper_.close();
for (auto i = max_files_; i > 0; --i)
{
filename_t src = calc_filename(base_filename_, i - 1);
if (!details::file_helper::file_exists(src))
{
continue;
}
filename_t target = calc_filename(base_filename_, i);
if (!rename_file(src, target))
{
// if failed try again after a small delay.
// this is a workaround to a windows issue, where very high rotation
// rates can cause the rename to fail with permission denied (because of antivirus?).
details::os::sleep_for_millis(100);
if (!rename_file(src, target))
{
file_helper_.reopen(true); // truncate the log file anyway to prevent it to grow beyond its limit!
current_size_ = 0;
throw spdlog_ex("rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno);
}
}
}
file_helper_.reopen(true);
}
// delete the target if exists, and rename the src file to target
// return true on success, false otherwise.
template<typename Mutex>
SPDLOG_INLINE bool rotating_file_sink<Mutex>::rename_file(const filename_t &src_filename, const filename_t &target_filename)
{
// try to delete the target file in case it already exists.
(void)details::os::remove(target_filename);
return details::os::rename(src_filename, target_filename) == 0;
}
} // namespace sinks
} // namespace spdlog

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -9,17 +7,12 @@
#include "spdlog/spdlog.h" #include "spdlog/spdlog.h"
#endif #endif
#include "spdlog/details/file_helper.h"
#include "spdlog/details/null_mutex.h"
#include "spdlog/fmt/fmt.h"
#include "spdlog/sinks/base_sink.h" #include "spdlog/sinks/base_sink.h"
#include "spdlog/details/file_helper.h"
#include <cerrno>
#include <chrono> #include <chrono>
#include <ctime>
#include <mutex> #include <mutex>
#include <string> #include <string>
#include <tuple>
namespace spdlog { namespace spdlog {
namespace sinks { namespace sinks {
@ -31,60 +24,13 @@ template<typename Mutex>
class rotating_file_sink final : public base_sink<Mutex> class rotating_file_sink final : public base_sink<Mutex>
{ {
public: public:
rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open=false) rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open = false);
: base_filename_(std::move(base_filename)) static filename_t calc_filename(const filename_t &filename, std::size_t index);
, max_size_(max_size) const filename_t &filename() const;
, max_files_(max_files)
{
file_helper_.open(calc_filename(base_filename_, 0));
current_size_ = file_helper_.size(); // expensive. called only once
if (rotate_on_open && current_size_ > 0)
{
rotate_();
}
}
// calc filename according to index and file extension if exists.
// e.g. calc_filename("logs/mylog.txt, 3) => "logs/mylog.3.txt".
static filename_t calc_filename(const filename_t &filename, std::size_t index)
{
typename std::conditional<std::is_same<filename_t::value_type, char>::value, fmt::memory_buffer, fmt::wmemory_buffer>::type w;
if (index != 0u)
{
filename_t basename, ext;
std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
fmt::format_to(w, SPDLOG_FILENAME_T("{}.{}{}"), basename, index, ext);
}
else
{
fmt::format_to(w, SPDLOG_FILENAME_T("{}"), filename);
}
return fmt::to_string(w);
}
const filename_t &filename() const
{
return file_helper_.filename();
}
protected: protected:
void sink_it_(const details::log_msg &msg) override void sink_it_(const details::log_msg &msg) override;
{ void flush_() override;
fmt::memory_buffer formatted;
sink::formatter_->format(msg, formatted);
current_size_ += formatted.size();
if (current_size_ > max_size_)
{
rotate_();
current_size_ = formatted.size();
}
file_helper_.write(formatted);
}
void flush_() override
{
file_helper_.flush();
}
private: private:
// Rotate files: // Rotate files:
@ -92,45 +38,11 @@ private:
// log.1.txt -> log.2.txt // log.1.txt -> log.2.txt
// log.2.txt -> log.3.txt // log.2.txt -> log.3.txt
// log.3.txt -> delete // log.3.txt -> delete
void rotate_() void rotate_();
{
using details::os::filename_to_str;
file_helper_.close();
for (auto i = max_files_; i > 0; --i)
{
filename_t src = calc_filename(base_filename_, i - 1);
if (!details::file_helper::file_exists(src))
{
continue;
}
filename_t target = calc_filename(base_filename_, i);
if (!rename_file(src, target))
{
// if failed try again after a small delay.
// this is a workaround to a windows issue, where very high rotation
// rates can cause the rename to fail with permission denied (because of antivirus?).
details::os::sleep_for_millis(100);
if (!rename_file(src, target))
{
file_helper_.reopen(true); // truncate the log file anyway to prevent it to grow beyond its limit!
current_size_ = 0;
throw spdlog_ex(
"rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno);
}
}
}
file_helper_.reopen(true);
}
// delete the target if exists, and rename the src file to target // delete the target if exists, and rename the src file to target
// return true on success, false otherwise. // return true on success, false otherwise.
bool rename_file(const filename_t &src_filename, const filename_t &target_filename) bool rename_file(const filename_t &src_filename, const filename_t &target_filename);
{
// try to delete the target file in case it already exists.
(void)details::os::remove(target_filename);
return details::os::rename(src_filename, target_filename) == 0;
}
filename_t base_filename_; filename_t base_filename_;
std::size_t max_size_; std::size_t max_size_;
@ -150,7 +62,7 @@ using rotating_file_sink_st = rotating_file_sink<details::null_mutex>;
template<typename Factory = default_factory> template<typename Factory = default_factory>
inline std::shared_ptr<logger> rotating_logger_mt( inline std::shared_ptr<logger> rotating_logger_mt(
const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files, bool rotate_on_open=false) const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files, bool rotate_on_open = false)
{ {
return Factory::template create<sinks::rotating_file_sink_mt>(logger_name, filename, max_file_size, max_files, rotate_on_open); return Factory::template create<sinks::rotating_file_sink_mt>(logger_name, filename, max_file_size, max_files, rotate_on_open);
} }
@ -162,3 +74,7 @@ inline std::shared_ptr<logger> rotating_logger_st(
return Factory::template create<sinks::rotating_file_sink_st>(logger_name, filename, max_file_size, max_files, rotate_on_open); return Factory::template create<sinks::rotating_file_sink_st>(logger_name, filename, max_file_size, max_files, rotate_on_open);
} }
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "rotating_file_sink-inl.h"
#endif

View File

@ -0,0 +1,34 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/sinks/sink.h"
#endif
#include "spdlog/common.h"
#include "spdlog/details/pattern_formatter.h"
SPDLOG_INLINE spdlog::sinks::sink::sink()
: formatter_{details::make_unique<spdlog::pattern_formatter>()}
{}
SPDLOG_INLINE spdlog::sinks::sink::sink(std::unique_ptr<spdlog::formatter> formatter)
: formatter_{std::move(formatter)}
{}
SPDLOG_INLINE bool spdlog::sinks::sink::should_log(spdlog::level::level_enum msg_level) const
{
return msg_level >= level_.load(std::memory_order_relaxed);
}
SPDLOG_INLINE void spdlog::sinks::sink::set_level(level::level_enum log_level)
{
level_.store(log_level);
}
SPDLOG_INLINE spdlog::level::level_enum spdlog::sinks::sink::level() const
{
return static_cast<spdlog::level::level_enum>(level_.load(std::memory_order_relaxed));
}

View File

@ -1,54 +1,43 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
#include "spdlog/details/log_msg.h" #include "spdlog/details/log_msg.h"
#include "spdlog/details/pattern_formatter.h"
#include "spdlog/formatter.h" #include "spdlog/formatter.h"
namespace spdlog { namespace spdlog {
namespace sinks { namespace sinks {
class sink class sink
{ {
public: public:
sink() = default; sink();
explicit sink(std::unique_ptr<spdlog::formatter> formatter)
: formatter_{std::move(formatter)}
{
}
explicit sink(std::unique_ptr<spdlog::formatter> 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;
virtual void flush() = 0; virtual void flush() = 0;
virtual void set_pattern(const std::string &pattern) = 0; virtual void set_pattern(const std::string &pattern) = 0;
virtual void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) = 0; virtual void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) = 0;
bool should_log(level::level_enum msg_level) const bool should_log(level::level_enum msg_level) const;
{
return msg_level >= level_.load(std::memory_order_relaxed);
}
void set_level(level::level_enum log_level) void set_level(level::level_enum log_level);
{
level_.store(log_level);
}
level::level_enum level() const level::level_enum level() const;
{
return static_cast<spdlog::level::level_enum>(level_.load(std::memory_order_relaxed));
}
protected: protected:
// sink log level - default is all // sink log level - default is all
level_t level_{level::trace}; level_t level_{level::trace};
// sink formatter - default is full format // sink formatter
std::unique_ptr<spdlog::formatter> formatter_{details::make_unique<spdlog::pattern_formatter>()}; std::unique_ptr<spdlog::formatter> formatter_;
}; };
} // namespace sinks } // namespace sinks
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "sink-inl.h"
#endif

View File

@ -0,0 +1,38 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/sinks/stdout_color_sinks.h"
#endif
#include "spdlog/logger.h"
#include "spdlog/common.h"
namespace spdlog {
template<typename Factory>
SPDLOG_INLINE std::shared_ptr<logger> stdout_color_mt(const std::string &logger_name, color_mode mode)
{
return Factory::template create<sinks::stdout_color_sink_mt>(logger_name, mode);
}
template<typename Factory>
SPDLOG_INLINE std::shared_ptr<logger> stdout_color_st(const std::string &logger_name, color_mode mode)
{
return Factory::template create<sinks::stdout_color_sink_st>(logger_name, mode);
}
template<typename Factory>
SPDLOG_INLINE std::shared_ptr<logger> stderr_color_mt(const std::string &logger_name, color_mode mode)
{
return Factory::template create<sinks::stderr_color_sink_mt>(logger_name, mode);
}
template<typename Factory>
SPDLOG_INLINE std::shared_ptr<logger> stderr_color_st(const std::string &logger_name, color_mode mode)
{
return Factory::template create<sinks::stderr_color_sink_st>(logger_name, mode);
}
} // namespace spdlog

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2018 spdlog
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -31,26 +29,19 @@ using stderr_color_sink_st = ansicolor_stderr_sink_st;
} // namespace sinks } // namespace sinks
template<typename Factory = default_factory> template<typename Factory = default_factory>
inline std::shared_ptr<logger> stdout_color_mt(const std::string &logger_name, color_mode mode = color_mode::automatic) std::shared_ptr<logger> stdout_color_mt(const std::string &logger_name, color_mode mode = color_mode::automatic);
{
return Factory::template create<sinks::stdout_color_sink_mt>(logger_name, mode);
}
template<typename Factory = default_factory> template<typename Factory = default_factory>
inline std::shared_ptr<logger> stdout_color_st(const std::string &logger_name, color_mode mode = color_mode::automatic) std::shared_ptr<logger> stdout_color_st(const std::string &logger_name, color_mode mode = color_mode::automatic);
{
return Factory::template create<sinks::stdout_color_sink_st>(logger_name, mode);
}
template<typename Factory = default_factory> template<typename Factory = default_factory>
inline std::shared_ptr<logger> stderr_color_mt(const std::string &logger_name, color_mode mode = color_mode::automatic) std::shared_ptr<logger> stderr_color_mt(const std::string &logger_name, color_mode mode = color_mode::automatic);
{
return Factory::template create<sinks::stderr_color_sink_mt>(logger_name, mode);
}
template<typename Factory = default_factory> template<typename Factory = default_factory>
inline std::shared_ptr<logger> stderr_color_st(const std::string &logger_name, color_mode mode = color_mode::automatic) std::shared_ptr<logger> stderr_color_st(const std::string &logger_name, color_mode mode = color_mode::automatic);
{
return Factory::template create<sinks::stderr_color_sink_st>(logger_name, mode);
}
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "stdout_color_sinks-inl.h"
#endif

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -11,6 +9,7 @@
#include "spdlog/details/console_globals.h" #include "spdlog/details/console_globals.h"
#include "spdlog/details/null_mutex.h" #include "spdlog/details/null_mutex.h"
#include "spdlog/details/pattern_formatter.h"
#include <cstdio> #include <cstdio>
#include <memory> #include <memory>
@ -28,8 +27,7 @@ public:
stdout_sink() stdout_sink()
: mutex_(ConsoleMutex::mutex()) : mutex_(ConsoleMutex::mutex())
, file_(TargetStream::stream()) , file_(TargetStream::stream())
{ {}
}
~stdout_sink() override = default; ~stdout_sink() override = default;
stdout_sink(const stdout_sink &other) = delete; stdout_sink(const stdout_sink &other) = delete;

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once

View File

@ -1,7 +1,5 @@
//
// Copyright(c) 2019 ZVYAGIN.Alexander@gmail.com // Copyright(c) 2019 ZVYAGIN.Alexander@gmail.com
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -18,22 +16,24 @@
namespace spdlog { namespace spdlog {
namespace sinks { namespace sinks {
inline int syslog_level(level::level_enum l) { inline int syslog_level(level::level_enum l)
switch(l) { {
case level::off: switch (l)
case level::trace: {
case level::debug: case level::off:
return LOG_DEBUG; case level::trace:
case level::info: case level::debug:
return LOG_INFO; return LOG_DEBUG;
case level::warn: case level::info:
return LOG_WARNING; return LOG_INFO;
case level::err: case level::warn:
return LOG_ERR; return LOG_WARNING;
case level::critical: case level::err:
return LOG_CRIT; return LOG_ERR;
default: case level::critical:
throw std::invalid_argument("systemd_sink.h syslog_level()"); return LOG_CRIT;
default:
throw std::invalid_argument("systemd_sink.h syslog_level()");
} }
} }
@ -57,13 +57,7 @@ public:
protected: protected:
void sink_it_(const details::log_msg &msg) override void sink_it_(const details::log_msg &msg) override
{ {
if( sd_journal_print( if (sd_journal_print(syslog_level(msg.level), "%.*s", static_cast<int>(msg.payload.size()), msg.payload.data()))
syslog_level(msg.level),
"%.*s",
static_cast<int>(msg.payload.size()),
msg.payload.data()
)
)
throw spdlog_ex("Failed writing to systemd"); throw spdlog_ex("Failed writing to systemd");
} }
@ -76,15 +70,13 @@ using systemd_sink_st = systemd_sink<details::null_mutex>;
// Create and register a syslog logger // Create and register a syslog logger
template<typename Factory = default_factory> template<typename Factory = default_factory>
inline std::shared_ptr<logger> systemd_logger_mt( inline std::shared_ptr<logger> systemd_logger_mt(const std::string &logger_name)
const std::string &logger_name)
{ {
return Factory::template create<sinks::systemd_sink_mt>(logger_name); return Factory::template create<sinks::systemd_sink_mt>(logger_name);
} }
template<typename Factory = default_factory> template<typename Factory = default_factory>
inline std::shared_ptr<logger> systemd_logger_st( inline std::shared_ptr<logger> systemd_logger_st(const std::string &logger_name)
const std::string &logger_name)
{ {
return Factory::template create<sinks::systemd_sink_st>(logger_name); return Factory::template create<sinks::systemd_sink_st>(logger_name);
} }

View File

@ -0,0 +1,129 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/sinks/wincolor_sink.h"
#endif
#include "spdlog/common.h"
namespace spdlog {
namespace sinks {
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE wincolor_sink<TargetStream, ConsoleMutex>::wincolor_sink(color_mode mode)
: out_handle_(TargetStream::handle())
, mutex_(ConsoleMutex::mutex())
{
set_color_mode(mode);
colors_[level::trace] = WHITE;
colors_[level::debug] = CYAN;
colors_[level::info] = GREEN;
colors_[level::warn] = YELLOW | BOLD;
colors_[level::err] = RED | BOLD; // red bold
colors_[level::critical] = BACKGROUND_RED | WHITE | BOLD; // white bold on red background
colors_[level::off] = 0;
}
template<typename TargetStream, typename ConsoleMutex>
SPDLOG_INLINE wincolor_sink<TargetStream, ConsoleMutex>::~wincolor_sink()
{
this->flush();
}
// change the color for the given level
template<typename TargetStream, typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<TargetStream, ConsoleMutex>::set_color(level::level_enum level, WORD color)
{
std::lock_guard<mutex_t> lock(mutex_);
colors_[level] = color;
}
template<typename TargetStream, typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<TargetStream, ConsoleMutex>::log(const details::log_msg &msg)
{
std::lock_guard<mutex_t> lock(mutex_);
fmt::memory_buffer formatted;
formatter_->format(msg, formatted);
if (should_do_colors_ && msg.color_range_end > msg.color_range_start)
{
// before color range
print_range_(formatted, 0, msg.color_range_start);
// in color range
auto orig_attribs = set_console_attribs(colors_[msg.level]);
print_range_(formatted, msg.color_range_start, msg.color_range_end);
::SetConsoleTextAttribute(out_handle_,
orig_attribs); // reset to orig colors
// after color range
print_range_(formatted, msg.color_range_end, formatted.size());
}
else // print without colors if color range is invalid (or color is disabled)
{
print_range_(formatted, 0, formatted.size());
}
}
template<typename TargetStream, typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<TargetStream, ConsoleMutex>::flush()
{
// windows console always flushed?
}
template<typename TargetStream, typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<TargetStream, ConsoleMutex>::set_pattern(const std::string &pattern)
{
std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));
}
template<typename TargetStream, typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<TargetStream, ConsoleMutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter)
{
std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::move(sink_formatter);
}
template<typename TargetStream, typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<TargetStream, ConsoleMutex>::set_color_mode(color_mode mode)
{
switch (mode)
{
case color_mode::always:
case color_mode::automatic:
should_do_colors_ = true;
break;
case color_mode::never:
should_do_colors_ = false;
break;
default:
should_do_colors_ = true;
}
}
// set color and return the orig console attributes (for resetting later)
template<typename TargetStream, typename ConsoleMutex>
WORD SPDLOG_INLINE wincolor_sink<TargetStream, ConsoleMutex>::set_console_attribs(WORD attribs)
{
CONSOLE_SCREEN_BUFFER_INFO orig_buffer_info;
::GetConsoleScreenBufferInfo(out_handle_, &orig_buffer_info);
WORD back_color = orig_buffer_info.wAttributes;
// retrieve the current background color
back_color &= static_cast<WORD>(~(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY));
// keep the background color unchanged
::SetConsoleTextAttribute(out_handle_, attribs | back_color);
return orig_buffer_info.wAttributes; // return orig attribs
}
// print a range of formatted message to console
template<typename TargetStream, typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<TargetStream, ConsoleMutex>::print_range_(const fmt::memory_buffer &formatted, size_t start, size_t end)
{
auto size = static_cast<DWORD>(end - start);
::WriteConsoleA(out_handle_, formatted.data() + start, size, nullptr, nullptr);
}
} // namespace sinks
} // namespace spdlog

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2016 spdlog
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -26,7 +24,7 @@ namespace sinks {
* Windows color console sink. Uses WriteConsoleA to write to the console with * Windows color console sink. Uses WriteConsoleA to write to the console with
* colors * colors
*/ */
template<typename OutHandle, typename ConsoleMutex> template<typename TargetStream, typename ConsoleMutex>
class wincolor_sink : public sink class wincolor_sink : public sink
{ {
public: public:
@ -37,123 +35,31 @@ public:
const WORD WHITE = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; const WORD WHITE = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
const WORD YELLOW = FOREGROUND_RED | FOREGROUND_GREEN; const WORD YELLOW = FOREGROUND_RED | FOREGROUND_GREEN;
wincolor_sink(color_mode mode = color_mode::automatic) wincolor_sink(color_mode mode = color_mode::automatic);
: out_handle_(OutHandle::handle()) ~wincolor_sink() override;
, mutex_(ConsoleMutex::mutex())
{
set_color_mode_(mode);
colors_[level::trace] = WHITE;
colors_[level::debug] = CYAN;
colors_[level::info] = GREEN;
colors_[level::warn] = YELLOW | BOLD;
colors_[level::err] = RED | BOLD; // red bold
colors_[level::critical] = BACKGROUND_RED | WHITE | BOLD; // white bold on red background
colors_[level::off] = 0;
}
~wincolor_sink() override
{
this->flush();
}
wincolor_sink(const wincolor_sink &other) = delete; wincolor_sink(const wincolor_sink &other) = delete;
wincolor_sink &operator=(const wincolor_sink &other) = delete; wincolor_sink &operator=(const wincolor_sink &other) = delete;
// change the color for the given level // change the color for the given level
void set_color(level::level_enum level, WORD color) void set_color(level::level_enum level, WORD color);
{ void log(const details::log_msg &msg) final override;
std::lock_guard<mutex_t> lock(mutex_); void flush() final override;
colors_[level] = color; void set_pattern(const std::string &pattern) override final;
} void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override final;
void set_color_mode(color_mode mode);
void log(const details::log_msg &msg) final override
{
std::lock_guard<mutex_t> lock(mutex_);
fmt::memory_buffer formatted;
formatter_->format(msg, formatted);
if (should_do_colors_ && msg.color_range_end > msg.color_range_start)
{
// before color range
print_range_(formatted, 0, msg.color_range_start);
// in color range
auto orig_attribs = set_console_attribs(colors_[msg.level]);
print_range_(formatted, msg.color_range_start, msg.color_range_end);
::SetConsoleTextAttribute(out_handle_,
orig_attribs); // reset to orig colors
// after color range
print_range_(formatted, msg.color_range_end, formatted.size());
}
else // print without colors if color range is invalid (or color is disabled)
{
print_range_(formatted, 0, formatted.size());
}
}
void flush() final override
{
// windows console always flushed?
}
void set_pattern(const std::string &pattern) override final
{
std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));
}
void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override final
{
std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::move(sink_formatter);
}
void set_color_mode(color_mode mode)
{
std::lock_guard<mutex_t> lock(mutex_);
set_color_mode_(mode);
}
private: private:
using mutex_t = typename ConsoleMutex::mutex_t; using mutex_t = typename ConsoleMutex::mutex_t;
void set_color_mode_(color_mode mode)
{
switch (mode)
{
case color_mode::always:
case color_mode::automatic:
should_do_colors_ = true;
break;
case color_mode::never:
should_do_colors_ = false;
break;
}
}
// set color and return the orig console attributes (for resetting later)
WORD set_console_attribs(WORD attribs)
{
CONSOLE_SCREEN_BUFFER_INFO orig_buffer_info;
::GetConsoleScreenBufferInfo(out_handle_, &orig_buffer_info);
WORD back_color = orig_buffer_info.wAttributes;
// retrieve the current background color
back_color &= static_cast<WORD>(~(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY));
// keep the background color unchanged
::SetConsoleTextAttribute(out_handle_, attribs | back_color);
return orig_buffer_info.wAttributes; // return orig attribs
}
// print a range of formatted message to console
void print_range_(const fmt::memory_buffer &formatted, size_t start, size_t end)
{
auto size = static_cast<DWORD>(end - start);
::WriteConsoleA(out_handle_, formatted.data() + start, size, nullptr, nullptr);
}
HANDLE out_handle_; HANDLE out_handle_;
mutex_t &mutex_; mutex_t &mutex_;
bool should_do_colors_; bool should_do_colors_;
std::unordered_map<level::level_enum, WORD, level::level_hasher> colors_; std::unordered_map<level::level_enum, WORD, level::level_hasher> colors_;
// set color and return the orig console attributes (for resetting later)
WORD set_console_attribs(WORD attribs);
// print a range of formatted message to console
void print_range_(const fmt::memory_buffer &formatted, size_t start, size_t end);
}; };
using wincolor_stdout_sink_mt = wincolor_sink<details::console_stdout, details::console_mutex>; using wincolor_stdout_sink_mt = wincolor_sink<details::console_stdout, details::console_mutex>;
@ -164,3 +70,7 @@ using wincolor_stderr_sink_st = wincolor_sink<details::console_stderr, details::
} // namespace sinks } // namespace sinks
} // namespace spdlog } // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "wincolor_sink-inl.h"
#endif

100
include/spdlog/spdlog-inl.h Normal file
View File

@ -0,0 +1,100 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include "spdlog/spdlog.h"
#endif
#include "spdlog/common.h"
#include "spdlog/details/pattern_formatter.h"
namespace spdlog {
SPDLOG_INLINE void initialize_logger(std::shared_ptr<logger> logger)
{
details::registry::instance().initialize_logger(std::move(logger));
}
SPDLOG_INLINE std::shared_ptr<logger> get(const std::string &name)
{
return details::registry::instance().get(name);
}
SPDLOG_INLINE void set_formatter(std::unique_ptr<spdlog::formatter> formatter)
{
details::registry::instance().set_formatter(std::move(formatter));
}
SPDLOG_INLINE void set_pattern(std::string pattern, pattern_time_type time_type)
{
set_formatter(std::unique_ptr<spdlog::formatter>(new pattern_formatter(std::move(pattern), time_type)));
}
SPDLOG_INLINE void set_level(level::level_enum log_level)
{
details::registry::instance().set_level(log_level);
}
SPDLOG_INLINE void flush_on(level::level_enum log_level)
{
details::registry::instance().flush_on(log_level);
}
SPDLOG_INLINE void flush_every(std::chrono::seconds interval)
{
details::registry::instance().flush_every(interval);
}
SPDLOG_INLINE void set_error_handler(void (*handler)(const std::string &msg))
{
details::registry::instance().set_error_handler(handler);
}
SPDLOG_INLINE void register_logger(std::shared_ptr<logger> logger)
{
details::registry::instance().register_logger(std::move(logger));
}
SPDLOG_INLINE void apply_all(const std::function<void(std::shared_ptr<logger>)> &fun)
{
details::registry::instance().apply_all(fun);
}
SPDLOG_INLINE void drop(const std::string &name)
{
details::registry::instance().drop(name);
}
SPDLOG_INLINE void drop_all()
{
details::registry::instance().drop_all();
}
SPDLOG_INLINE void shutdown()
{
details::registry::instance().shutdown();
}
SPDLOG_INLINE void set_automatic_registration(bool automatic_registation)
{
details::registry::instance().set_automatic_registration(automatic_registation);
}
SPDLOG_INLINE std::shared_ptr<spdlog::logger> default_logger()
{
return details::registry::instance().default_logger();
}
SPDLOG_INLINE spdlog::logger *default_logger_raw()
{
return details::registry::instance().get_default_raw();
}
SPDLOG_INLINE void set_default_logger(std::shared_ptr<spdlog::logger> default_logger)
{
details::registry::instance().set_default_logger(std::move(default_logger));
}
} // namespace spdlog

View File

@ -1,12 +1,12 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015-2018 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
// spdlog main header file. // spdlog main header file.
// see example.cpp for usage example // see example.cpp for usage example
#ifndef SPDLOG_H #ifndef SPDLOG_H
#define SPDLOG_H #define SPDLOG_H
#pragma once #pragma once
#include "spdlog/common.h" #include "spdlog/common.h"
@ -57,94 +57,52 @@ inline std::shared_ptr<spdlog::logger> create(std::string logger_name, SinkArgs
// auto console_sink = std::make_shared<spdlog::sinks::stdout_sink_mt>(); // auto console_sink = std::make_shared<spdlog::sinks::stdout_sink_mt>();
// auto console_logger = std::make_shared<spdlog::logger>("console_logger", console_sink); // auto console_logger = std::make_shared<spdlog::logger>("console_logger", console_sink);
// spdlog::initialize_logger(console_logger); // spdlog::initialize_logger(console_logger);
inline void initialize_logger(std::shared_ptr<logger> logger) void initialize_logger(std::shared_ptr<logger> logger);
{
details::registry::instance().initialize_logger(std::move(logger));
}
// Return an existing logger or nullptr if a logger with such name doesn't // Return an existing logger or nullptr if a logger with such name doesn't
// exist. // exist.
// example: spdlog::get("my_logger")->info("hello {}", "world"); // example: spdlog::get("my_logger")->info("hello {}", "world");
inline std::shared_ptr<logger> get(const std::string &name) std::shared_ptr<logger> get(const std::string &name);
{
return details::registry::instance().get(name);
}
// Set global formatter. Each sink in each logger will get a clone of this object // Set global formatter. Each sink in each logger will get a clone of this object
inline void set_formatter(std::unique_ptr<spdlog::formatter> formatter) void set_formatter(std::unique_ptr<spdlog::formatter> formatter);
{
details::registry::instance().set_formatter(std::move(formatter));
}
// Set global format string. // Set global format string.
// 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) 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(std::move(pattern), time_type)));
}
// Set global logging level // Set global logging level
inline void set_level(level::level_enum log_level) void set_level(level::level_enum log_level);
{
details::registry::instance().set_level(log_level);
}
// Set global flush level // Set global flush level
inline void flush_on(level::level_enum log_level) void flush_on(level::level_enum log_level);
{
details::registry::instance().flush_on(log_level);
}
// Start/Restart a periodic flusher thread // Start/Restart a periodic flusher thread
// Warning: Use only if all your loggers are thread safe! // Warning: Use only if all your loggers are thread safe!
inline void flush_every(std::chrono::seconds interval) void flush_every(std::chrono::seconds interval);
{
details::registry::instance().flush_every(interval);
}
// Set global error handler // Set global error handler
inline void set_error_handler(log_err_handler handler) void set_error_handler(void (*handler)(const std::string &msg));
{
details::registry::instance().set_error_handler(std::move(handler));
}
// Register the given logger with the given name // Register the given logger with the given name
inline void register_logger(std::shared_ptr<logger> logger) void register_logger(std::shared_ptr<logger> logger);
{
details::registry::instance().register_logger(std::move(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(const std::function<void(std::shared_ptr<logger>)> &fun) void apply_all(const std::function<void(std::shared_ptr<logger>)> &fun);
{
details::registry::instance().apply_all(fun);
}
// Drop the reference to the given logger // Drop the reference to the given logger
inline void drop(const std::string &name) void drop(const std::string &name);
{
details::registry::instance().drop(name);
}
// Drop all references from the registry // Drop all references from the registry
inline void drop_all() void drop_all();
{
details::registry::instance().drop_all();
}
// stop any running threads started by spdlog and clean registry loggers // stop any running threads started by spdlog and clean registry loggers
inline void shutdown() void shutdown();
{
details::registry::instance().shutdown();
}
// Automatic registration of loggers when using spdlog::create() or spdlog::create_async // Automatic registration of loggers when using spdlog::create() or spdlog::create_async
inline void set_automatic_registration(bool automatic_registation) void set_automatic_registration(bool automatic_registation);
{
details::registry::instance().set_automatic_registration(automatic_registation);
}
// API for using default logger (stdout_color_mt), // API for using default logger (stdout_color_mt),
// e.g: spdlog::info("Message {}", 1); // e.g: spdlog::info("Message {}", 1);
@ -161,20 +119,11 @@ inline void set_automatic_registration(bool automatic_registation)
// set_default_logger() *should not* be used concurrently with the default API. // set_default_logger() *should not* be used concurrently with the default API.
// e.g do not call set_default_logger() from one thread while calling spdlog::info() from another. // e.g do not call set_default_logger() from one thread while calling spdlog::info() from another.
inline std::shared_ptr<spdlog::logger> default_logger() std::shared_ptr<spdlog::logger> default_logger();
{
return details::registry::instance().default_logger();
}
inline spdlog::logger *default_logger_raw() spdlog::logger *default_logger_raw();
{
return details::registry::instance().get_default_raw();
}
inline void set_default_logger(std::shared_ptr<spdlog::logger> default_logger) void set_default_logger(std::shared_ptr<spdlog::logger> default_logger);
{
details::registry::instance().set_default_logger(std::move(default_logger));
}
template<typename... Args> template<typename... Args>
inline void log(source_loc source, level::level_enum lvl, const char *fmt, const Args &... args) inline void log(source_loc source, level::level_enum lvl, const char *fmt, const Args &... args)
@ -327,7 +276,8 @@ inline void critical(const wchar_t *fmt, const Args &... args)
// //
#define SPDLOG_LOGGER_CALL(logger, level, ...) \ #define SPDLOG_LOGGER_CALL(logger, level, ...) \
do { \ do \
{ \
if (logger->should_log(level)) \ if (logger->should_log(level)) \
logger->log(spdlog::source_loc{SPDLOG_FILE_BASENAME(__FILE__), __LINE__, SPDLOG_FUNCTION}, level, __VA_ARGS__); \ logger->log(spdlog::source_loc{SPDLOG_FILE_BASENAME(__FILE__), __LINE__, SPDLOG_FUNCTION}, level, __VA_ARGS__); \
} while (0) } while (0)
@ -380,4 +330,8 @@ inline void critical(const wchar_t *fmt, const Args &... args)
#define SPDLOG_CRITICAL(...) (void)0 #define SPDLOG_CRITICAL(...) (void)0
#endif #endif
#ifdef SPDLOG_HEADER_ONLY
#include "spdlog-inl.h"
#endif
#endif // SPDLOG_H #endif // SPDLOG_H

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once
@ -107,13 +105,6 @@
// #define SPDLOG_PREVENT_CHILD_FD // #define SPDLOG_PREVENT_CHILD_FD
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Uncomment to enable message counting feature.
// Use the %i in the logger pattern to display log message sequence id.
//
// #define SPDLOG_ENABLE_MESSAGE_COUNTER
///////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Uncomment to customize level names (e.g. "MT TRACE") // Uncomment to customize level names (e.g. "MT TRACE")
// //

View File

@ -1,7 +1,5 @@
// // Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT) // Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once #pragma once

103
src/spdlog.cpp Normal file
View File

@ -0,0 +1,103 @@
// Copyright(c) 2015-present Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#ifndef SPDLOG_COMPILED_LIB
#error Please define SPDLOG_COMPILED_LIB to compile this file.
#endif
#include <mutex>
#include <chrono>
#include "spdlog/details/null_mutex.h"
#include "spdlog/async.h"
#include "spdlog/spdlog-inl.h"
#include "spdlog/common-inl.h"
#include "spdlog/logger-inl.h"
template spdlog::logger::logger(std::string name, sinks_init_list::iterator begin, sinks_init_list::iterator end);
#include "spdlog/async_logger-inl.h"
#include "spdlog/details/log_msg-inl.h"
#include "spdlog/sinks/sink-inl.h"
#include "spdlog/sinks/base_sink-inl.h"
template class spdlog::sinks::base_sink<std::mutex>;
template class spdlog::sinks::base_sink<spdlog::details::null_mutex>;
#include "spdlog/sinks/basic_file_sink-inl.h"
template class spdlog::sinks::basic_file_sink<std::mutex>;
template class spdlog::sinks::basic_file_sink<spdlog::details::null_mutex>;
#include "spdlog/sinks/rotating_file_sink-inl.h"
template class spdlog::sinks::rotating_file_sink<std::mutex>;
template class spdlog::sinks::rotating_file_sink<spdlog::details::null_mutex>;
#include "spdlog/details/registry-inl.h"
#include "spdlog/details/os-inl.h"
#include "spdlog/details/periodic_worker-inl.h"
#include "spdlog/details/file_helper-inl.h"
#include "spdlog/details/pattern_formatter-inl.h"
#include "spdlog/details/thread_pool-inl.h"
template class spdlog::details::mpmc_blocking_queue<spdlog::details::async_msg>;
#ifdef _WIN32
#include "spdlog/sinks/wincolor_sink-inl.h"
template class spdlog::sinks::wincolor_sink<spdlog::details::console_stdout, spdlog::details::console_mutex>;
template class spdlog::sinks::wincolor_sink<spdlog::details::console_stdout, spdlog::details::console_nullmutex>;
template class spdlog::sinks::wincolor_sink<spdlog::details::console_stderr, spdlog::details::console_mutex>;
template class spdlog::sinks::wincolor_sink<spdlog::details::console_stderr, spdlog::details::console_nullmutex>;
#else
#include "spdlog/sinks/ansicolor_sink-inl.h"
template class spdlog::sinks::ansicolor_sink<spdlog::details::console_stdout, spdlog::details::console_mutex>;
template class spdlog::sinks::ansicolor_sink<spdlog::details::console_stdout, spdlog::details::console_nullmutex>;
template class spdlog::sinks::ansicolor_sink<spdlog::details::console_stderr, spdlog::details::console_mutex>;
template class spdlog::sinks::ansicolor_sink<spdlog::details::console_stderr, spdlog::details::console_nullmutex>;
#endif
#include "spdlog/sinks/stdout_color_sinks-inl.h"
template std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt<spdlog::synchronous_factory>(const std::string &logger_name, color_mode mode);
template std::shared_ptr<spdlog::logger> spdlog::stdout_color_st<spdlog::synchronous_factory>(const std::string &logger_name, color_mode mode);
template std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt<spdlog::synchronous_factory>(const std::string &logger_name, color_mode mode);
template std::shared_ptr<spdlog::logger> spdlog::stderr_color_st<spdlog::synchronous_factory>(const std::string &logger_name, color_mode mode);
template std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt<spdlog::async_factory>(const std::string &logger_name, color_mode mode);
template std::shared_ptr<spdlog::logger> spdlog::stdout_color_st<spdlog::async_factory>(const std::string &logger_name, color_mode mode);
template std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt<spdlog::async_factory>(const std::string &logger_name, color_mode mode);
template std::shared_ptr<spdlog::logger> spdlog::stderr_color_st<spdlog::async_factory>(const std::string &logger_name, color_mode mode);
// Slightly modified version of fmt lib's format.cc source file.
// Copyright (c) 2012 - 2016, Victor Zverovich
// All rights reserved.
#if !defined(SPDLOG_FMT_EXTERNAL)
#include "spdlog/fmt/bundled/format-inl.h"
FMT_BEGIN_NAMESPACE
template struct internal::basic_data<void>;
template FMT_API internal::locale_ref::locale_ref(const std::locale &loc);
template FMT_API std::locale internal::locale_ref::get<std::locale>() const;
// Explicit instantiations for char.
template FMT_API char internal::thousands_sep_impl(locale_ref);
template FMT_API void internal::basic_buffer<char>::append(const char *, const char *);
template FMT_API void internal::arg_map<format_context>::init(const basic_format_args<format_context> &args);
template FMT_API int internal::char_traits<char>::format_float(char *, std::size_t, const char *, int, double);
template FMT_API int internal::char_traits<char>::format_float(char *, std::size_t, const char *, int, long double);
template FMT_API std::string internal::vformat<char>(string_view, basic_format_args<format_context>);
template FMT_API format_context::iterator internal::vformat_to(internal::buffer &, string_view, basic_format_args<format_context>);
template FMT_API void internal::sprintf_format(double, internal::buffer &, core_format_specs);
template FMT_API void internal::sprintf_format(long double, internal::buffer &, core_format_specs);
// Explicit instantiations for wchar_t.
template FMT_API wchar_t internal::thousands_sep_impl(locale_ref);
template FMT_API void internal::basic_buffer<wchar_t>::append(const wchar_t *, const wchar_t *);
template FMT_API void internal::arg_map<wformat_context>::init(const basic_format_args<wformat_context> &);
template FMT_API int internal::char_traits<wchar_t>::format_float(wchar_t *, std::size_t, const wchar_t *, int, double);
template FMT_API int internal::char_traits<wchar_t>::format_float(wchar_t *, std::size_t, const wchar_t *, int, long double);
template FMT_API std::wstring internal::vformat<wchar_t>(wstring_view, basic_format_args<wformat_context>);
FMT_END_NAMESPACE
#endif

View File

@ -1,7 +1,3 @@
project(spdlog-utests CXX)
find_package(Threads REQUIRED)
set(SPDLOG_UTESTS_SOURCES set(SPDLOG_UTESTS_SOURCES
test_errors.cpp test_errors.cpp
test_file_helper.cpp test_file_helper.cpp
@ -19,11 +15,10 @@ set(SPDLOG_UTESTS_SOURCES
test_sink.h test_sink.h
test_fmt_helper.cpp) test_fmt_helper.cpp)
add_executable(${PROJECT_NAME} ${SPDLOG_UTESTS_SOURCES}) add_executable(spdlog-utests ${SPDLOG_UTESTS_SOURCES})
target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) target_link_libraries(spdlog-utests spdlog)
target_link_libraries(${PROJECT_NAME} PRIVATE spdlog::spdlog)
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs")
enable_testing() enable_testing()
add_test(NAME ${PROJECT_NAME} COMMAND ${PROJECT_NAME}) add_test(NAME spdlog-utests COMMAND spdlog-utests)

View File

@ -1,22 +0,0 @@
CXX ?= g++
CXXFLAGS = -Wall -pedantic -std=c++11 -pthread -Wconversion -O3 -I../include -fmax-errors=1
LDPFALGS = -pthread -lsystemd
CPP_FILES := $(wildcard *.cpp)
OBJ_FILES := $(addprefix ./,$(notdir $(CPP_FILES:.cpp=.o)))
tests: $(OBJ_FILES)
$(CXX) $(CXXFLAGS) $(LDPFALGS) -o $@ $^
mkdir -p logs
%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
rm -f tests *.o logs/*.txt
rebuild: clean tests

View File

@ -11,7 +11,6 @@
#include <string> #include <string>
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_DEBUG #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_DEBUG
#define SPDLOG_ENABLE_MESSAGE_COUNTER
#include "spdlog/spdlog.h" #include "spdlog/spdlog.h"
#include "spdlog/async.h" #include "spdlog/async.h"
@ -21,3 +20,4 @@
#include "spdlog/sinks/ostream_sink.h" #include "spdlog/sinks/ostream_sink.h"
#include "spdlog/sinks/rotating_file_sink.h" #include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h" #include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/details/pattern_formatter.h"

View File

@ -39,8 +39,7 @@ TEST_CASE("default_error_handler", "[errors]]")
} }
struct custom_ex struct custom_ex
{ {};
};
TEST_CASE("custom_error_handler", "[errors]]") TEST_CASE("custom_error_handler", "[errors]]")
{ {
prepare_logdir(); prepare_logdir();

View File

@ -69,7 +69,7 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]]")
logger->info("Test message {}", i); logger->info("Test message {}", i);
} }
// drop causes the logger destructor to be called, which is required so the // drop causes the logger destructor to be called, which is required so the
// next logger can rename the first output file. // next logger can rename the first output file.
spdlog::drop(logger->name()); spdlog::drop(logger->name());
} }

View File

@ -1,5 +1,6 @@
#include "includes.h" #include "includes.h"
#include "spdlog/details/fmt_helper.h"
void test_pad2(int n, const char *expected) void test_pad2(int n, const char *expected)
{ {

View File

@ -107,7 +107,6 @@ TEST_CASE("clone-logger", "[clone]")
cloned->info("Some message 2"); cloned->info("Some message 2");
auto test_sink = std::static_pointer_cast<sinks::test_sink_mt>(cloned->sinks()[0]); auto test_sink = std::static_pointer_cast<sinks::test_sink_mt>(cloned->sinks()[0]);
REQUIRE(test_sink->msg_counter() == 2);
spdlog::drop_all(); spdlog::drop_all();
} }
@ -130,7 +129,6 @@ TEST_CASE("clone async", "[clone]")
spdlog::details::os::sleep_for_millis(10); spdlog::details::os::sleep_for_millis(10);
auto test_sink = std::static_pointer_cast<sinks::test_sink_mt>(cloned->sinks()[0]); auto test_sink = std::static_pointer_cast<sinks::test_sink_mt>(cloned->sinks()[0]);
REQUIRE(test_sink->msg_counter() == 2);
spdlog::drop_all(); spdlog::drop_all();
} }
@ -176,22 +174,6 @@ TEST_CASE("to_hex_no_delimiter", "[to_hex]")
REQUIRE(ends_with(output, "0000: 090A0B0CFFFF" + std::string(spdlog::details::os::default_eol))); REQUIRE(ends_with(output, "0000: 090A0B0CFFFF" + std::string(spdlog::details::os::default_eol)));
} }
TEST_CASE("message_counter", "[message_counter]")
{
std::ostringstream oss;
auto oss_sink = std::make_shared<spdlog::sinks::ostream_sink_mt>(oss);
spdlog::logger oss_logger("oss", oss_sink);
oss_logger.set_pattern("%i %v");
oss_logger.info("Hello");
REQUIRE(oss.str() == "000001 Hello" + std::string(spdlog::details::os::default_eol));
oss.str("");
oss_logger.info("Hello again");
REQUIRE(oss.str() == "000002 Hello again" + std::string(spdlog::details::os::default_eol));
}
TEST_CASE("default logger API", "[default logger]") TEST_CASE("default logger API", "[default logger]")
{ {
std::ostringstream oss; std::ostringstream oss;

View File

@ -1,98 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27428.2037
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tests", "tests.vcxproj", "{59A07559-5F38-4DD6-A7FA-DB4153690B42}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "spdlog", "spdlog", "{0C043010-E40A-43B9-A5EA-B931FC8B6EFB}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\async.h = ..\include\spdlog\async.h
..\include\spdlog\async_logger.h = ..\include\spdlog\async_logger.h
..\include\spdlog\common.h = ..\include\spdlog\common.h
..\include\spdlog\formatter.h = ..\include\spdlog\formatter.h
..\include\spdlog\logger.h = ..\include\spdlog\logger.h
..\include\spdlog\spdlog.h = ..\include\spdlog\spdlog.h
..\include\spdlog\tweakme.h = ..\include\spdlog\tweakme.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "details", "details", "{C8A207B7-6930-4D28-85BB-EA79ADFD7DAC}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\details\async_logger_impl.h = ..\include\spdlog\details\async_logger_impl.h
..\include\spdlog\details\file_helper.h = ..\include\spdlog\details\file_helper.h
..\include\spdlog\details\log_msg.h = ..\include\spdlog\details\log_msg.h
..\include\spdlog\details\logger_impl.h = ..\include\spdlog\details\logger_impl.h
..\include\spdlog\details\mpmc_bounded_q.h = ..\include\spdlog\details\mpmc_bounded_q.h
..\include\spdlog\details\null_mutex.h = ..\include\spdlog\details\null_mutex.h
..\include\spdlog\details\os.h = ..\include\spdlog\details\os.h
..\include\spdlog\details\pattern_formatter.h = ..\include\spdlog\details\pattern_formatter.h
..\include\spdlog\details\registry.h = ..\include\spdlog\details\registry.h
..\include\spdlog\details\spdlog_impl.h = ..\include\spdlog\details\spdlog_impl.h
..\include\spdlog\details\thread_pool.h = ..\include\spdlog\details\thread_pool.h
..\include\spdlog\details\traits.h = ..\include\spdlog\details\traits.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "fmt", "fmt", "{6512BA57-E9B9-4971-BC3A-83C784CC59A5}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\fmt\fmt.h = ..\include\spdlog\fmt\fmt.h
..\include\spdlog\fmt\ostr.h = ..\include\spdlog\fmt\ostr.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "bundled", "bundled", "{F0D4A944-E0C7-4575-8254-06AC92B384E6}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\fmt\bundled\format.cc = ..\include\spdlog\fmt\bundled\format.cc
..\include\spdlog\fmt\bundled\format.h = ..\include\spdlog\fmt\bundled\format.h
..\include\spdlog\fmt\bundled\LICENSE.rst = ..\include\spdlog\fmt\bundled\LICENSE.rst
..\include\spdlog\fmt\bundled\ostream.cc = ..\include\spdlog\fmt\bundled\ostream.cc
..\include\spdlog\fmt\bundled\ostream.h = ..\include\spdlog\fmt\bundled\ostream.h
..\include\spdlog\fmt\bundled\posix.cc = ..\include\spdlog\fmt\bundled\posix.cc
..\include\spdlog\fmt\bundled\posix.h = ..\include\spdlog\fmt\bundled\posix.h
..\include\spdlog\fmt\bundled\time.h = ..\include\spdlog\fmt\bundled\time.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sinks", "sinks", "{093AE34A-B617-467E-8F31-3C5A85EF51EB}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\sinks\android_sink.h = ..\include\spdlog\sinks\android_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\dist_sink.h = ..\include\spdlog\sinks\dist_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\ostream_sink.h = ..\include\spdlog\sinks\ostream_sink.h
..\include\spdlog\sinks\sink.h = ..\include\spdlog\sinks\sink.h
..\include\spdlog\sinks\stdout_color_sinks.h = ..\include\spdlog\sinks\stdout_color_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\wincolor_sink.h = ..\include\spdlog\sinks\wincolor_sink.h
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{59A07559-5F38-4DD6-A7FA-DB4153690B42}.Debug|Win32.ActiveCfg = Debug|Win32
{59A07559-5F38-4DD6-A7FA-DB4153690B42}.Debug|Win32.Build.0 = Debug|Win32
{59A07559-5F38-4DD6-A7FA-DB4153690B42}.Debug|x64.ActiveCfg = Debug|x64
{59A07559-5F38-4DD6-A7FA-DB4153690B42}.Debug|x64.Build.0 = Debug|x64
{59A07559-5F38-4DD6-A7FA-DB4153690B42}.Release|Win32.ActiveCfg = Release|Win32
{59A07559-5F38-4DD6-A7FA-DB4153690B42}.Release|Win32.Build.0 = Release|Win32
{59A07559-5F38-4DD6-A7FA-DB4153690B42}.Release|x64.ActiveCfg = Release|x64
{59A07559-5F38-4DD6-A7FA-DB4153690B42}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{C8A207B7-6930-4D28-85BB-EA79ADFD7DAC} = {0C043010-E40A-43B9-A5EA-B931FC8B6EFB}
{6512BA57-E9B9-4971-BC3A-83C784CC59A5} = {0C043010-E40A-43B9-A5EA-B931FC8B6EFB}
{F0D4A944-E0C7-4575-8254-06AC92B384E6} = {6512BA57-E9B9-4971-BC3A-83C784CC59A5}
{093AE34A-B617-467E-8F31-3C5A85EF51EB} = {0C043010-E40A-43B9-A5EA-B931FC8B6EFB}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1D363F0E-2DC2-4544-963A-9812679AFF6B}
EndGlobalSection
EndGlobal

View File

@ -1,148 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{59A07559-5F38-4DD6-A7FA-DB4153690B42}</ProjectGuid>
<RootNamespace>tests</RootNamespace>
<WindowsTargetPlatformVersion>10.0.16299.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(SolutionDir)\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_MBCS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(SolutionDir)..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(SolutionDir)\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_MBCS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(SolutionDir)..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="errors.cpp" />
<ClCompile Include="file_helper.cpp" />
<ClCompile Include="file_log.cpp" />
<ClCompile Include="test_async.cpp" />
<ClCompile Include="test_misc.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="registry.cpp" />
<ClCompile Include="test_macros.cpp" />
<ClCompile Include="test_pattern_formatter.cpp" />
<ClCompile Include="utils.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="catch.hpp" />
<ClInclude Include="includes.h" />
<ClInclude Include="utils.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,60 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="file_log.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="registry.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="file_helper.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="utils.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="errors.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="test_macros.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="test_pattern_formatter.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="test_misc.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="test_async.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="includes.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="catch.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="utils.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>