From 414ff25564d85f06c668133f205c922bf9456d28 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 13:31:57 +0200 Subject: [PATCH 001/157] lite wip --- CMakeLists.txt | 7 ++++ lite-example/CMakeLists.txt | 13 ++++++++ lite-example/create_lite.cpp | 15 +++++++++ lite-example/example.cpp | 7 ++++ lite/CMakeLists.txt | 6 ++++ lite/logger.cpp | 21 ++++++++++++ lite/logger.h | 64 ++++++++++++++++++++++++++++++++++++ lite/spd_types.h | 24 ++++++++++++++ 8 files changed, 157 insertions(+) create mode 100644 lite-example/CMakeLists.txt create mode 100644 lite-example/create_lite.cpp create mode 100644 lite-example/example.cpp create mode 100644 lite/CMakeLists.txt create mode 100644 lite/logger.cpp create mode 100644 lite/logger.h create mode 100644 lite/spd_types.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 9f0951fc..c4093403 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,6 +54,8 @@ option(SPDLOG_BUILD_BENCH "Build benchmarks (Requires https://github.com/google/ option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) +option(SPDLOG_BUILD_LITE "Build spdlog lite" ${SPDLOG_MASTER_PROJECT}) + if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) find_package(fmt REQUIRED CONFIG) @@ -86,6 +88,11 @@ if(SPDLOG_BUILD_BENCH) add_subdirectory(bench) endif() +if(SPDLOG_BUILD_LITE) + add_subdirectory(lite) + add_subdirectory(lite-example) +endif() + #--------------------------------------------------------------------------------------- # Install/export targets and files #--------------------------------------------------------------------------------------- diff --git a/lite-example/CMakeLists.txt b/lite-example/CMakeLists.txt new file mode 100644 index 00000000..d152ecd1 --- /dev/null +++ b/lite-example/CMakeLists.txt @@ -0,0 +1,13 @@ +project(spdlog-lite-example CXX) + +find_package(Threads REQUIRED) + +set(LITE_SOURCES example.cpp create_lite.cpp) + +add_executable(${PROJECT_NAME} ${LITE_SOURCES}) + +include_directories(../lite) +target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) +target_link_libraries(${PROJECT_NAME} PRIVATE spdlog_lite) + + diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp new file mode 100644 index 00000000..aa375d4e --- /dev/null +++ b/lite-example/create_lite.cpp @@ -0,0 +1,15 @@ +#include "logger.h" +#include "spdlog/spdlog.h" + + +spdlog::lite::logger spdlog::create_lite(void* ctx) +{ + if(ctx) { + //.. + } + auto logger_impl = spdlog::default_logger(); + logger_impl->set_level(spdlog::level::trace); + return spdlog::lite::logger(logger_impl); +} + + diff --git a/lite-example/example.cpp b/lite-example/example.cpp new file mode 100644 index 00000000..a1a78eb6 --- /dev/null +++ b/lite-example/example.cpp @@ -0,0 +1,7 @@ +#include "logger.h" + +int main() +{ + auto l = spdlog::create_lite(); + l.trace("HELLO {}!!!", "lite"); +} \ No newline at end of file diff --git a/lite/CMakeLists.txt b/lite/CMakeLists.txt new file mode 100644 index 00000000..3ed30be7 --- /dev/null +++ b/lite/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.1) +project(spdlog_lite) + +add_library(spdlog_lite logger.cpp) + +target_link_libraries(spdlog_lite spdlog::spdlog) diff --git a/lite/logger.cpp b/lite/logger.cpp new file mode 100644 index 00000000..6098df84 --- /dev/null +++ b/lite/logger.cpp @@ -0,0 +1,21 @@ +#include "logger.h" +#include "spdlog/spdlog.h" +#include "spdlog/logger.h" + +spdlog::lite::logger::logger(std::shared_ptr impl) +{ + impl_ = std::move(impl); +} + + +bool spdlog::lite::logger::should_log(spdlog::lite::level lvl) const SPDLOG_NOEXCEPT +{ + auto spd_level = static_cast(lvl); + return impl_->should_log(spd_level);//TODO level +} + +void spdlog::lite::logger::log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted) +{ + auto spd_level = static_cast(lvl); + impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); //TODO and source_loc +} \ No newline at end of file diff --git a/lite/logger.h b/lite/logger.h new file mode 100644 index 00000000..6cc60b09 --- /dev/null +++ b/lite/logger.h @@ -0,0 +1,64 @@ +// +// Created by gabi on 3/16/19. +// + +#ifndef SPDLOG_LIB_LOGGER_H +#define SPDLOG_LIB_LOGGER_H + +#include +#include "spd_types.h" +#include "spdlog/fmt/fmt.h" + + +namespace spdlog { + class logger; + + namespace lite { + class logger { + public: + logger() = default; + + logger(std::shared_ptr impl); + logger(const logger&) = default; + logger(logger&&) = default; + logger& operator=(const logger&) = default; + + ~logger() = default; + + bool should_log(spdlog::lite::level lvl) const noexcept; + + template + void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) { + if (!should_log(lvl)) { + return; + } + fmt::memory_buffer formatted_buf; + fmt::format_to(formatted_buf, fmt, args...); + log_formatted_(lvl, formatted_buf); + } + +// template +// void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) +// { +// log(lvl, fmt, args...); +// } + + template + void trace(const char *fmt, const Args &... args) { + log(spdlog::lite::level::trace, fmt, args...); + } + + protected: + std::shared_ptr impl_; + + void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + + }; + + } // namespace lite + + // factory to create lite logger + // implement it in a dedicated compilation unit for fast compiles + spdlog::lite::logger create_lite(void* ctx = nullptr); +} // namespace spdlog +#endif //SPDLOG_LIB_LOGGER_H diff --git a/lite/spd_types.h b/lite/spd_types.h new file mode 100644 index 00000000..94be9b34 --- /dev/null +++ b/lite/spd_types.h @@ -0,0 +1,24 @@ +// +// Copyright(c) 2019 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +// core types, forward declarations and defines used by spdlog + +#pragma once + +namespace spdlog +{ +namespace lite +{ + enum class level{ + trace, + debug, + info, + warning, + error, + critical, + off + + }; +}} \ No newline at end of file From ee502aed491e31a0e3b2bd14e7c59ec21d0403a4 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 16:15:58 +0200 Subject: [PATCH 002/157] wip lite --- example/example.cpp | 240 ++------------------------------------- lite-example/example.cpp | 4 +- lite/logger.cpp | 76 +++++++++++-- lite/logger.h | 139 ++++++++++++++++++++--- lite/spd_types.h | 24 ---- 5 files changed, 205 insertions(+), 278 deletions(-) delete mode 100644 lite/spd_types.h diff --git a/example/example.cpp b/example/example.cpp index 345f8bd1..0c3b8395 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -1,235 +1,11 @@ -// -// Copyright(c) 2015 Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) -// -// -// spdlog usage example -// -// - -#include - -void stdout_logger_example(); -void basic_example(); -void rotating_example(); -void daily_example(); -void async_example(); -void binary_example(); -void trace_example(); -void multi_sink_example(); -void user_defined_example(); -void err_handler_example(); -void syslog_example(); -void clone_example(); - #include "spdlog/spdlog.h" -int main(int, char *[]) +int main() { - 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::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); - spdlog::info("Support for floats {:03.2f}", 1.23456); - spdlog::info("Positional args are {1} {0}..", "too", "supported"); - spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left"); - - // Runtime log levels - spdlog::set_level(spdlog::level::info); // Set global log level to info - spdlog::debug("This message should not be displayed!"); - spdlog::set_level(spdlog::level::trace); // Set specific logger's log level - spdlog::debug("This message should be displayed.."); - - // Customize msg format for all loggers - spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v"); - spdlog::info("This an info message with custom format"); - spdlog::set_pattern("%+"); // back to default format - - try - { - stdout_logger_example(); - basic_example(); - rotating_example(); - daily_example(); - clone_example(); - async_example(); - binary_example(); - multi_sink_example(); - user_defined_example(); - err_handler_example(); - trace_example(); - - // Flush all *registered* loggers using a worker thread every 3 seconds. - // note: registered loggers *must* be thread safe for this to work correctly! - spdlog::flush_every(std::chrono::seconds(3)); - - // Apply some function on all registered loggers - spdlog::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); - - // Release all spdlog resources, and drop all loggers in the registry. - // This is optional (only mandatory if using windows + async log). - spdlog::shutdown(); - } - - // Exceptions will only be thrown upon failed logger or sink construction (not during logging). - catch (const spdlog::spdlog_ex &ex) - { - std::printf("Log initialization failed: %s\n", ex.what()); - return 1; - } -} - -#include "spdlog/sinks/stdout_color_sinks.h" -// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed. -void stdout_logger_example() -{ - // Create color multi threaded logger. - auto console = spdlog::stdout_color_mt("console"); - // or for stderr: - // auto console = spdlog::stderr_color_mt("error-logger"); -} - -#include "spdlog/sinks/basic_file_sink.h" -void basic_example() -{ - // Create basic file logger (not rotated). - auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt"); -} - -#include "spdlog/sinks/rotating_file_sink.h" -void rotating_example() -{ - // Create a file rotating logger with 5mb size max and 3 rotated files. - auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); -} - -#include "spdlog/sinks/daily_file_sink.h" -void daily_example() -{ - // Create a daily logger - a new file is created every day on 2:30am. - auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); -} - -// Clone a logger and give it new name. -// Useful for creating component/subsystem loggers from some "root" logger. -void clone_example() -{ - auto network_logger = spdlog::default_logger()->clone("network"); - network_logger->info("Logging network stuff.."); -} - -#include "spdlog/async.h" -void async_example() -{ - // Default thread pool settings can be modified *before* creating the async logger: - // spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread. - auto async_file = spdlog::basic_logger_mt("async_file_logger", "logs/async_log.txt"); - // alternatively: - // auto async_file = spdlog::create_async("async_file_logger", "logs/async_log.txt"); - - for (int i = 1; i < 101; ++i) - { - async_file->info("Async message #{}", i); - } -} - -// Log binary data as hex. -// Many types of std::container types can be used. -// Iterator ranges are supported too. -// Format flags: -// {:X} - print in uppercase. -// {:s} - don't separate each byte with space. -// {:p} - don't print the position on each line start. -// {:n} - don't split the output to lines. - -#include "spdlog/fmt/bin_to_hex.h" -void binary_example() -{ - std::vector buf; - for (int i = 0; i < 80; i++) - { - buf.push_back(static_cast(i & 0xff)); - } - spdlog::info("Binary example: {}", spdlog::to_hex(buf)); - spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10)); - // more examples: - // logger->info("uppercase: {:X}", spdlog::to_hex(buf)); - // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf)); - // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf)); -} - -// Compile time log levels. -// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE) -void trace_example() -{ - // trace from default logger - SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23); - // debug from default logger - SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23); - - // trace from logger object - auto logger = spdlog::get("file_logger"); - SPDLOG_LOGGER_TRACE(logger, "another trace message"); -} - -// A logger with multiple sinks (stdout and file) - each with a different format and log level. -void multi_sink_example() -{ - auto console_sink = std::make_shared(); - console_sink->set_level(spdlog::level::warn); - console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v"); - - auto file_sink = std::make_shared("logs/multisink.txt", true); - file_sink->set_level(spdlog::level::trace); - - spdlog::logger logger("multi_sink", {console_sink, file_sink}); - logger.set_level(spdlog::level::debug); - logger.warn("this should appear in both console and file"); - logger.info("this message should not appear in the console, only in the file"); -} - -// User defined types logging by implementing operator<< -#include "spdlog/fmt/ostr.h" // must be included -struct my_type -{ - int i; - template - friend OStream &operator<<(OStream &os, const my_type &c) - { - return os << "[my_type i=" << c.i << "]"; - } -}; - -void user_defined_example() -{ - spdlog::info("user defined type: {}", my_type{14}); -} - -// Custom error handler. Will be triggered on log failure. -void err_handler_example() -{ - // can be set globally or per logger(logger->set_error_handler(..)) - spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); }); -} - -// syslog example (linux/osx/freebsd) -#ifndef _WIN32 -#include "spdlog/sinks/syslog_sink.h" -void syslog_example() -{ - std::string ident = "spdlog-example"; - auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID); - syslog_logger->warn("This is warning that will end up in syslog."); -} -#endif - -// Android example. -#if defined(__ANDROID__) -#include "spdlog/sinks/android_sink.h" -void android_example() -{ - std::string tag = "spdlog-android"; - auto android_logger = spdlog::android_logger_mt("android", tag); - android_logger->critical("Use \"adb shell logcat\" to view this message."); -} - -#endif + auto l = spdlog::default_logger(); + l->trace("HELLO {}!!!", "lite"); + l->debug("HELLO {}!!!", "lite"); + l->info("HELLO {}!!!", "lite"); + l->warn("HELLO {}!!!", "lite"); + l->critical("HELLO s{}!!!", "lite"); +} \ No newline at end of file diff --git a/lite-example/example.cpp b/lite-example/example.cpp index a1a78eb6..05d772aa 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -2,6 +2,6 @@ int main() { - auto l = spdlog::create_lite(); - l.trace("HELLO {}!!!", "lite"); + //auto l = spdlog::create_lite(); + spdlog::lite::info("HELLO info {}", 123); } \ No newline at end of file diff --git a/lite/logger.cpp b/lite/logger.cpp index 6098df84..39841553 100644 --- a/lite/logger.cpp +++ b/lite/logger.cpp @@ -2,20 +2,82 @@ #include "spdlog/spdlog.h" #include "spdlog/logger.h" +static spdlog::level::level_enum to_spdlog_level(spdlog::lite::level level) +{ + return static_cast(level); +} + +static spdlog::lite::level to_lite_level(spdlog::level::level_enum level) +{ + return static_cast(level); +} + spdlog::lite::logger::logger(std::shared_ptr impl) { impl_ = std::move(impl); } - -bool spdlog::lite::logger::should_log(spdlog::lite::level lvl) const SPDLOG_NOEXCEPT +bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NOEXCEPT { - auto spd_level = static_cast(lvl); + auto spd_level = to_spdlog_level(level); return impl_->should_log(spd_level);//TODO level } -void spdlog::lite::logger::log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted) +void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt::memory_buffer &formatted) { - auto spd_level = static_cast(lvl); - impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); //TODO and source_loc -} \ No newline at end of file + auto spd_level = to_spdlog_level(level); + impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); +} + + +void spdlog::lite::logger::log_formatted_src(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) +{ + auto spd_level = to_spdlog_level(lvl); + spdlog::source_loc source_loc{src.filename, src.line, src.funcname}; + impl_->log(source_loc, spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); +} + +void spdlog::lite::logger::set_level(spdlog::lite::level level) +{ + auto spd_level = to_spdlog_level(level); + impl_->set_level(spd_level); +} + +spdlog::lite::level spdlog::lite::logger::get_level() const +{ + return to_lite_level(impl_->level()); +} + +std::string spdlog::lite::logger::name() const +{ + return impl_->name(); +} + +void spdlog::lite::logger::flush() +{ + impl_->flush(); +} + +void spdlog::lite::logger::flush_on(spdlog::lite::level level) +{ + auto spd_level = to_spdlog_level(level); + impl_->flush_on(spd_level); +} + +spdlog::lite::level spdlog::lite::logger::flush_level() const +{ + return to_lite_level(impl_->flush_level()); +} + +// pattern +void spdlog::lite::logger::set_pattern(std::string pattern) +{ + impl_->set_pattern(std::move(pattern)); +} + + +spdlog::lite::logger &spdlog::lite::default_logger() +{ + static spdlog::lite::logger s_default(spdlog::default_logger()); + return s_default; +} diff --git a/lite/logger.h b/lite/logger.h index 6cc60b09..b762b3f5 100644 --- a/lite/logger.h +++ b/lite/logger.h @@ -1,19 +1,36 @@ // // Created by gabi on 3/16/19. // - -#ifndef SPDLOG_LIB_LOGGER_H -#define SPDLOG_LIB_LOGGER_H +#pragma once #include -#include "spd_types.h" +#include #include "spdlog/fmt/fmt.h" +//#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::info, __VA_ARGS__) +//#define SPDLITE_INFO(...) SPDLOG_LOGGER_INFO(spdlog::default_logger_raw(), __VA_ARGS__) + namespace spdlog { class logger; namespace lite { + enum class level{ + trace, + debug, + info, + warn, + err, + critical, + off + }; + + struct src_loc { + const char *filename; + int line; + const char* funcname; + }; + class logger { public: logger() = default; @@ -37,28 +54,124 @@ namespace spdlog { log_formatted_(lvl, formatted_buf); } -// template -// void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) -// { -// log(lvl, fmt, args...); -// } template - void trace(const char *fmt, const Args &... args) { + void log(const spdlog::lite::src_loc& src, spdlog::lite::level lvl, const char *fmt, const Args &... args) { + if (!should_log(lvl)) { + return; + } + fmt::memory_buffer formatted_buf; + fmt::format_to(formatted_buf, fmt, args...); + log_formatted_src(src, lvl, formatted_buf); + } + + + template + void trace(const char *fmt, const Args &... args) + { log(spdlog::lite::level::trace, fmt, args...); } + template + void trace(const char* source_file, int source_line, const char* source_func, const char *fmt, const Args &... args) + { + spdlog::lite::src_loc src{source_file, source_line, source_func}; + log(src, spdlog::lite::level::trace, fmt, args...); + } + + template + void debug(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::debug, fmt, args...); + } + + template + void info(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::info, fmt, args...); + } + + template + void warn(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::warn, fmt, args...); + } + + template + void error(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::err, fmt, args...); + } + + template + void critical(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::critical, fmt, args...); + } + + std::string name() const; + + // level + void set_level(lite::level level); + lite::level get_level() const; + + // flush + void flush(); + void flush_on(spdlog::lite::level log_level); + spdlog::lite::level flush_level() const; + + // pattern + void set_pattern(std::string pattern); + protected: std::shared_ptr impl_; - void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + void log_formatted_src(const spdlog::lite::src_loc& src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); }; + spdlog::lite::logger& default_logger(); + + + template + void trace(const char *fmt, const Args &... args) + { + default_logger().trace(fmt, args...); + } + template + void debug(const char *fmt, const Args &... args) + { + default_logger().debug(fmt, args...); + } + + template + void info(const char *fmt, const Args &... args) + { + default_logger().info(fmt, args...); + } + + template + void warn(const char *fmt, const Args &... args) + { + default_logger().warn(fmt, args...); + } + + template + void error(const char *fmt, const Args &... args) + { + default_logger().error(fmt, args...); + } + + template + void critical(const char *fmt, const Args &... args) + { + default_logger().critical(fmt, args...); + } + } // namespace lite // factory to create lite logger // implement it in a dedicated compilation unit for fast compiles spdlog::lite::logger create_lite(void* ctx = nullptr); -} // namespace spdlog -#endif //SPDLOG_LIB_LOGGER_H + +} // namespace spdlog \ No newline at end of file diff --git a/lite/spd_types.h b/lite/spd_types.h deleted file mode 100644 index 94be9b34..00000000 --- a/lite/spd_types.h +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright(c) 2019 Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) -// - -// core types, forward declarations and defines used by spdlog - -#pragma once - -namespace spdlog -{ -namespace lite -{ - enum class level{ - trace, - debug, - info, - warning, - error, - critical, - off - - }; -}} \ No newline at end of file From c29b7d22d96999dcb696a16a5d1dfc804defd10a Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 16:39:05 +0200 Subject: [PATCH 003/157] wip lite --- lite-example/example.cpp | 6 ++- lite/logger.h | 86 +++++++++++++++++++++++++++++++++++----- 2 files changed, 80 insertions(+), 12 deletions(-) diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 05d772aa..929e75dd 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -1,7 +1,11 @@ +#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_INFO #include "logger.h" int main() { //auto l = spdlog::create_lite(); - spdlog::lite::info("HELLO info {}", 123); + //spdlog::lite::info("HELLO info {}", 123); + SPDLITE_TRACE("SOME MACRO {}", 123); + SPDLITE_INFO("SOME MACRO {}", "HHHHH"); + } \ No newline at end of file diff --git a/lite/logger.h b/lite/logger.h index b762b3f5..7246411c 100644 --- a/lite/logger.h +++ b/lite/logger.h @@ -1,28 +1,92 @@ // -// Created by gabi on 3/16/19. -// +// Copyright(c) 2015-present Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + #pragma once #include #include #include "spdlog/fmt/fmt.h" +// +// enable/disable log calls at compile time according to global level. +// +// define SPDLITE_ACTIVE_LEVEL to one of those (before including lite.h): + +#define SPDLITE_LEVEL_TRACE 0 +#define SPDLITE_LEVEL_DEBUG 1 +#define SPDLITE_LEVEL_INFO 2 +#define SPDLITE_LEVEL_WARN 3 +#define SPDLITE_LEVEL_ERROR 4 +#define SPDLITE_LEVEL_CRITICAL 5 +#define SPDLITE_LEVEL_OFF 6 + +#define SPDLITE_LOGGER_CALL(logger, level, ...) \ + if (logger.should_log(level)) \ + logger.log(level, __VA_ARGS__) + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE +#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::trace, __VA_ARGS__) +#define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 +#define SPDLITE_TRACE(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_DEBUG +#define SPDLITE_LOGGER_DEBUG(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::debug, __VA_ARGS__) +#define SPDLITE_DEBUG(...) SPDLITE_LOGGER_DEBUG(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_DEBUG(logger, ...) (void)0 +#define SPDLITE_DEBUG(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_INFO +#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::info, __VA_ARGS__) +#define SPDLITE_INFO(...) SPDLITE_LOGGER_INFO(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_INFO(logger, ...) (void)0 +#define SPDLITE_INFO(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_WARN +#define SPDLITE_LOGGER_WARN(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::warn, __VA_ARGS__) +#define SPDLITE_WARN(...) SPDLITE_LOGGER_WARN(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_WARN(logger, ...) (void)0 +#define SPDLITE_WARN(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_ERROR +#define SPDLITE_LOGGER_ERROR(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::err, __VA_ARGS__) +#define SPDLITE_ERROR(...) SPDLITE_LOGGER_ERROR(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_ERROR(logger, ...) (void)0 +#define SPDLITE_ERROR(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_CRITICAL +#define SPDLITE_LOGGER_CRITICAL(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::critical, __VA_ARGS__) +#define SPDLITE_CRITICAL(...) SPDLITE_LOGGER_CRITICAL(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_CRITICAL(logger, ...) (void)0 +#define SPDLITE_CRITICAL(...) (void)0 +#endif + -//#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::info, __VA_ARGS__) -//#define SPDLITE_INFO(...) SPDLOG_LOGGER_INFO(spdlog::default_logger_raw(), __VA_ARGS__) namespace spdlog { class logger; namespace lite { enum class level{ - trace, - debug, - info, - warn, - err, - critical, - off + trace = SPDLITE_LEVEL_TRACE, + debug =SPDLITE_LEVEL_DEBUG, + info = SPDLITE_LEVEL_INFO, + warn = SPDLITE_LEVEL_WARN, + err = SPDLITE_LEVEL_ERROR, + critical = SPDLITE_LEVEL_CRITICAL, + off = SPDLITE_LEVEL_OFF }; struct src_loc { From 1d72edcc4f9f37f3ebafe32639f7aa1454a16115 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 16:39:32 +0200 Subject: [PATCH 004/157] clang-format --- include/spdlog/common.h | 5 +- include/spdlog/sinks/rotating_file_sink.h | 4 +- include/spdlog/sinks/systemd_sink.h | 48 ++-- lite-example/create_lite.cpp | 8 +- lite-example/example.cpp | 5 +- lite/logger.cpp | 8 +- lite/logger.h | 294 +++++++++++----------- tests/test_file_logging.cpp | 2 +- 8 files changed, 183 insertions(+), 191 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index dd9a4785..71273d30 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -128,7 +128,10 @@ enum level_enum static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES; #if !defined(SPDLOG_SHORT_LEVEL_NAMES) -#define SPDLOG_SHORT_LEVEL_NAMES {"T", "D", "I", "W", "E", "C", "O"} +#define SPDLOG_SHORT_LEVEL_NAMES \ + { \ + "T", "D", "I", "W", "E", "C", "O" \ + } #endif static const char *short_level_names[] SPDLOG_SHORT_LEVEL_NAMES; diff --git a/include/spdlog/sinks/rotating_file_sink.h b/include/spdlog/sinks/rotating_file_sink.h index ae0f70f6..35f33a4d 100644 --- a/include/spdlog/sinks/rotating_file_sink.h +++ b/include/spdlog/sinks/rotating_file_sink.h @@ -31,7 +31,7 @@ template class rotating_file_sink final : public base_sink { 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)) , max_size_(max_size) , max_files_(max_files) @@ -150,7 +150,7 @@ using rotating_file_sink_st = rotating_file_sink; template inline std::shared_ptr 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(logger_name, filename, max_file_size, max_files, rotate_on_open); } diff --git a/include/spdlog/sinks/systemd_sink.h b/include/spdlog/sinks/systemd_sink.h index fa9efd83..be143194 100644 --- a/include/spdlog/sinks/systemd_sink.h +++ b/include/spdlog/sinks/systemd_sink.h @@ -18,22 +18,24 @@ namespace spdlog { namespace sinks { -inline int syslog_level(level::level_enum l) { - switch(l) { - case level::off: - case level::trace: - case level::debug: - return LOG_DEBUG; - case level::info: - return LOG_INFO; - case level::warn: - return LOG_WARNING; - case level::err: - return LOG_ERR; - case level::critical: - return LOG_CRIT; - default: - throw std::invalid_argument("systemd_sink.h syslog_level()"); +inline int syslog_level(level::level_enum l) +{ + switch (l) + { + case level::off: + case level::trace: + case level::debug: + return LOG_DEBUG; + case level::info: + return LOG_INFO; + case level::warn: + return LOG_WARNING; + case level::err: + return LOG_ERR; + case level::critical: + return LOG_CRIT; + default: + throw std::invalid_argument("systemd_sink.h syslog_level()"); } } @@ -57,13 +59,7 @@ public: protected: void sink_it_(const details::log_msg &msg) override { - if( sd_journal_print( - syslog_level(msg.level), - "%.*s", - static_cast(msg.payload.size()), - msg.payload.data() - ) - ) + if (sd_journal_print(syslog_level(msg.level), "%.*s", static_cast(msg.payload.size()), msg.payload.data())) throw spdlog_ex("Failed writing to systemd"); } @@ -76,15 +72,13 @@ using systemd_sink_st = systemd_sink; // Create and register a syslog logger template -inline std::shared_ptr systemd_logger_mt( - const std::string &logger_name) +inline std::shared_ptr systemd_logger_mt(const std::string &logger_name) { return Factory::template create(logger_name); } template -inline std::shared_ptr systemd_logger_st( - const std::string &logger_name) +inline std::shared_ptr systemd_logger_st(const std::string &logger_name) { return Factory::template create(logger_name); } diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp index aa375d4e..5345237f 100644 --- a/lite-example/create_lite.cpp +++ b/lite-example/create_lite.cpp @@ -1,15 +1,13 @@ #include "logger.h" #include "spdlog/spdlog.h" - -spdlog::lite::logger spdlog::create_lite(void* ctx) +spdlog::lite::logger spdlog::create_lite(void *ctx) { - if(ctx) { + if (ctx) + { //.. } auto logger_impl = spdlog::default_logger(); logger_impl->set_level(spdlog::level::trace); return spdlog::lite::logger(logger_impl); } - - diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 929e75dd..376d9a68 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -3,9 +3,8 @@ int main() { - //auto l = spdlog::create_lite(); - //spdlog::lite::info("HELLO info {}", 123); + // auto l = spdlog::create_lite(); + // spdlog::lite::info("HELLO info {}", 123); SPDLITE_TRACE("SOME MACRO {}", 123); SPDLITE_INFO("SOME MACRO {}", "HHHHH"); - } \ No newline at end of file diff --git a/lite/logger.cpp b/lite/logger.cpp index 39841553..0cbe766f 100644 --- a/lite/logger.cpp +++ b/lite/logger.cpp @@ -2,9 +2,9 @@ #include "spdlog/spdlog.h" #include "spdlog/logger.h" -static spdlog::level::level_enum to_spdlog_level(spdlog::lite::level level) +static spdlog::level::level_enum to_spdlog_level(spdlog::lite::level level) { - return static_cast(level); + return static_cast(level); } static spdlog::lite::level to_lite_level(spdlog::level::level_enum level) @@ -20,7 +20,7 @@ spdlog::lite::logger::logger(std::shared_ptr impl) bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NOEXCEPT { auto spd_level = to_spdlog_level(level); - return impl_->should_log(spd_level);//TODO level + return impl_->should_log(spd_level); // TODO level } void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt::memory_buffer &formatted) @@ -29,7 +29,6 @@ void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt:: impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); } - void spdlog::lite::logger::log_formatted_src(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) { auto spd_level = to_spdlog_level(lvl); @@ -75,7 +74,6 @@ void spdlog::lite::logger::set_pattern(std::string pattern) impl_->set_pattern(std::move(pattern)); } - spdlog::lite::logger &spdlog::lite::default_logger() { static spdlog::lite::logger s_default(spdlog::default_logger()); diff --git a/lite/logger.h b/lite/logger.h index 7246411c..b55a7159 100644 --- a/lite/logger.h +++ b/lite/logger.h @@ -21,8 +21,8 @@ #define SPDLITE_LEVEL_CRITICAL 5 #define SPDLITE_LEVEL_OFF 6 -#define SPDLITE_LOGGER_CALL(logger, level, ...) \ - if (logger.should_log(level)) \ +#define SPDLITE_LOGGER_CALL(logger, level, ...) \ + if (logger.should_log(level)) \ logger.log(level, __VA_ARGS__) #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE @@ -73,169 +73,169 @@ #define SPDLITE_CRITICAL(...) (void)0 #endif - - namespace spdlog { - class logger; +class logger; - namespace lite { - enum class level{ - trace = SPDLITE_LEVEL_TRACE, - debug =SPDLITE_LEVEL_DEBUG, - info = SPDLITE_LEVEL_INFO, - warn = SPDLITE_LEVEL_WARN, - err = SPDLITE_LEVEL_ERROR, - critical = SPDLITE_LEVEL_CRITICAL, - off = SPDLITE_LEVEL_OFF - }; +namespace lite { +enum class level +{ + trace = SPDLITE_LEVEL_TRACE, + debug = SPDLITE_LEVEL_DEBUG, + info = SPDLITE_LEVEL_INFO, + warn = SPDLITE_LEVEL_WARN, + err = SPDLITE_LEVEL_ERROR, + critical = SPDLITE_LEVEL_CRITICAL, + off = SPDLITE_LEVEL_OFF +}; - struct src_loc { - const char *filename; - int line; - const char* funcname; - }; +struct src_loc +{ + const char *filename; + int line; + const char *funcname; +}; - class logger { - public: - logger() = default; +class logger +{ +public: + logger() = default; - logger(std::shared_ptr impl); - logger(const logger&) = default; - logger(logger&&) = default; - logger& operator=(const logger&) = default; + logger(std::shared_ptr impl); + logger(const logger &) = default; + logger(logger &&) = default; + logger &operator=(const logger &) = default; - ~logger() = default; + ~logger() = default; - bool should_log(spdlog::lite::level lvl) const noexcept; + bool should_log(spdlog::lite::level lvl) const noexcept; - template - void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) { - if (!should_log(lvl)) { - return; - } - fmt::memory_buffer formatted_buf; - fmt::format_to(formatted_buf, fmt, args...); - log_formatted_(lvl, formatted_buf); - } - - - template - void log(const spdlog::lite::src_loc& src, spdlog::lite::level lvl, const char *fmt, const Args &... args) { - if (!should_log(lvl)) { - return; - } - fmt::memory_buffer formatted_buf; - fmt::format_to(formatted_buf, fmt, args...); - log_formatted_src(src, lvl, formatted_buf); - } - - - template - void trace(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::trace, fmt, args...); - } - - template - void trace(const char* source_file, int source_line, const char* source_func, const char *fmt, const Args &... args) - { - spdlog::lite::src_loc src{source_file, source_line, source_func}; - log(src, spdlog::lite::level::trace, fmt, args...); - } - - template - void debug(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::debug, fmt, args...); - } - - template - void info(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::info, fmt, args...); - } - - template - void warn(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::warn, fmt, args...); - } - - template - void error(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::err, fmt, args...); - } - - template - void critical(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::critical, fmt, args...); - } - - std::string name() const; - - // level - void set_level(lite::level level); - lite::level get_level() const; - - // flush - void flush(); - void flush_on(spdlog::lite::level log_level); - spdlog::lite::level flush_level() const; - - // pattern - void set_pattern(std::string pattern); - - protected: - std::shared_ptr impl_; - void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); - void log_formatted_src(const spdlog::lite::src_loc& src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); - - }; - spdlog::lite::logger& default_logger(); - - - template - void trace(const char *fmt, const Args &... args) + template + void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) + { + if (!should_log(lvl)) { - default_logger().trace(fmt, args...); + return; } - template - void debug(const char *fmt, const Args &... args) + fmt::memory_buffer formatted_buf; + fmt::format_to(formatted_buf, fmt, args...); + log_formatted_(lvl, formatted_buf); + } + + template + void log(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const char *fmt, const Args &... args) + { + if (!should_log(lvl)) { - default_logger().debug(fmt, args...); + return; } + fmt::memory_buffer formatted_buf; + fmt::format_to(formatted_buf, fmt, args...); + log_formatted_src(src, lvl, formatted_buf); + } - template - void info(const char *fmt, const Args &... args) - { - default_logger().info(fmt, args...); - } + template + void trace(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::trace, fmt, args...); + } - template - void warn(const char *fmt, const Args &... args) - { - default_logger().warn(fmt, args...); - } + template + void trace(const char *source_file, int source_line, const char *source_func, const char *fmt, const Args &... args) + { + spdlog::lite::src_loc src{source_file, source_line, source_func}; + log(src, spdlog::lite::level::trace, fmt, args...); + } - template - void error(const char *fmt, const Args &... args) - { - default_logger().error(fmt, args...); - } + template + void debug(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::debug, fmt, args...); + } - template - void critical(const char *fmt, const Args &... args) - { - default_logger().critical(fmt, args...); - } + template + void info(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::info, fmt, args...); + } + template + void warn(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::warn, fmt, args...); + } - } // namespace lite + template + void error(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::err, fmt, args...); + } - // factory to create lite logger - // implement it in a dedicated compilation unit for fast compiles - spdlog::lite::logger create_lite(void* ctx = nullptr); + template + void critical(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::critical, fmt, args...); + } + + std::string name() const; + + // level + void set_level(lite::level level); + lite::level get_level() const; + + // flush + void flush(); + void flush_on(spdlog::lite::level log_level); + spdlog::lite::level flush_level() const; + + // pattern + void set_pattern(std::string pattern); + +protected: + std::shared_ptr impl_; + void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + void log_formatted_src(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); +}; +spdlog::lite::logger &default_logger(); + +template +void trace(const char *fmt, const Args &... args) +{ + default_logger().trace(fmt, args...); +} +template +void debug(const char *fmt, const Args &... args) +{ + default_logger().debug(fmt, args...); +} + +template +void info(const char *fmt, const Args &... args) +{ + default_logger().info(fmt, args...); +} + +template +void warn(const char *fmt, const Args &... args) +{ + default_logger().warn(fmt, args...); +} + +template +void error(const char *fmt, const Args &... args) +{ + default_logger().error(fmt, args...); +} + +template +void critical(const char *fmt, const Args &... args) +{ + default_logger().critical(fmt, args...); +} + +} // namespace lite + +// factory to create lite logger +// implement it in a dedicated compilation unit for fast compiles +spdlog::lite::logger create_lite(void *ctx = nullptr); } // namespace spdlog \ No newline at end of file diff --git a/tests/test_file_logging.cpp b/tests/test_file_logging.cpp index dd0c8999..4de3a742 100644 --- a/tests/test_file_logging.cpp +++ b/tests/test_file_logging.cpp @@ -69,7 +69,7 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]]") logger->info("Test message {}", i); } // 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()); } From 3dee10772dfe6aa196336cc1932375c062054710 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 17:25:50 +0200 Subject: [PATCH 005/157] renamed --- lite-example/create_lite.cpp | 2 +- lite-example/example.cpp | 2 +- lite/CMakeLists.txt | 2 +- lite/{logger.cpp => spdlite.cpp} | 2 +- lite/{logger.h => spdlite.h} | 0 5 files changed, 4 insertions(+), 4 deletions(-) rename lite/{logger.cpp => spdlite.cpp} (99%) rename lite/{logger.h => spdlite.h} (100%) diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp index 5345237f..beea64ba 100644 --- a/lite-example/create_lite.cpp +++ b/lite-example/create_lite.cpp @@ -1,4 +1,4 @@ -#include "logger.h" +#include "spdlite.h" #include "spdlog/spdlog.h" spdlog::lite::logger spdlog::create_lite(void *ctx) diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 376d9a68..82ddef93 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -1,5 +1,5 @@ #define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_INFO -#include "logger.h" +#include "spdlite.h" int main() { diff --git a/lite/CMakeLists.txt b/lite/CMakeLists.txt index 3ed30be7..ee8a4aab 100644 --- a/lite/CMakeLists.txt +++ b/lite/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.1) project(spdlog_lite) -add_library(spdlog_lite logger.cpp) +add_library(spdlog_lite spdlite.cpp) target_link_libraries(spdlog_lite spdlog::spdlog) diff --git a/lite/logger.cpp b/lite/spdlite.cpp similarity index 99% rename from lite/logger.cpp rename to lite/spdlite.cpp index 0cbe766f..043bd1c8 100644 --- a/lite/logger.cpp +++ b/lite/spdlite.cpp @@ -1,4 +1,4 @@ -#include "logger.h" +#include "spdlite.h" #include "spdlog/spdlog.h" #include "spdlog/logger.h" diff --git a/lite/logger.h b/lite/spdlite.h similarity index 100% rename from lite/logger.h rename to lite/spdlite.h From 0e977d66c1186e19704682ac2d45327c3823b062 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 19:23:37 +0200 Subject: [PATCH 006/157] Dont check level in macros (redundant) --- include/spdlog/spdlog.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 20ff24be..2fadfb45 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -311,8 +311,7 @@ inline void critical(const wchar_t *fmt, const Args &... args) // SPDLOG_LEVEL_OFF // -#define SPDLOG_LOGGER_CALL(logger, level, ...) \ - if (logger->should_log(level)) \ +#define SPDLOG_LOGGER_CALL(logger, level, ...) \ logger->log(spdlog::source_loc{SPDLOG_FILE_BASENAME(__FILE__), __LINE__, SPDLOG_FUNCTION}, level, __VA_ARGS__) #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE From 4c240edf946e0b5887dd0cc0b6f12b907fb27072 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 19:34:50 +0200 Subject: [PATCH 007/157] wip lite --- .clang-tidy | 2 +- clang_tidy.sh | 3 +- example/example.cpp | 12 ++++---- include/spdlog/spdlog.h | 2 +- lite-example/create_lite.cpp | 12 ++++++-- lite-example/example.cpp | 10 +++---- lite/spdlite.cpp | 15 +++++----- lite/spdlite.h | 55 +++++++++++++++++------------------- 8 files changed, 58 insertions(+), 53 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 309c7e94..9079dd9a 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,6 +1,6 @@ Checks: 'modernize-*,modernize-use-override,google-*,-google-runtime-references,misc-*,clang-analyzer-*' 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 FormatStyle: none diff --git a/clang_tidy.sh b/clang_tidy.sh index 6e043e27..4fb8644b 100755 --- a/clang_tidy.sh +++ b/clang_tidy.sh @@ -1,2 +1,3 @@ #!/bin/bash -clang-tidy example/example.cpp -- -I ./include +clang-tidy example/example.cpp -- -I ./include +clang-tidy lite-example/example.cpp -- -I./include -I./lite diff --git a/example/example.cpp b/example/example.cpp index 0c3b8395..c0971620 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -1,11 +1,11 @@ +#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE #include "spdlog/spdlog.h" int main() { - auto l = spdlog::default_logger(); - l->trace("HELLO {}!!!", "lite"); - l->debug("HELLO {}!!!", "lite"); - l->info("HELLO {}!!!", "lite"); - l->warn("HELLO {}!!!", "lite"); - l->critical("HELLO s{}!!!", "lite"); + // auto l = spdlog::create_lite(); + // spdlog::lite::info("HELLO info {}", 123); + + SPDLOG_TRACE("SOME MACRO {}", 123); + SPDLOG_INFO("SOME MACRO {}", "HHHHH"); } \ No newline at end of file diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 2fadfb45..995e93f4 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -311,7 +311,7 @@ inline void critical(const wchar_t *fmt, const Args &... args) // SPDLOG_LEVEL_OFF // -#define SPDLOG_LOGGER_CALL(logger, level, ...) \ +#define SPDLOG_LOGGER_CALL(logger, level, ...) \ logger->log(spdlog::source_loc{SPDLOG_FILE_BASENAME(__FILE__), __LINE__, SPDLOG_FUNCTION}, level, __VA_ARGS__) #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp index beea64ba..a0e5e389 100644 --- a/lite-example/create_lite.cpp +++ b/lite-example/create_lite.cpp @@ -1,5 +1,9 @@ #include "spdlite.h" #include "spdlog/spdlog.h" +#include "spdlog/sinks/basic_file_sink.h" +#include "spdlog/sinks/stdout_color_sinks.h" + + spdlog::lite::logger spdlog::create_lite(void *ctx) { @@ -7,7 +11,9 @@ spdlog::lite::logger spdlog::create_lite(void *ctx) { //.. } - auto logger_impl = spdlog::default_logger(); - logger_impl->set_level(spdlog::level::trace); - return spdlog::lite::logger(logger_impl); + auto logger_impl = spdlog::stdout_color_mt("mylogger"); + auto file_sink = std::make_shared("file.txt", true); + logger_impl->sinks().push_back(file_sink); + logger_impl->set_level(spdlog::level::debug); + return spdlog::lite::logger(std::move(logger_impl)); } diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 82ddef93..87cbc895 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -1,10 +1,10 @@ -#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_INFO +#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_TRACE #include "spdlite.h" int main() { - // auto l = spdlog::create_lite(); - // spdlog::lite::info("HELLO info {}", 123); - SPDLITE_TRACE("SOME MACRO {}", 123); - SPDLITE_INFO("SOME MACRO {}", "HHHHH"); + //auto l = spdlog::create_lite(); + //l.info("Hello spdlog {}", "lite"); + SPDLITE_TRACE("HELLO TRACE"); + } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 043bd1c8..53f98fe9 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -20,22 +20,23 @@ spdlog::lite::logger::logger(std::shared_ptr impl) bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NOEXCEPT { auto spd_level = to_spdlog_level(level); - return impl_->should_log(spd_level); // TODO level + return impl_->should_log(spd_level); // TODO avoid the call using local level member? } -void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt::memory_buffer &formatted) -{ - auto spd_level = to_spdlog_level(level); - impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); -} -void spdlog::lite::logger::log_formatted_src(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) + +void spdlog::lite::logger::log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) { auto spd_level = to_spdlog_level(lvl); spdlog::source_loc source_loc{src.filename, src.line, src.funcname}; impl_->log(source_loc, spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); } +void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt::memory_buffer &formatted) +{ + log_formatted_(src_loc{}, level, formatted); +} + void spdlog::lite::logger::set_level(spdlog::lite::level level) { auto spd_level = to_spdlog_level(level); diff --git a/lite/spdlite.h b/lite/spdlite.h index b55a7159..c1ec48ba 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -21,12 +21,16 @@ #define SPDLITE_LEVEL_CRITICAL 5 #define SPDLITE_LEVEL_OFF 6 -#define SPDLITE_LOGGER_CALL(logger, level, ...) \ - if (logger.should_log(level)) \ - logger.log(level, __VA_ARGS__) + +#define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) + +//with source info +#define SPDLITE_LOGGER_CALL2(logger, level, ...) \ + logger.log(spdlog::lite::src_loc{__FILE__, __LINE__, __FUNCTION__}, level, __VA_ARGS__) + #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE -#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::trace, __VA_ARGS__) +#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL2(logger, spdlog::lite::level::trace, __VA_ARGS__) #define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlog::lite::default_logger(), __VA_ARGS__) #else #define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 @@ -90,9 +94,13 @@ enum class level struct src_loc { - const char *filename; - int line; - const char *funcname; + src_loc() = default; + src_loc(const char *filename, int line, const char *funcname): + filename(filename), line(line), funcname(funcname){} + + const char *filename = nullptr; + int line = 0; + const char *funcname = nullptr; }; class logger @@ -100,7 +108,7 @@ class logger public: logger() = default; - logger(std::shared_ptr impl); + explicit logger(std::shared_ptr impl); logger(const logger &) = default; logger(logger &&) = default; logger &operator=(const logger &) = default; @@ -109,18 +117,6 @@ public: bool should_log(spdlog::lite::level lvl) const noexcept; - template - void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) - { - if (!should_log(lvl)) - { - return; - } - fmt::memory_buffer formatted_buf; - fmt::format_to(formatted_buf, fmt, args...); - log_formatted_(lvl, formatted_buf); - } - template void log(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const char *fmt, const Args &... args) { @@ -130,7 +126,13 @@ public: } fmt::memory_buffer formatted_buf; fmt::format_to(formatted_buf, fmt, args...); - log_formatted_src(src, lvl, formatted_buf); + log_formatted_(src, lvl, formatted_buf); + } + + template + void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) + { + log(spdlog::lite::src_loc{}, lvl, fmt, args...); } template @@ -139,13 +141,7 @@ public: log(spdlog::lite::level::trace, fmt, args...); } - template - void trace(const char *source_file, int source_line, const char *source_func, const char *fmt, const Args &... args) - { - spdlog::lite::src_loc src{source_file, source_line, source_func}; - log(src, spdlog::lite::level::trace, fmt, args...); - } - + template void debug(const char *fmt, const Args &... args) { @@ -193,8 +189,9 @@ public: protected: std::shared_ptr impl_; void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); - void log_formatted_src(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + void log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); }; + spdlog::lite::logger &default_logger(); template From 569c62e5286d61c0e65c4ce76cc2e067ddac4202 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 20:06:49 +0200 Subject: [PATCH 008/157] support for const char* messages --- lite/spdlite.cpp | 13 +++++++++--- lite/spdlite.h | 51 ++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 53f98fe9..1e32a570 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -24,7 +24,6 @@ bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NO } - void spdlog::lite::logger::log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) { auto spd_level = to_spdlog_level(lvl); @@ -32,11 +31,19 @@ void spdlog::lite::logger::log_formatted_(const spdlog::lite::src_loc &src, spdl impl_->log(source_loc, spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); } -void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt::memory_buffer &formatted) +void spdlog::lite::logger::log_string_view_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const string_view_t &sv) { - log_formatted_(src_loc{}, level, formatted); + auto spd_level = to_spdlog_level(lvl); + spdlog::source_loc source_loc{src.filename, src.line, src.funcname}; + impl_->log(source_loc, spd_level, sv); } +void spdlog::lite::logger::log_string_view_(spdlog::lite::level lvl, const string_view_t &sv) +{ + log_string_view_(spdlog::lite::src_loc{}, lvl, sv); +} + + void spdlog::lite::logger::set_level(spdlog::lite::level level) { auto spd_level = to_spdlog_level(level); diff --git a/lite/spdlite.h b/lite/spdlite.h index c1ec48ba..f596cf31 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -77,10 +77,22 @@ #define SPDLITE_CRITICAL(...) (void)0 #endif + + + + namespace spdlog { class logger; namespace lite { + +// string_view type - either std::string_view or fmt::string_view (pre c++17) +#if defined(FMT_USE_STD_STRING_VIEW) + using string_view_t = std::string_view; +#else + using string_view_t = fmt::string_view; +#endif + enum class level { trace = SPDLITE_LEVEL_TRACE, @@ -135,42 +147,74 @@ public: log(spdlog::lite::src_loc{}, lvl, fmt, args...); } + template void trace(const char *fmt, const Args &... args) { log(spdlog::lite::level::trace, fmt, args...); } - + void trace(const char* msg) + { + log_string_view_(spdlog::lite::level::trace, msg); + } + + template void debug(const char *fmt, const Args &... args) { log(spdlog::lite::level::debug, fmt, args...); } + void debug(const char* msg) + { + log_string_view_(spdlog::lite::level::debug, msg); + } + template void info(const char *fmt, const Args &... args) { log(spdlog::lite::level::info, fmt, args...); } + void info(const char* msg) + { + log_string_view_(spdlog::lite::level::info, msg); + } + + template void warn(const char *fmt, const Args &... args) { log(spdlog::lite::level::warn, fmt, args...); } + void warn(const char* msg) + { + log_string_view_(spdlog::lite::level::warn, msg); + } + template void error(const char *fmt, const Args &... args) { log(spdlog::lite::level::err, fmt, args...); } + void error(const char* msg) + { + log_string_view_(spdlog::lite::level::err, msg); + } + template void critical(const char *fmt, const Args &... args) { log(spdlog::lite::level::critical, fmt, args...); } + void critical(const char* msg) + { + log_string_view_(spdlog::lite::level::critical, msg); + } + std::string name() const; @@ -188,8 +232,10 @@ public: protected: std::shared_ptr impl_; - void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); void log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + void log_string_view_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const string_view_t &sv); + void log_string_view_(spdlog::lite::level lvl, const string_view_t &sv); + }; spdlog::lite::logger &default_logger(); @@ -199,6 +245,7 @@ void trace(const char *fmt, const Args &... args) { default_logger().trace(fmt, args...); } + template void debug(const char *fmt, const Args &... args) { From 4449bf6f8366c94d0b05c4df27e3d98b72c2c07d Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 23:13:38 +0200 Subject: [PATCH 009/157] wip lite --- lite-example/create_lite.cpp | 5 ++- lite-example/example.cpp | 11 +++--- lite/spdlite.cpp | 2 -- lite/spdlite.h | 69 ++++++++++++++++-------------------- 4 files changed, 39 insertions(+), 48 deletions(-) diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp index a0e5e389..1a6d6bfe 100644 --- a/lite-example/create_lite.cpp +++ b/lite-example/create_lite.cpp @@ -3,8 +3,6 @@ #include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/stdout_color_sinks.h" - - spdlog::lite::logger spdlog::create_lite(void *ctx) { if (ctx) @@ -13,7 +11,8 @@ spdlog::lite::logger spdlog::create_lite(void *ctx) } auto logger_impl = spdlog::stdout_color_mt("mylogger"); auto file_sink = std::make_shared("file.txt", true); + file_sink->set_level(spdlog::level::info); logger_impl->sinks().push_back(file_sink); - logger_impl->set_level(spdlog::level::debug); + logger_impl->set_level(spdlog::level::trace); return spdlog::lite::logger(std::move(logger_impl)); } diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 87cbc895..60942ebe 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -1,10 +1,11 @@ -#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_TRACE #include "spdlite.h" int main() { - //auto l = spdlog::create_lite(); - //l.info("Hello spdlog {}", "lite"); - SPDLITE_TRACE("HELLO TRACE"); - + using namespace spdlog; + auto l = spdlog::create_lite(); + l.set_level(spdlog::lite::level::trace); + lite::default_logger().set_level(l.get_level()); + lite::trace("hello"); + lite::trace("hello {}", std::string("again")); } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 1e32a570..6b4f4f87 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -23,7 +23,6 @@ bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NO return impl_->should_log(spd_level); // TODO avoid the call using local level member? } - void spdlog::lite::logger::log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) { auto spd_level = to_spdlog_level(lvl); @@ -43,7 +42,6 @@ void spdlog::lite::logger::log_string_view_(spdlog::lite::level lvl, const strin log_string_view_(spdlog::lite::src_loc{}, lvl, sv); } - void spdlog::lite::logger::set_level(spdlog::lite::level level) { auto spd_level = to_spdlog_level(level); diff --git a/lite/spdlite.h b/lite/spdlite.h index f596cf31..77656959 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -21,13 +21,10 @@ #define SPDLITE_LEVEL_CRITICAL 5 #define SPDLITE_LEVEL_OFF 6 +#define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) -#define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) - -//with source info -#define SPDLITE_LOGGER_CALL2(logger, level, ...) \ - logger.log(spdlog::lite::src_loc{__FILE__, __LINE__, __FUNCTION__}, level, __VA_ARGS__) - +// with source info +#define SPDLITE_LOGGER_CALL2(logger, level, ...) logger.log(spdlog::lite::src_loc{__FILE__, __LINE__, __FUNCTION__}, level, __VA_ARGS__) #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE #define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL2(logger, spdlog::lite::level::trace, __VA_ARGS__) @@ -77,10 +74,6 @@ #define SPDLITE_CRITICAL(...) (void)0 #endif - - - - namespace spdlog { class logger; @@ -88,9 +81,9 @@ namespace lite { // string_view type - either std::string_view or fmt::string_view (pre c++17) #if defined(FMT_USE_STD_STRING_VIEW) - using string_view_t = std::string_view; +using string_view_t = std::string_view; #else - using string_view_t = fmt::string_view; +using string_view_t = fmt::string_view; #endif enum class level @@ -107,8 +100,12 @@ enum class level struct src_loc { src_loc() = default; - src_loc(const char *filename, int line, const char *funcname): - filename(filename), line(line), funcname(funcname){} + src_loc(const char *filename, int line, const char *funcname) + : filename(filename) + , line(line) + , funcname(funcname) + { + } const char *filename = nullptr; int line = 0; @@ -147,6 +144,11 @@ public: log(spdlog::lite::src_loc{}, lvl, fmt, args...); } + // trace + void trace(const char *msg) + { + log_string_view_(spdlog::lite::level::trace, msg); + } template void trace(const char *fmt, const Args &... args) @@ -154,21 +156,22 @@ public: log(spdlog::lite::level::trace, fmt, args...); } - void trace(const char* msg) + // debug + void debug(const char *msg) { - log_string_view_(spdlog::lite::level::trace, msg); + log_string_view_(spdlog::lite::level::debug, msg); } - template void debug(const char *fmt, const Args &... args) { log(spdlog::lite::level::debug, fmt, args...); } - void debug(const char* msg) + // info + void info(const char *msg) { - log_string_view_(spdlog::lite::level::debug, msg); + log_string_view_(spdlog::lite::level::info, msg); } template @@ -177,21 +180,22 @@ public: log(spdlog::lite::level::info, fmt, args...); } - void info(const char* msg) + // warn + void warn(const char *msg) { - log_string_view_(spdlog::lite::level::info, msg); + log_string_view_(spdlog::lite::level::warn, msg); } - template void warn(const char *fmt, const Args &... args) { log(spdlog::lite::level::warn, fmt, args...); } - void warn(const char* msg) + // error + void error(const char *msg) { - log_string_view_(spdlog::lite::level::warn, msg); + log_string_view_(spdlog::lite::level::err, msg); } template @@ -200,9 +204,10 @@ public: log(spdlog::lite::level::err, fmt, args...); } - void error(const char* msg) + // critical + void critical(const char *msg) { - log_string_view_(spdlog::lite::level::err, msg); + log_string_view_(spdlog::lite::level::critical, msg); } template @@ -210,24 +215,13 @@ public: { log(spdlog::lite::level::critical, fmt, args...); } - void critical(const char* msg) - { - log_string_view_(spdlog::lite::level::critical, msg); - } - std::string name() const; - - // level void set_level(lite::level level); lite::level get_level() const; - - // flush void flush(); void flush_on(spdlog::lite::level log_level); spdlog::lite::level flush_level() const; - - // pattern void set_pattern(std::string pattern); protected: @@ -235,7 +229,6 @@ protected: void log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); void log_string_view_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const string_view_t &sv); void log_string_view_(spdlog::lite::level lvl, const string_view_t &sv); - }; spdlog::lite::logger &default_logger(); From 621e0a833055cbd785095ce67c01ced44f5d0d14 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 00:30:08 +0200 Subject: [PATCH 010/157] added printf syntax support for even faster compilation! --- example/example.cpp | 9 ++--- lite-example/example.cpp | 8 +++-- lite/spdlite.cpp | 74 +++++++++++++++++++++++++++++++++----- lite/spdlite.h | 76 ++++++++++++++++++++++++---------------- 4 files changed, 121 insertions(+), 46 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index c0971620..8384906d 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -3,9 +3,10 @@ int main() { - // auto l = spdlog::create_lite(); - // spdlog::lite::info("HELLO info {}", 123); + using namespace spdlog; + auto l = spdlog::default_logger(); + l->set_level(spdlog::level::trace); + + l->trace("hello123123213 "); - SPDLOG_TRACE("SOME MACRO {}", 123); - SPDLOG_INFO("SOME MACRO {}", "HHHHH"); } \ No newline at end of file diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 60942ebe..34bb3ac4 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -5,7 +5,9 @@ int main() using namespace spdlog; auto l = spdlog::create_lite(); l.set_level(spdlog::lite::level::trace); - lite::default_logger().set_level(l.get_level()); - lite::trace("hello"); - lite::trace("hello {}", std::string("again")); + + + l.trace_f("Hello %s ","GABI"); + l.info_f("Hello %d", 12346); + } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 6b4f4f87..2bcdfa1b 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -23,23 +23,71 @@ bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NO return impl_->should_log(spd_level); // TODO avoid the call using local level member? } -void spdlog::lite::logger::log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) +void spdlog::lite::logger::log(spdlog::lite::level lvl, const string_view_t &sv) { auto spd_level = to_spdlog_level(lvl); - spdlog::source_loc source_loc{src.filename, src.line, src.funcname}; - impl_->log(source_loc, spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); + impl_->log(spd_level, sv); } -void spdlog::lite::logger::log_string_view_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const string_view_t &sv) + +void spdlog::lite::logger::log_printf(spdlog::lite::level lvl, const char* format, va_list args) { - auto spd_level = to_spdlog_level(lvl); - spdlog::source_loc source_loc{src.filename, src.line, src.funcname}; - impl_->log(source_loc, spd_level, sv); + char buffer[500]; + auto size = vsnprintf (buffer, sizeof(buffer),format, args); + if(size < 0) + { + size = snprintf(buffer, sizeof(buffer), "invalid format (%s)", format); + } + log(lvl, string_view_t{buffer, static_cast(size)}); } -void spdlog::lite::logger::log_string_view_(spdlog::lite::level lvl, const string_view_t &sv) + +void spdlog::lite::logger::trace_f(const char *format, ...) { - log_string_view_(spdlog::lite::src_loc{}, lvl, sv); + va_list args; + va_start (args, format); + log_printf(lite::level::trace, format, args); + va_end (args); +} + +void spdlog::lite::logger::debug_f(const char *format, ...) +{ + va_list args; + va_start (args, format); + log_printf(lite::level::debug, format, args); + va_end (args); +} + +void spdlog::lite::logger::info_f(const char *format, ...) +{ + va_list args; + va_start (args, format); + log_printf(lite::level::info, format, args); + va_end (args); +} + +void spdlog::lite::logger::warn_f(const char *format, ...) +{ + va_list args; + va_start (args, format); + log_printf(lite::level::warn, format, args); + va_end (args); +} + +void spdlog::lite::logger::error_f(const char *format, ...) +{ + va_list args; + va_start (args, format); + log_printf(lite::level::err, format, args); + va_end (args); +} + +void spdlog::lite::logger::critical_f(const char *format, ...) +{ + va_list args; + va_start (args, format); + log_printf(lite::level::critical, format, args); + va_end (args); } void spdlog::lite::logger::set_level(spdlog::lite::level level) @@ -80,8 +128,16 @@ void spdlog::lite::logger::set_pattern(std::string pattern) impl_->set_pattern(std::move(pattern)); } +void spdlog::lite::logger::log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted) +{ + auto spd_level = to_spdlog_level(lvl); + impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); +} + spdlog::lite::logger &spdlog::lite::default_logger() { static spdlog::lite::logger s_default(spdlog::default_logger()); return s_default; } + + diff --git a/lite/spdlite.h b/lite/spdlite.h index 77656959..51f4ed6f 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -97,20 +97,6 @@ enum class level off = SPDLITE_LEVEL_OFF }; -struct src_loc -{ - src_loc() = default; - src_loc(const char *filename, int line, const char *funcname) - : filename(filename) - , line(line) - , funcname(funcname) - { - } - - const char *filename = nullptr; - int line = 0; - const char *funcname = nullptr; -}; class logger { @@ -127,7 +113,7 @@ public: bool should_log(spdlog::lite::level lvl) const noexcept; template - void log(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const char *fmt, const Args &... args) + void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) { if (!should_log(lvl)) { @@ -135,19 +121,20 @@ public: } fmt::memory_buffer formatted_buf; fmt::format_to(formatted_buf, fmt, args...); - log_formatted_(src, lvl, formatted_buf); + log_formatted_(lvl, formatted_buf); } - template - void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) - { - log(spdlog::lite::src_loc{}, lvl, fmt, args...); - } + // log string view + void log(spdlog::lite::level lvl, const string_view_t &sv); + void log_printf(spdlog::lite::level lvl, const char* format, va_list args); + + // // trace + // void trace(const char *msg) { - log_string_view_(spdlog::lite::level::trace, msg); + log(spdlog::lite::level::trace, string_view_t(msg)); } template @@ -156,10 +143,14 @@ public: log(spdlog::lite::level::trace, fmt, args...); } + void trace_f(const char *printf_format, ...); + + // // debug + // void debug(const char *msg) { - log_string_view_(spdlog::lite::level::debug, msg); + log(spdlog::lite::level::debug, string_view_t(msg)); } template @@ -168,10 +159,14 @@ public: log(spdlog::lite::level::debug, fmt, args...); } + void debug_f(const char *printf_format, ...); + + // // info + // void info(const char *msg) { - log_string_view_(spdlog::lite::level::info, msg); + log(spdlog::lite::level::info, string_view_t(msg)); } template @@ -180,10 +175,14 @@ public: log(spdlog::lite::level::info, fmt, args...); } + void info_f(const char *printf_format, ...); + + // // warn + // void warn(const char *msg) { - log_string_view_(spdlog::lite::level::warn, msg); + log(spdlog::lite::level::warn, string_view_t(msg)); } template @@ -192,22 +191,31 @@ public: log(spdlog::lite::level::warn, fmt, args...); } + void warn_f(const char *printf_format, ...); + + // // error + // void error(const char *msg) { - log_string_view_(spdlog::lite::level::err, msg); + log(spdlog::lite::level::err, string_view_t(msg)); } + template void error(const char *fmt, const Args &... args) { log(spdlog::lite::level::err, fmt, args...); } + void error_f(const char *printf_format, ...); + + // // critical + // void critical(const char *msg) { - log_string_view_(spdlog::lite::level::critical, msg); + log(spdlog::lite::level::critical, string_view_t(msg)); } template @@ -216,9 +224,18 @@ public: log(spdlog::lite::level::critical, fmt, args...); } + void critical_f(const char *printf_format, ...); + + // + // setters/getters + // std::string name() const; void set_level(lite::level level); lite::level get_level() const; + + // + // flush + // void flush(); void flush_on(spdlog::lite::level log_level); spdlog::lite::level flush_level() const; @@ -226,9 +243,8 @@ public: protected: std::shared_ptr impl_; - void log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); - void log_string_view_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const string_view_t &sv); - void log_string_view_(spdlog::lite::level lvl, const string_view_t &sv); + void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + }; spdlog::lite::logger &default_logger(); From 680f19a4244975cbb1be2a4890612588024ac3c7 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 00:31:55 +0200 Subject: [PATCH 011/157] Removed source logging --- lite/spdlite.h | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lite/spdlite.h b/lite/spdlite.h index 51f4ed6f..2793f5c1 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -23,11 +23,8 @@ #define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) -// with source info -#define SPDLITE_LOGGER_CALL2(logger, level, ...) logger.log(spdlog::lite::src_loc{__FILE__, __LINE__, __FUNCTION__}, level, __VA_ARGS__) - #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE -#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL2(logger, spdlog::lite::level::trace, __VA_ARGS__) +#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::trace, __VA_ARGS__) #define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlog::lite::default_logger(), __VA_ARGS__) #else #define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 From b1c90f08cc534430d62ca94da5f5175497e50af5 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 00:38:00 +0200 Subject: [PATCH 012/157] moved macros to seprate headers --- lite-example/example.cpp | 4 +-- lite/spdlite.cpp | 1 - lite/spdlite.h | 78 ++++------------------------------------ lite/spdlite_macros.h | 67 ++++++++++++++++++++++++++++++++++ 4 files changed, 76 insertions(+), 74 deletions(-) create mode 100644 lite/spdlite_macros.h diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 34bb3ac4..f45eeb9e 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -6,8 +6,8 @@ int main() auto l = spdlog::create_lite(); l.set_level(spdlog::lite::level::trace); - l.trace_f("Hello %s ","GABI"); l.info_f("Hello %d", 12346); - + l.warn_f("Hello %f", 12346.5656); + l.warn("Hello {}", 12346.5656); } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 2bcdfa1b..8b7ace31 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -1,6 +1,5 @@ #include "spdlite.h" #include "spdlog/spdlog.h" -#include "spdlog/logger.h" static spdlog::level::level_enum to_spdlog_level(spdlog::lite::level level) { diff --git a/lite/spdlite.h b/lite/spdlite.h index 2793f5c1..39579002 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -8,69 +8,6 @@ #include #include "spdlog/fmt/fmt.h" -// -// enable/disable log calls at compile time according to global level. -// -// define SPDLITE_ACTIVE_LEVEL to one of those (before including lite.h): - -#define SPDLITE_LEVEL_TRACE 0 -#define SPDLITE_LEVEL_DEBUG 1 -#define SPDLITE_LEVEL_INFO 2 -#define SPDLITE_LEVEL_WARN 3 -#define SPDLITE_LEVEL_ERROR 4 -#define SPDLITE_LEVEL_CRITICAL 5 -#define SPDLITE_LEVEL_OFF 6 - -#define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE -#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::trace, __VA_ARGS__) -#define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 -#define SPDLITE_TRACE(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_DEBUG -#define SPDLITE_LOGGER_DEBUG(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::debug, __VA_ARGS__) -#define SPDLITE_DEBUG(...) SPDLITE_LOGGER_DEBUG(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_DEBUG(logger, ...) (void)0 -#define SPDLITE_DEBUG(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_INFO -#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::info, __VA_ARGS__) -#define SPDLITE_INFO(...) SPDLITE_LOGGER_INFO(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_INFO(logger, ...) (void)0 -#define SPDLITE_INFO(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_WARN -#define SPDLITE_LOGGER_WARN(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::warn, __VA_ARGS__) -#define SPDLITE_WARN(...) SPDLITE_LOGGER_WARN(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_WARN(logger, ...) (void)0 -#define SPDLITE_WARN(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_ERROR -#define SPDLITE_LOGGER_ERROR(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::err, __VA_ARGS__) -#define SPDLITE_ERROR(...) SPDLITE_LOGGER_ERROR(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_ERROR(logger, ...) (void)0 -#define SPDLITE_ERROR(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_CRITICAL -#define SPDLITE_LOGGER_CRITICAL(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::critical, __VA_ARGS__) -#define SPDLITE_CRITICAL(...) SPDLITE_LOGGER_CRITICAL(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_CRITICAL(logger, ...) (void)0 -#define SPDLITE_CRITICAL(...) (void)0 -#endif - namespace spdlog { class logger; @@ -85,13 +22,13 @@ using string_view_t = fmt::string_view; enum class level { - trace = SPDLITE_LEVEL_TRACE, - debug = SPDLITE_LEVEL_DEBUG, - info = SPDLITE_LEVEL_INFO, - warn = SPDLITE_LEVEL_WARN, - err = SPDLITE_LEVEL_ERROR, - critical = SPDLITE_LEVEL_CRITICAL, - off = SPDLITE_LEVEL_OFF + trace, + debug, + info, + warn, + err, + critical, + off }; @@ -121,7 +58,6 @@ public: log_formatted_(lvl, formatted_buf); } - // log string view void log(spdlog::lite::level lvl, const string_view_t &sv); void log_printf(spdlog::lite::level lvl, const char* format, va_list args); diff --git a/lite/spdlite_macros.h b/lite/spdlite_macros.h new file mode 100644 index 00000000..8d9eb4f8 --- /dev/null +++ b/lite/spdlite_macros.h @@ -0,0 +1,67 @@ +// +// Created by gabi on 3/24/19. +// + +#pragma once +// +// enable/disable log calls at compile time according to global level. +// +// define SPDLITE_ACTIVE_LEVEL to one of those (before including lite.h): + +#define SPDLITE_LEVEL_TRACE 0 +#define SPDLITE_LEVEL_DEBUG 1 +#define SPDLITE_LEVEL_INFO 2 +#define SPDLITE_LEVEL_WARN 3 +#define SPDLITE_LEVEL_ERROR 4 +#define SPDLITE_LEVEL_CRITICAL 5 +#define SPDLITE_LEVEL_OFF 6 + +#define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE +#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::trace, __VA_ARGS__) +#define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 +#define SPDLITE_TRACE(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_DEBUG +#define SPDLITE_LOGGER_DEBUG(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::debug, __VA_ARGS__) +#define SPDLITE_DEBUG(...) SPDLITE_LOGGER_DEBUG(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_DEBUG(logger, ...) (void)0 +#define SPDLITE_DEBUG(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_INFO +#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::info, __VA_ARGS__) +#define SPDLITE_INFO(...) SPDLITE_LOGGER_INFO(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_INFO(logger, ...) (void)0 +#define SPDLITE_INFO(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_WARN +#define SPDLITE_LOGGER_WARN(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::warn, __VA_ARGS__) +#define SPDLITE_WARN(...) SPDLITE_LOGGER_WARN(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_WARN(logger, ...) (void)0 +#define SPDLITE_WARN(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_ERROR +#define SPDLITE_LOGGER_ERROR(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::err, __VA_ARGS__) +#define SPDLITE_ERROR(...) SPDLITE_LOGGER_ERROR(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_ERROR(logger, ...) (void)0 +#define SPDLITE_ERROR(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_CRITICAL +#define SPDLITE_LOGGER_CRITICAL(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::critical, __VA_ARGS__) +#define SPDLITE_CRITICAL(...) SPDLITE_LOGGER_CRITICAL(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_CRITICAL(logger, ...) (void)0 +#define SPDLITE_CRITICAL(...) (void)0 +#endif From 934cc892eb159c1b12f536dadb1436b5e9e331a9 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 00:40:27 +0200 Subject: [PATCH 013/157] Fixed examples --- example/example.cpp | 237 +++++++++++++++++++++++++++++++++++++-- lite-example/example.cpp | 1 - 2 files changed, 230 insertions(+), 8 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 8384906d..88b0b415 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -1,12 +1,235 @@ -#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// +// +// spdlog usage example +// +// + +#include + +void stdout_logger_example(); +void basic_example(); +void rotating_example(); +void daily_example(); +void async_example(); +void binary_example(); +void trace_example(); +void multi_sink_example(); +void user_defined_example(); +void err_handler_example(); +void syslog_example(); +void clone_example(); + #include "spdlog/spdlog.h" -int main() +int main(int, char *[]) { - using namespace spdlog; - auto l = spdlog::default_logger(); - l->set_level(spdlog::level::trace); + 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::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); + spdlog::info("Support for floats {:03.2f}", 1.23456); + spdlog::info("Positional args are {1} {0}..", "too", "supported"); + spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left"); - l->trace("hello123123213 "); + // Runtime log levels + spdlog::set_level(spdlog::level::info); // Set global log level to info + spdlog::debug("This message should not be displayed!"); + spdlog::set_level(spdlog::level::trace); // Set specific logger's log level + spdlog::debug("This message should be displayed.."); -} \ No newline at end of file + // Customize msg format for all loggers + spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v"); + spdlog::info("This an info message with custom format"); + spdlog::set_pattern("%+"); // back to default format + + try + { + stdout_logger_example(); + basic_example(); + rotating_example(); + daily_example(); + clone_example(); + async_example(); + binary_example(); + multi_sink_example(); + user_defined_example(); + err_handler_example(); + trace_example(); + + // Flush all *registered* loggers using a worker thread every 3 seconds. + // note: registered loggers *must* be thread safe for this to work correctly! + spdlog::flush_every(std::chrono::seconds(3)); + + // Apply some function on all registered loggers + spdlog::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); + + // Release all spdlog resources, and drop all loggers in the registry. + // This is optional (only mandatory if using windows + async log). + spdlog::shutdown(); + } + + // Exceptions will only be thrown upon failed logger or sink construction (not during logging). + catch (const spdlog::spdlog_ex &ex) + { + std::printf("Log initialization failed: %s\n", ex.what()); + return 1; + } +} + +#include "spdlog/sinks/stdout_color_sinks.h" +// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed. +void stdout_logger_example() +{ + // Create color multi threaded logger. + auto console = spdlog::stdout_color_mt("console"); + // or for stderr: + // auto console = spdlog::stderr_color_mt("error-logger"); +} + +#include "spdlog/sinks/basic_file_sink.h" +void basic_example() +{ + // Create basic file logger (not rotated). + auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt"); +} + +#include "spdlog/sinks/rotating_file_sink.h" +void rotating_example() +{ + // Create a file rotating logger with 5mb size max and 3 rotated files. + auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); +} + +#include "spdlog/sinks/daily_file_sink.h" +void daily_example() +{ + // Create a daily logger - a new file is created every day on 2:30am. + auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); +} + +// Clone a logger and give it new name. +// Useful for creating component/subsystem loggers from some "root" logger. +void clone_example() +{ + auto network_logger = spdlog::default_logger()->clone("network"); + network_logger->info("Logging network stuff.."); +} + +#include "spdlog/async.h" +void async_example() +{ + // Default thread pool settings can be modified *before* creating the async logger: + // spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread. + auto async_file = spdlog::basic_logger_mt("async_file_logger", "logs/async_log.txt"); + // alternatively: + // auto async_file = spdlog::create_async("async_file_logger", "logs/async_log.txt"); + + for (int i = 1; i < 101; ++i) + { + async_file->info("Async message #{}", i); + } +} + +// Log binary data as hex. +// Many types of std::container types can be used. +// Iterator ranges are supported too. +// Format flags: +// {:X} - print in uppercase. +// {:s} - don't separate each byte with space. +// {:p} - don't print the position on each line start. +// {:n} - don't split the output to lines. + +#include "spdlog/fmt/bin_to_hex.h" +void binary_example() +{ + std::vector buf; + for (int i = 0; i < 80; i++) + { + buf.push_back(static_cast(i & 0xff)); + } + spdlog::info("Binary example: {}", spdlog::to_hex(buf)); + spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10)); + // more examples: + // logger->info("uppercase: {:X}", spdlog::to_hex(buf)); + // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf)); + // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf)); +} + +// Compile time log levels. +// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE) +void trace_example() +{ + // trace from default logger + SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23); + // debug from default logger + SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23); + + // trace from logger object + auto logger = spdlog::get("file_logger"); + SPDLOG_LOGGER_TRACE(logger, "another trace message"); +} + +// A logger with multiple sinks (stdout and file) - each with a different format and log level. +void multi_sink_example() +{ + auto console_sink = std::make_shared(); + console_sink->set_level(spdlog::level::warn); + console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v"); + + auto file_sink = std::make_shared("logs/multisink.txt", true); + file_sink->set_level(spdlog::level::trace); + + spdlog::logger logger("multi_sink", {console_sink, file_sink}); + logger.set_level(spdlog::level::debug); + logger.warn("this should appear in both console and file"); + logger.info("this message should not appear in the console, only in the file"); +} + +// User defined types logging by implementing operator<< +#include "spdlog/fmt/ostr.h" // must be included +struct my_type +{ + int i; + template + friend OStream &operator<<(OStream &os, const my_type &c) + { + return os << "[my_type i=" << c.i << "]"; + } +}; + +void user_defined_example() +{ + spdlog::info("user defined type: {}", my_type{14}); +} + +// Custom error handler. Will be triggered on log failure. +void err_handler_example() +{ + // can be set globally or per logger(logger->set_error_handler(..)) + spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); }); +} + +// syslog example (linux/osx/freebsd) +#ifndef _WIN32 +#include "spdlog/sinks/syslog_sink.h" +void syslog_example() +{ + std::string ident = "spdlog-example"; + auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID); + syslog_logger->warn("This is warning that will end up in syslog."); +} +#endif + +// Android example. +#if defined(__ANDROID__) +#include "spdlog/sinks/android_sink.h" +void android_example() +{ + std::string tag = "spdlog-android"; + auto android_logger = spdlog::android_logger_mt("android", tag); + android_logger->critical("Use \"adb shell logcat\" to view this message."); +} + +#endif diff --git a/lite-example/example.cpp b/lite-example/example.cpp index f45eeb9e..d0ce4562 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -2,7 +2,6 @@ int main() { - using namespace spdlog; auto l = spdlog::create_lite(); l.set_level(spdlog::lite::level::trace); From bac1e4a850a6e5c83e8217ff1f632b0eb180419f Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 00:41:22 +0200 Subject: [PATCH 014/157] clang-format --- example/example.cpp | 2 +- lite-example/example.cpp | 2 +- lite/spdlite.cpp | 34 +++++++++++++++------------------- lite/spdlite.h | 15 ++++++--------- 4 files changed, 23 insertions(+), 30 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 88b0b415..345f8bd1 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -70,7 +70,7 @@ int main(int, char *[]) spdlog::shutdown(); } - // Exceptions will only be thrown upon failed logger or sink construction (not during logging). + // Exceptions will only be thrown upon failed logger or sink construction (not during logging). catch (const spdlog::spdlog_ex &ex) { std::printf("Log initialization failed: %s\n", ex.what()); diff --git a/lite-example/example.cpp b/lite-example/example.cpp index d0ce4562..e4185131 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -5,7 +5,7 @@ int main() auto l = spdlog::create_lite(); l.set_level(spdlog::lite::level::trace); - l.trace_f("Hello %s ","GABI"); + l.trace_f("Hello %s ", "GABI"); l.info_f("Hello %d", 12346); l.warn_f("Hello %f", 12346.5656); l.warn("Hello {}", 12346.5656); diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 8b7ace31..80c0388b 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -28,65 +28,63 @@ void spdlog::lite::logger::log(spdlog::lite::level lvl, const string_view_t &sv) impl_->log(spd_level, sv); } - -void spdlog::lite::logger::log_printf(spdlog::lite::level lvl, const char* format, va_list args) +void spdlog::lite::logger::log_printf(spdlog::lite::level lvl, const char *format, va_list args) { char buffer[500]; - auto size = vsnprintf (buffer, sizeof(buffer),format, args); - if(size < 0) + auto size = vsnprintf(buffer, sizeof(buffer), format, args); + if (size < 0) { size = snprintf(buffer, sizeof(buffer), "invalid format (%s)", format); } log(lvl, string_view_t{buffer, static_cast(size)}); } - void spdlog::lite::logger::trace_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::trace, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::debug_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::debug, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::info_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::info, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::warn_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::warn, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::error_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::err, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::critical_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::critical, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::set_level(spdlog::lite::level level) @@ -138,5 +136,3 @@ spdlog::lite::logger &spdlog::lite::default_logger() static spdlog::lite::logger s_default(spdlog::default_logger()); return s_default; } - - diff --git a/lite/spdlite.h b/lite/spdlite.h index 39579002..ddfc4b27 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -31,7 +31,6 @@ enum class level off }; - class logger { public: @@ -60,7 +59,7 @@ public: // log string view void log(spdlog::lite::level lvl, const string_view_t &sv); - void log_printf(spdlog::lite::level lvl, const char* format, va_list args); + void log_printf(spdlog::lite::level lvl, const char *format, va_list args); // // trace @@ -76,7 +75,7 @@ public: log(spdlog::lite::level::trace, fmt, args...); } - void trace_f(const char *printf_format, ...); + void trace_f(const char *printf_format, ...); // // debug @@ -92,7 +91,7 @@ public: log(spdlog::lite::level::debug, fmt, args...); } - void debug_f(const char *printf_format, ...); + void debug_f(const char *printf_format, ...); // // info @@ -124,7 +123,7 @@ public: log(spdlog::lite::level::warn, fmt, args...); } - void warn_f(const char *printf_format, ...); + void warn_f(const char *printf_format, ...); // // error @@ -134,14 +133,13 @@ public: log(spdlog::lite::level::err, string_view_t(msg)); } - template void error(const char *fmt, const Args &... args) { log(spdlog::lite::level::err, fmt, args...); } - void error_f(const char *printf_format, ...); + void error_f(const char *printf_format, ...); // // critical @@ -157,7 +155,7 @@ public: log(spdlog::lite::level::critical, fmt, args...); } - void critical_f(const char *printf_format, ...); + void critical_f(const char *printf_format, ...); // // setters/getters @@ -177,7 +175,6 @@ public: protected: std::shared_ptr impl_; void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); - }; spdlog::lite::logger &default_logger(); From 509a503761e8f108f452cdf04416222071fd579f Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:18:05 +0200 Subject: [PATCH 015/157] update example --- lite-example/create_lite.cpp | 23 ++++++++++++-------- lite-example/example.cpp | 2 +- lite/spdlite.h | 42 ++++++++++++++++++++---------------- 3 files changed, 38 insertions(+), 29 deletions(-) diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp index 1a6d6bfe..74892d64 100644 --- a/lite-example/create_lite.cpp +++ b/lite-example/create_lite.cpp @@ -3,16 +3,21 @@ #include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/stdout_color_sinks.h" +#define UNUSED(x) (void)(x) + +// example of creating lite logger with console and file sink spdlog::lite::logger spdlog::create_lite(void *ctx) { - if (ctx) - { - //.. - } - auto logger_impl = spdlog::stdout_color_mt("mylogger"); - auto file_sink = std::make_shared("file.txt", true); - file_sink->set_level(spdlog::level::info); - logger_impl->sinks().push_back(file_sink); - logger_impl->set_level(spdlog::level::trace); + UNUSED(ctx); + std::shared_ptr logger_impl; + + auto console_sink = std::make_shared (); + console_sink->set_level(spdlog::level::debug); + + auto file_sink = std::make_shared ("log.txt", true); + file_sink ->set_level(spdlog::level::info); + + logger_impl = std::make_shared("my-logger", spdlog::sinks_init_list{console_sink, file_sink}); + logger_impl->set_level(spdlog::level::debug); return spdlog::lite::logger(std::move(logger_impl)); } diff --git a/lite-example/example.cpp b/lite-example/example.cpp index e4185131..bffd0a2f 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -2,7 +2,7 @@ int main() { - auto l = spdlog::create_lite(); + auto l = spdlog::create_lite((void*)"async"); l.set_level(spdlog::lite::level::trace); l.trace_f("Hello %s ", "GABI"); diff --git a/lite/spdlite.h b/lite/spdlite.h index ddfc4b27..4429b50d 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -43,10 +43,10 @@ public: ~logger() = default; - bool should_log(spdlog::lite::level lvl) const noexcept; + bool should_log(lite::level lvl) const noexcept; template - void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) + void log(lite::level lvl, const char *fmt, const Args &... args) { if (!should_log(lvl)) { @@ -58,21 +58,21 @@ public: } // log string view - void log(spdlog::lite::level lvl, const string_view_t &sv); - void log_printf(spdlog::lite::level lvl, const char *format, va_list args); + void log(lite::level lvl, const string_view_t &sv); + void log_printf(lite::level lvl, const char *format, va_list args); // // trace // void trace(const char *msg) { - log(spdlog::lite::level::trace, string_view_t(msg)); + log(lite::level::trace, string_view_t(msg)); } template void trace(const char *fmt, const Args &... args) { - log(spdlog::lite::level::trace, fmt, args...); + log(lite::level::trace, fmt, args...); } void trace_f(const char *printf_format, ...); @@ -82,13 +82,13 @@ public: // void debug(const char *msg) { - log(spdlog::lite::level::debug, string_view_t(msg)); + log(lite::level::debug, string_view_t(msg)); } template void debug(const char *fmt, const Args &... args) { - log(spdlog::lite::level::debug, fmt, args...); + log(lite::level::debug, fmt, args...); } void debug_f(const char *printf_format, ...); @@ -98,13 +98,13 @@ public: // void info(const char *msg) { - log(spdlog::lite::level::info, string_view_t(msg)); + log(lite::level::info, string_view_t(msg)); } template void info(const char *fmt, const Args &... args) { - log(spdlog::lite::level::info, fmt, args...); + log(lite::level::info, fmt, args...); } void info_f(const char *printf_format, ...); @@ -114,13 +114,13 @@ public: // void warn(const char *msg) { - log(spdlog::lite::level::warn, string_view_t(msg)); + log(lite::level::warn, string_view_t(msg)); } template void warn(const char *fmt, const Args &... args) { - log(spdlog::lite::level::warn, fmt, args...); + log(lite::level::warn, fmt, args...); } void warn_f(const char *printf_format, ...); @@ -130,13 +130,13 @@ public: // void error(const char *msg) { - log(spdlog::lite::level::err, string_view_t(msg)); + log(lite::level::err, string_view_t(msg)); } template void error(const char *fmt, const Args &... args) { - log(spdlog::lite::level::err, fmt, args...); + log(lite::level::err, fmt, args...); } void error_f(const char *printf_format, ...); @@ -146,13 +146,13 @@ public: // void critical(const char *msg) { - log(spdlog::lite::level::critical, string_view_t(msg)); + log(lite::level::critical, string_view_t(msg)); } template void critical(const char *fmt, const Args &... args) { - log(spdlog::lite::level::critical, fmt, args...); + log(lite::level::critical, fmt, args...); } void critical_f(const char *printf_format, ...); @@ -168,13 +168,17 @@ public: // flush // void flush(); - void flush_on(spdlog::lite::level log_level); - spdlog::lite::level flush_level() const; + void flush_on(lite::level log_level); + lite::level flush_level() const; + + // + // set pattern + // void set_pattern(std::string pattern); protected: std::shared_ptr impl_; - void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + void log_formatted_(lite::level lvl, const fmt::memory_buffer &formatted); }; spdlog::lite::logger &default_logger(); From 722943000e0a23d14175f3e6d08905e3b3dbdecf Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:21:07 +0200 Subject: [PATCH 016/157] renamed printf --- lite-example/example.cpp | 6 +++--- lite/spdlite.cpp | 12 ++++++------ lite/spdlite.h | 12 ++++++------ 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/lite-example/example.cpp b/lite-example/example.cpp index bffd0a2f..1a08bcc7 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -5,8 +5,8 @@ int main() auto l = spdlog::create_lite((void*)"async"); l.set_level(spdlog::lite::level::trace); - l.trace_f("Hello %s ", "GABI"); - l.info_f("Hello %d", 12346); - l.warn_f("Hello %f", 12346.5656); + l.trace_printf("Hello %s ", "GABI"); + l.info_printf("Hello %d", 12346); + l.warn_printf("Hello %f", 12346.5656); l.warn("Hello {}", 12346.5656); } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 80c0388b..e3af7bb7 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -39,7 +39,7 @@ void spdlog::lite::logger::log_printf(spdlog::lite::level lvl, const char *forma log(lvl, string_view_t{buffer, static_cast(size)}); } -void spdlog::lite::logger::trace_f(const char *format, ...) +void spdlog::lite::logger::trace_printf(const char *format, ...) { va_list args; va_start(args, format); @@ -47,7 +47,7 @@ void spdlog::lite::logger::trace_f(const char *format, ...) va_end(args); } -void spdlog::lite::logger::debug_f(const char *format, ...) +void spdlog::lite::logger::debug_printf(const char *format, ...) { va_list args; va_start(args, format); @@ -55,7 +55,7 @@ void spdlog::lite::logger::debug_f(const char *format, ...) va_end(args); } -void spdlog::lite::logger::info_f(const char *format, ...) +void spdlog::lite::logger::info_printf(const char *format, ...) { va_list args; va_start(args, format); @@ -63,7 +63,7 @@ void spdlog::lite::logger::info_f(const char *format, ...) va_end(args); } -void spdlog::lite::logger::warn_f(const char *format, ...) +void spdlog::lite::logger::warn_printf(const char *format, ...) { va_list args; va_start(args, format); @@ -71,7 +71,7 @@ void spdlog::lite::logger::warn_f(const char *format, ...) va_end(args); } -void spdlog::lite::logger::error_f(const char *format, ...) +void spdlog::lite::logger::error_printf(const char *format, ...) { va_list args; va_start(args, format); @@ -79,7 +79,7 @@ void spdlog::lite::logger::error_f(const char *format, ...) va_end(args); } -void spdlog::lite::logger::critical_f(const char *format, ...) +void spdlog::lite::logger::critical_printf(const char *format, ...) { va_list args; va_start(args, format); diff --git a/lite/spdlite.h b/lite/spdlite.h index 4429b50d..5642df79 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -75,7 +75,7 @@ public: log(lite::level::trace, fmt, args...); } - void trace_f(const char *printf_format, ...); + void trace_printf(const char *format, ...); // // debug @@ -91,7 +91,7 @@ public: log(lite::level::debug, fmt, args...); } - void debug_f(const char *printf_format, ...); + void debug_printf(const char *format, ...); // // info @@ -107,7 +107,7 @@ public: log(lite::level::info, fmt, args...); } - void info_f(const char *printf_format, ...); + void info_printf(const char *format, ...); // // warn @@ -123,7 +123,7 @@ public: log(lite::level::warn, fmt, args...); } - void warn_f(const char *printf_format, ...); + void warn_printf(const char *format, ...); // // error @@ -139,7 +139,7 @@ public: log(lite::level::err, fmt, args...); } - void error_f(const char *printf_format, ...); + void error_printf(const char *format, ...); // // critical @@ -155,7 +155,7 @@ public: log(lite::level::critical, fmt, args...); } - void critical_f(const char *printf_format, ...); + void critical_printf(const char *format, ...); // // setters/getters From 221ce33eb5e37411e67c61494e9728677cc93605 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:23:14 +0200 Subject: [PATCH 017/157] renamed printf --- lite-example/example.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 1a08bcc7..b89ddc09 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -2,11 +2,11 @@ int main() { - auto l = spdlog::create_lite((void*)"async"); + auto l = spdlog::create_lite(); l.set_level(spdlog::lite::level::trace); l.trace_printf("Hello %s ", "GABI"); l.info_printf("Hello %d", 12346); l.warn_printf("Hello %f", 12346.5656); - l.warn("Hello {}", 12346.5656); + l.warn("Hello {}", "LITE :) "); } \ No newline at end of file From 240f13a0a68eaff0dfaf7875f28563ed8f65b376 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:27:05 +0200 Subject: [PATCH 018/157] Renamed source file --- lite-example/CMakeLists.txt | 2 +- lite-example/{create_lite.cpp => create_logger.cpp} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename lite-example/{create_lite.cpp => create_logger.cpp} (100%) diff --git a/lite-example/CMakeLists.txt b/lite-example/CMakeLists.txt index d152ecd1..5f309a6b 100644 --- a/lite-example/CMakeLists.txt +++ b/lite-example/CMakeLists.txt @@ -2,7 +2,7 @@ project(spdlog-lite-example CXX) find_package(Threads REQUIRED) -set(LITE_SOURCES example.cpp create_lite.cpp) +set(LITE_SOURCES example.cpp create_logger.cpp) add_executable(${PROJECT_NAME} ${LITE_SOURCES}) diff --git a/lite-example/create_lite.cpp b/lite-example/create_logger.cpp similarity index 100% rename from lite-example/create_lite.cpp rename to lite-example/create_logger.cpp From 9e5d1b3ba5a9a632ccfde286f6e2793e4980f873 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:34:21 +0200 Subject: [PATCH 019/157] Removed default ctor from lite logger --- lite/spdlite.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/lite/spdlite.h b/lite/spdlite.h index 5642df79..e969678a 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -34,8 +34,6 @@ enum class level class logger { public: - logger() = default; - explicit logger(std::shared_ptr impl); logger(const logger &) = default; logger(logger &&) = default; From 4ccca079a56102060006761c0f59c8f6c7dd9234 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:40:20 +0200 Subject: [PATCH 020/157] clone support in lite logger --- lite-example/example.cpp | 4 ++++ lite/spdlite.cpp | 5 +++++ lite/spdlite.h | 5 +++++ 3 files changed, 14 insertions(+) diff --git a/lite-example/example.cpp b/lite-example/example.cpp index b89ddc09..34771028 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -9,4 +9,8 @@ int main() l.info_printf("Hello %d", 12346); l.warn_printf("Hello %f", 12346.5656); l.warn("Hello {}", "LITE :) "); + + auto l2 = l.clone("logger2"); + l2.debug("HELLO"); + } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index e3af7bb7..71a1aacb 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -125,6 +125,11 @@ void spdlog::lite::logger::set_pattern(std::string pattern) impl_->set_pattern(std::move(pattern)); } +spdlog::lite::logger spdlog::lite::logger::clone(std::string logger_name) +{ + return spdlog::lite::logger(impl_->clone(std::move(logger_name))); +} + void spdlog::lite::logger::log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted) { auto spd_level = to_spdlog_level(lvl); diff --git a/lite/spdlite.h b/lite/spdlite.h index e969678a..36a7b7af 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -174,6 +174,11 @@ public: // void set_pattern(std::string pattern); + // + //clone with new name + // + spdlog::lite::logger clone(std::string logger_name); + protected: std::shared_ptr impl_; void log_formatted_(lite::level lvl, const fmt::memory_buffer &formatted); From 4a00590a1bd4f77adc7faa1396c0fb75b0de138a Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:44:40 +0200 Subject: [PATCH 021/157] comment --- lite/spdlite.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lite/spdlite.h b/lite/spdlite.h index 36a7b7af..425a762c 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -4,6 +4,10 @@ #pragma once +// lite logger - a lite wrapper around spdlog::logger shared_ptr pimpl +// main purpose is much faster compile time and very cheap copy and move. +// also supports printf format for even faster compile times (by avoiding variadic templates) + #include #include #include "spdlog/fmt/fmt.h" From bf307e24c5d919131595939796145175890dceae Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:50:56 +0200 Subject: [PATCH 022/157] comment --- lite/spdlite.h | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lite/spdlite.h b/lite/spdlite.h index 425a762c..bb9972ee 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -4,9 +4,13 @@ #pragma once -// lite logger - a lite wrapper around spdlog::logger shared_ptr pimpl -// main purpose is much faster compile time and very cheap copy and move. -// also supports printf format for even faster compile times (by avoiding variadic templates) +// lite logger - a pimpl around spdlog::logger shared_ptr: +// much faster compile times. +// can be used as lib or separate compilation unit. +// very cheap copy and move. +// supports printf format for even faster compile (by avoiding variadic templates). +// +// see lite-example/ for usage. #include #include From 4a07ce5faef5ae32448003468288b323a423c6a7 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 29 Mar 2019 13:56:44 +0300 Subject: [PATCH 023/157] added header to cmake --- lite/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lite/CMakeLists.txt b/lite/CMakeLists.txt index ee8a4aab..f0769a0d 100644 --- a/lite/CMakeLists.txt +++ b/lite/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.1) project(spdlog_lite) -add_library(spdlog_lite spdlite.cpp) +add_library(spdlog_lite spdlite.cpp spdlite.h) target_link_libraries(spdlog_lite spdlog::spdlog) From bb88a74f92f45bdf1c2518972403b443145e77c2 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 29 Mar 2019 14:38:40 +0300 Subject: [PATCH 024/157] wip lite --- lite-example/create_logger.cpp | 4 +-- lite-example/example.cpp | 9 ++++-- lite/spdlite.cpp | 10 +++---- lite/spdlite.h | 50 ++++++++++++---------------------- 4 files changed, 30 insertions(+), 43 deletions(-) diff --git a/lite-example/create_logger.cpp b/lite-example/create_logger.cpp index 74892d64..07608139 100644 --- a/lite-example/create_logger.cpp +++ b/lite-example/create_logger.cpp @@ -6,7 +6,7 @@ #define UNUSED(x) (void)(x) // example of creating lite logger with console and file sink -spdlog::lite::logger spdlog::create_lite(void *ctx) +spdlog::lite::logger spdlog::lite::create_logger(void *ctx) { UNUSED(ctx); std::shared_ptr logger_impl; @@ -17,7 +17,7 @@ spdlog::lite::logger spdlog::create_lite(void *ctx) auto file_sink = std::make_shared ("log.txt", true); file_sink ->set_level(spdlog::level::info); - logger_impl = std::make_shared("my-logger", spdlog::sinks_init_list{console_sink, file_sink}); + logger_impl = std::make_unique("my-logger", spdlog::sinks_init_list{console_sink, file_sink}); logger_impl->set_level(spdlog::level::debug); return spdlog::lite::logger(std::move(logger_impl)); } diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 34771028..3668a400 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -2,15 +2,18 @@ int main() { - auto l = spdlog::create_lite(); + auto l = spdlog::lite::create_logger(); l.set_level(spdlog::lite::level::trace); - l.trace_printf("Hello %s ", "GABI"); + l.trace_printf("Hello %s ", "GABI"); l.info_printf("Hello %d", 12346); l.warn_printf("Hello %f", 12346.5656); l.warn("Hello {}", "LITE :) "); - auto l2 = l.clone("logger2"); + auto l2 = l.clone("logger2"); l2.debug("HELLO"); + auto l3 = std::move(l); + l3.warn("HELLO FROM L3"); + } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 71a1aacb..f3557543 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -87,18 +87,18 @@ void spdlog::lite::logger::critical_printf(const char *format, ...) va_end(args); } -void spdlog::lite::logger::set_level(spdlog::lite::level level) +void spdlog::lite::logger::set_level(spdlog::lite::level level) noexcept { auto spd_level = to_spdlog_level(level); impl_->set_level(spd_level); } -spdlog::lite::level spdlog::lite::logger::get_level() const +spdlog::lite::level spdlog::lite::logger::level() const noexcept { return to_lite_level(impl_->level()); } -std::string spdlog::lite::logger::name() const +std::string spdlog::lite::logger::name() const noexcept { return impl_->name(); } @@ -114,13 +114,13 @@ void spdlog::lite::logger::flush_on(spdlog::lite::level level) impl_->flush_on(spd_level); } -spdlog::lite::level spdlog::lite::logger::flush_level() const +spdlog::lite::level spdlog::lite::logger::flush_level() const noexcept { return to_lite_level(impl_->flush_level()); } // pattern -void spdlog::lite::logger::set_pattern(std::string pattern) +void spdlog::lite::logger::set_pattern(std::string pattern) noexcept { impl_->set_pattern(std::move(pattern)); } diff --git a/lite/spdlite.h b/lite/spdlite.h index bb9972ee..636dbdab 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -42,7 +42,7 @@ enum class level class logger { public: - explicit logger(std::shared_ptr impl); + explicit logger(std::shared_ptr impl); logger(const logger &) = default; logger(logger &&) = default; logger &operator=(const logger &) = default; @@ -65,6 +65,8 @@ public: // log string view void log(lite::level lvl, const string_view_t &sv); + + // log using printf format void log_printf(lite::level lvl, const char *format, va_list args); // @@ -98,10 +100,8 @@ public: } void debug_printf(const char *format, ...); - - // - // info - // + + // info void info(const char *msg) { log(lite::level::info, string_view_t(msg)); @@ -115,9 +115,7 @@ public: void info_printf(const char *format, ...); - // // warn - // void warn(const char *msg) { log(lite::level::warn, string_view_t(msg)); @@ -131,9 +129,7 @@ public: void warn_printf(const char *format, ...); - // // error - // void error(const char *msg) { log(lite::level::err, string_view_t(msg)); @@ -147,9 +143,7 @@ public: void error_printf(const char *format, ...); - // // critical - // void critical(const char *msg) { log(lite::level::critical, string_view_t(msg)); @@ -163,28 +157,18 @@ public: void critical_printf(const char *format, ...); - // - // setters/getters - // - std::string name() const; - void set_level(lite::level level); - lite::level get_level() const; + // setters/getters + void set_level(lite::level level) noexcept; + void set_pattern(std::string pattern) noexcept; + lite::level level() const noexcept; + std::string name() const noexcept; + lite::level flush_level() const noexcept; - // // flush - // void flush(); void flush_on(lite::level log_level); - lite::level flush_level() const; - - // - // set pattern - // - void set_pattern(std::string pattern); - - // + //clone with new name - // spdlog::lite::logger clone(std::string logger_name); protected: @@ -230,10 +214,10 @@ void critical(const char *fmt, const Args &... args) default_logger().critical(fmt, args...); } +// user implemented factory to create lite logger +// implement it in a seperated and dedicated compilation unit for fast compiles. +logger create_logger(void *ctx = nullptr); + } // namespace lite +} // namespace spdlog -// factory to create lite logger -// implement it in a dedicated compilation unit for fast compiles -spdlog::lite::logger create_lite(void *ctx = nullptr); - -} // namespace spdlog \ No newline at end of file From 57a312cb1ace32c87dad8ef0d62b907aa4a17405 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 13:31:57 +0200 Subject: [PATCH 025/157] lite wip --- CMakeLists.txt | 7 ++++ lite-example/CMakeLists.txt | 13 ++++++++ lite-example/create_lite.cpp | 15 +++++++++ lite-example/example.cpp | 7 ++++ lite/CMakeLists.txt | 6 ++++ lite/logger.cpp | 21 ++++++++++++ lite/logger.h | 64 ++++++++++++++++++++++++++++++++++++ lite/spd_types.h | 24 ++++++++++++++ 8 files changed, 157 insertions(+) create mode 100644 lite-example/CMakeLists.txt create mode 100644 lite-example/create_lite.cpp create mode 100644 lite-example/example.cpp create mode 100644 lite/CMakeLists.txt create mode 100644 lite/logger.cpp create mode 100644 lite/logger.h create mode 100644 lite/spd_types.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 9f0951fc..c4093403 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,6 +54,8 @@ option(SPDLOG_BUILD_BENCH "Build benchmarks (Requires https://github.com/google/ option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) +option(SPDLOG_BUILD_LITE "Build spdlog lite" ${SPDLOG_MASTER_PROJECT}) + if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) find_package(fmt REQUIRED CONFIG) @@ -86,6 +88,11 @@ if(SPDLOG_BUILD_BENCH) add_subdirectory(bench) endif() +if(SPDLOG_BUILD_LITE) + add_subdirectory(lite) + add_subdirectory(lite-example) +endif() + #--------------------------------------------------------------------------------------- # Install/export targets and files #--------------------------------------------------------------------------------------- diff --git a/lite-example/CMakeLists.txt b/lite-example/CMakeLists.txt new file mode 100644 index 00000000..d152ecd1 --- /dev/null +++ b/lite-example/CMakeLists.txt @@ -0,0 +1,13 @@ +project(spdlog-lite-example CXX) + +find_package(Threads REQUIRED) + +set(LITE_SOURCES example.cpp create_lite.cpp) + +add_executable(${PROJECT_NAME} ${LITE_SOURCES}) + +include_directories(../lite) +target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) +target_link_libraries(${PROJECT_NAME} PRIVATE spdlog_lite) + + diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp new file mode 100644 index 00000000..aa375d4e --- /dev/null +++ b/lite-example/create_lite.cpp @@ -0,0 +1,15 @@ +#include "logger.h" +#include "spdlog/spdlog.h" + + +spdlog::lite::logger spdlog::create_lite(void* ctx) +{ + if(ctx) { + //.. + } + auto logger_impl = spdlog::default_logger(); + logger_impl->set_level(spdlog::level::trace); + return spdlog::lite::logger(logger_impl); +} + + diff --git a/lite-example/example.cpp b/lite-example/example.cpp new file mode 100644 index 00000000..a1a78eb6 --- /dev/null +++ b/lite-example/example.cpp @@ -0,0 +1,7 @@ +#include "logger.h" + +int main() +{ + auto l = spdlog::create_lite(); + l.trace("HELLO {}!!!", "lite"); +} \ No newline at end of file diff --git a/lite/CMakeLists.txt b/lite/CMakeLists.txt new file mode 100644 index 00000000..3ed30be7 --- /dev/null +++ b/lite/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.1) +project(spdlog_lite) + +add_library(spdlog_lite logger.cpp) + +target_link_libraries(spdlog_lite spdlog::spdlog) diff --git a/lite/logger.cpp b/lite/logger.cpp new file mode 100644 index 00000000..6098df84 --- /dev/null +++ b/lite/logger.cpp @@ -0,0 +1,21 @@ +#include "logger.h" +#include "spdlog/spdlog.h" +#include "spdlog/logger.h" + +spdlog::lite::logger::logger(std::shared_ptr impl) +{ + impl_ = std::move(impl); +} + + +bool spdlog::lite::logger::should_log(spdlog::lite::level lvl) const SPDLOG_NOEXCEPT +{ + auto spd_level = static_cast(lvl); + return impl_->should_log(spd_level);//TODO level +} + +void spdlog::lite::logger::log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted) +{ + auto spd_level = static_cast(lvl); + impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); //TODO and source_loc +} \ No newline at end of file diff --git a/lite/logger.h b/lite/logger.h new file mode 100644 index 00000000..6cc60b09 --- /dev/null +++ b/lite/logger.h @@ -0,0 +1,64 @@ +// +// Created by gabi on 3/16/19. +// + +#ifndef SPDLOG_LIB_LOGGER_H +#define SPDLOG_LIB_LOGGER_H + +#include +#include "spd_types.h" +#include "spdlog/fmt/fmt.h" + + +namespace spdlog { + class logger; + + namespace lite { + class logger { + public: + logger() = default; + + logger(std::shared_ptr impl); + logger(const logger&) = default; + logger(logger&&) = default; + logger& operator=(const logger&) = default; + + ~logger() = default; + + bool should_log(spdlog::lite::level lvl) const noexcept; + + template + void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) { + if (!should_log(lvl)) { + return; + } + fmt::memory_buffer formatted_buf; + fmt::format_to(formatted_buf, fmt, args...); + log_formatted_(lvl, formatted_buf); + } + +// template +// void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) +// { +// log(lvl, fmt, args...); +// } + + template + void trace(const char *fmt, const Args &... args) { + log(spdlog::lite::level::trace, fmt, args...); + } + + protected: + std::shared_ptr impl_; + + void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + + }; + + } // namespace lite + + // factory to create lite logger + // implement it in a dedicated compilation unit for fast compiles + spdlog::lite::logger create_lite(void* ctx = nullptr); +} // namespace spdlog +#endif //SPDLOG_LIB_LOGGER_H diff --git a/lite/spd_types.h b/lite/spd_types.h new file mode 100644 index 00000000..94be9b34 --- /dev/null +++ b/lite/spd_types.h @@ -0,0 +1,24 @@ +// +// Copyright(c) 2019 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +// core types, forward declarations and defines used by spdlog + +#pragma once + +namespace spdlog +{ +namespace lite +{ + enum class level{ + trace, + debug, + info, + warning, + error, + critical, + off + + }; +}} \ No newline at end of file From 478f16234d9d0f04671cf13cfa0cc886e14559cd Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 16:15:58 +0200 Subject: [PATCH 026/157] wip lite --- example/example.cpp | 240 ++------------------------------------- lite-example/example.cpp | 4 +- lite/logger.cpp | 76 +++++++++++-- lite/logger.h | 139 ++++++++++++++++++++--- lite/spd_types.h | 24 ---- 5 files changed, 205 insertions(+), 278 deletions(-) delete mode 100644 lite/spd_types.h diff --git a/example/example.cpp b/example/example.cpp index 345f8bd1..0c3b8395 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -1,235 +1,11 @@ -// -// Copyright(c) 2015 Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) -// -// -// spdlog usage example -// -// - -#include - -void stdout_logger_example(); -void basic_example(); -void rotating_example(); -void daily_example(); -void async_example(); -void binary_example(); -void trace_example(); -void multi_sink_example(); -void user_defined_example(); -void err_handler_example(); -void syslog_example(); -void clone_example(); - #include "spdlog/spdlog.h" -int main(int, char *[]) +int main() { - 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::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); - spdlog::info("Support for floats {:03.2f}", 1.23456); - spdlog::info("Positional args are {1} {0}..", "too", "supported"); - spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left"); - - // Runtime log levels - spdlog::set_level(spdlog::level::info); // Set global log level to info - spdlog::debug("This message should not be displayed!"); - spdlog::set_level(spdlog::level::trace); // Set specific logger's log level - spdlog::debug("This message should be displayed.."); - - // Customize msg format for all loggers - spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v"); - spdlog::info("This an info message with custom format"); - spdlog::set_pattern("%+"); // back to default format - - try - { - stdout_logger_example(); - basic_example(); - rotating_example(); - daily_example(); - clone_example(); - async_example(); - binary_example(); - multi_sink_example(); - user_defined_example(); - err_handler_example(); - trace_example(); - - // Flush all *registered* loggers using a worker thread every 3 seconds. - // note: registered loggers *must* be thread safe for this to work correctly! - spdlog::flush_every(std::chrono::seconds(3)); - - // Apply some function on all registered loggers - spdlog::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); - - // Release all spdlog resources, and drop all loggers in the registry. - // This is optional (only mandatory if using windows + async log). - spdlog::shutdown(); - } - - // Exceptions will only be thrown upon failed logger or sink construction (not during logging). - catch (const spdlog::spdlog_ex &ex) - { - std::printf("Log initialization failed: %s\n", ex.what()); - return 1; - } -} - -#include "spdlog/sinks/stdout_color_sinks.h" -// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed. -void stdout_logger_example() -{ - // Create color multi threaded logger. - auto console = spdlog::stdout_color_mt("console"); - // or for stderr: - // auto console = spdlog::stderr_color_mt("error-logger"); -} - -#include "spdlog/sinks/basic_file_sink.h" -void basic_example() -{ - // Create basic file logger (not rotated). - auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt"); -} - -#include "spdlog/sinks/rotating_file_sink.h" -void rotating_example() -{ - // Create a file rotating logger with 5mb size max and 3 rotated files. - auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); -} - -#include "spdlog/sinks/daily_file_sink.h" -void daily_example() -{ - // Create a daily logger - a new file is created every day on 2:30am. - auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); -} - -// Clone a logger and give it new name. -// Useful for creating component/subsystem loggers from some "root" logger. -void clone_example() -{ - auto network_logger = spdlog::default_logger()->clone("network"); - network_logger->info("Logging network stuff.."); -} - -#include "spdlog/async.h" -void async_example() -{ - // Default thread pool settings can be modified *before* creating the async logger: - // spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread. - auto async_file = spdlog::basic_logger_mt("async_file_logger", "logs/async_log.txt"); - // alternatively: - // auto async_file = spdlog::create_async("async_file_logger", "logs/async_log.txt"); - - for (int i = 1; i < 101; ++i) - { - async_file->info("Async message #{}", i); - } -} - -// Log binary data as hex. -// Many types of std::container types can be used. -// Iterator ranges are supported too. -// Format flags: -// {:X} - print in uppercase. -// {:s} - don't separate each byte with space. -// {:p} - don't print the position on each line start. -// {:n} - don't split the output to lines. - -#include "spdlog/fmt/bin_to_hex.h" -void binary_example() -{ - std::vector buf; - for (int i = 0; i < 80; i++) - { - buf.push_back(static_cast(i & 0xff)); - } - spdlog::info("Binary example: {}", spdlog::to_hex(buf)); - spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10)); - // more examples: - // logger->info("uppercase: {:X}", spdlog::to_hex(buf)); - // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf)); - // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf)); -} - -// Compile time log levels. -// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE) -void trace_example() -{ - // trace from default logger - SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23); - // debug from default logger - SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23); - - // trace from logger object - auto logger = spdlog::get("file_logger"); - SPDLOG_LOGGER_TRACE(logger, "another trace message"); -} - -// A logger with multiple sinks (stdout and file) - each with a different format and log level. -void multi_sink_example() -{ - auto console_sink = std::make_shared(); - console_sink->set_level(spdlog::level::warn); - console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v"); - - auto file_sink = std::make_shared("logs/multisink.txt", true); - file_sink->set_level(spdlog::level::trace); - - spdlog::logger logger("multi_sink", {console_sink, file_sink}); - logger.set_level(spdlog::level::debug); - logger.warn("this should appear in both console and file"); - logger.info("this message should not appear in the console, only in the file"); -} - -// User defined types logging by implementing operator<< -#include "spdlog/fmt/ostr.h" // must be included -struct my_type -{ - int i; - template - friend OStream &operator<<(OStream &os, const my_type &c) - { - return os << "[my_type i=" << c.i << "]"; - } -}; - -void user_defined_example() -{ - spdlog::info("user defined type: {}", my_type{14}); -} - -// Custom error handler. Will be triggered on log failure. -void err_handler_example() -{ - // can be set globally or per logger(logger->set_error_handler(..)) - spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); }); -} - -// syslog example (linux/osx/freebsd) -#ifndef _WIN32 -#include "spdlog/sinks/syslog_sink.h" -void syslog_example() -{ - std::string ident = "spdlog-example"; - auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID); - syslog_logger->warn("This is warning that will end up in syslog."); -} -#endif - -// Android example. -#if defined(__ANDROID__) -#include "spdlog/sinks/android_sink.h" -void android_example() -{ - std::string tag = "spdlog-android"; - auto android_logger = spdlog::android_logger_mt("android", tag); - android_logger->critical("Use \"adb shell logcat\" to view this message."); -} - -#endif + auto l = spdlog::default_logger(); + l->trace("HELLO {}!!!", "lite"); + l->debug("HELLO {}!!!", "lite"); + l->info("HELLO {}!!!", "lite"); + l->warn("HELLO {}!!!", "lite"); + l->critical("HELLO s{}!!!", "lite"); +} \ No newline at end of file diff --git a/lite-example/example.cpp b/lite-example/example.cpp index a1a78eb6..05d772aa 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -2,6 +2,6 @@ int main() { - auto l = spdlog::create_lite(); - l.trace("HELLO {}!!!", "lite"); + //auto l = spdlog::create_lite(); + spdlog::lite::info("HELLO info {}", 123); } \ No newline at end of file diff --git a/lite/logger.cpp b/lite/logger.cpp index 6098df84..39841553 100644 --- a/lite/logger.cpp +++ b/lite/logger.cpp @@ -2,20 +2,82 @@ #include "spdlog/spdlog.h" #include "spdlog/logger.h" +static spdlog::level::level_enum to_spdlog_level(spdlog::lite::level level) +{ + return static_cast(level); +} + +static spdlog::lite::level to_lite_level(spdlog::level::level_enum level) +{ + return static_cast(level); +} + spdlog::lite::logger::logger(std::shared_ptr impl) { impl_ = std::move(impl); } - -bool spdlog::lite::logger::should_log(spdlog::lite::level lvl) const SPDLOG_NOEXCEPT +bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NOEXCEPT { - auto spd_level = static_cast(lvl); + auto spd_level = to_spdlog_level(level); return impl_->should_log(spd_level);//TODO level } -void spdlog::lite::logger::log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted) +void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt::memory_buffer &formatted) { - auto spd_level = static_cast(lvl); - impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); //TODO and source_loc -} \ No newline at end of file + auto spd_level = to_spdlog_level(level); + impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); +} + + +void spdlog::lite::logger::log_formatted_src(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) +{ + auto spd_level = to_spdlog_level(lvl); + spdlog::source_loc source_loc{src.filename, src.line, src.funcname}; + impl_->log(source_loc, spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); +} + +void spdlog::lite::logger::set_level(spdlog::lite::level level) +{ + auto spd_level = to_spdlog_level(level); + impl_->set_level(spd_level); +} + +spdlog::lite::level spdlog::lite::logger::get_level() const +{ + return to_lite_level(impl_->level()); +} + +std::string spdlog::lite::logger::name() const +{ + return impl_->name(); +} + +void spdlog::lite::logger::flush() +{ + impl_->flush(); +} + +void spdlog::lite::logger::flush_on(spdlog::lite::level level) +{ + auto spd_level = to_spdlog_level(level); + impl_->flush_on(spd_level); +} + +spdlog::lite::level spdlog::lite::logger::flush_level() const +{ + return to_lite_level(impl_->flush_level()); +} + +// pattern +void spdlog::lite::logger::set_pattern(std::string pattern) +{ + impl_->set_pattern(std::move(pattern)); +} + + +spdlog::lite::logger &spdlog::lite::default_logger() +{ + static spdlog::lite::logger s_default(spdlog::default_logger()); + return s_default; +} diff --git a/lite/logger.h b/lite/logger.h index 6cc60b09..b762b3f5 100644 --- a/lite/logger.h +++ b/lite/logger.h @@ -1,19 +1,36 @@ // // Created by gabi on 3/16/19. // - -#ifndef SPDLOG_LIB_LOGGER_H -#define SPDLOG_LIB_LOGGER_H +#pragma once #include -#include "spd_types.h" +#include #include "spdlog/fmt/fmt.h" +//#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::info, __VA_ARGS__) +//#define SPDLITE_INFO(...) SPDLOG_LOGGER_INFO(spdlog::default_logger_raw(), __VA_ARGS__) + namespace spdlog { class logger; namespace lite { + enum class level{ + trace, + debug, + info, + warn, + err, + critical, + off + }; + + struct src_loc { + const char *filename; + int line; + const char* funcname; + }; + class logger { public: logger() = default; @@ -37,28 +54,124 @@ namespace spdlog { log_formatted_(lvl, formatted_buf); } -// template -// void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) -// { -// log(lvl, fmt, args...); -// } template - void trace(const char *fmt, const Args &... args) { + void log(const spdlog::lite::src_loc& src, spdlog::lite::level lvl, const char *fmt, const Args &... args) { + if (!should_log(lvl)) { + return; + } + fmt::memory_buffer formatted_buf; + fmt::format_to(formatted_buf, fmt, args...); + log_formatted_src(src, lvl, formatted_buf); + } + + + template + void trace(const char *fmt, const Args &... args) + { log(spdlog::lite::level::trace, fmt, args...); } + template + void trace(const char* source_file, int source_line, const char* source_func, const char *fmt, const Args &... args) + { + spdlog::lite::src_loc src{source_file, source_line, source_func}; + log(src, spdlog::lite::level::trace, fmt, args...); + } + + template + void debug(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::debug, fmt, args...); + } + + template + void info(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::info, fmt, args...); + } + + template + void warn(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::warn, fmt, args...); + } + + template + void error(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::err, fmt, args...); + } + + template + void critical(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::critical, fmt, args...); + } + + std::string name() const; + + // level + void set_level(lite::level level); + lite::level get_level() const; + + // flush + void flush(); + void flush_on(spdlog::lite::level log_level); + spdlog::lite::level flush_level() const; + + // pattern + void set_pattern(std::string pattern); + protected: std::shared_ptr impl_; - void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + void log_formatted_src(const spdlog::lite::src_loc& src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); }; + spdlog::lite::logger& default_logger(); + + + template + void trace(const char *fmt, const Args &... args) + { + default_logger().trace(fmt, args...); + } + template + void debug(const char *fmt, const Args &... args) + { + default_logger().debug(fmt, args...); + } + + template + void info(const char *fmt, const Args &... args) + { + default_logger().info(fmt, args...); + } + + template + void warn(const char *fmt, const Args &... args) + { + default_logger().warn(fmt, args...); + } + + template + void error(const char *fmt, const Args &... args) + { + default_logger().error(fmt, args...); + } + + template + void critical(const char *fmt, const Args &... args) + { + default_logger().critical(fmt, args...); + } + } // namespace lite // factory to create lite logger // implement it in a dedicated compilation unit for fast compiles spdlog::lite::logger create_lite(void* ctx = nullptr); -} // namespace spdlog -#endif //SPDLOG_LIB_LOGGER_H + +} // namespace spdlog \ No newline at end of file diff --git a/lite/spd_types.h b/lite/spd_types.h deleted file mode 100644 index 94be9b34..00000000 --- a/lite/spd_types.h +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright(c) 2019 Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) -// - -// core types, forward declarations and defines used by spdlog - -#pragma once - -namespace spdlog -{ -namespace lite -{ - enum class level{ - trace, - debug, - info, - warning, - error, - critical, - off - - }; -}} \ No newline at end of file From 9ea607907261b1579f02f61b1450232aed601613 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 16:39:05 +0200 Subject: [PATCH 027/157] wip lite --- lite-example/example.cpp | 6 ++- lite/logger.h | 86 +++++++++++++++++++++++++++++++++++----- 2 files changed, 80 insertions(+), 12 deletions(-) diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 05d772aa..929e75dd 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -1,7 +1,11 @@ +#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_INFO #include "logger.h" int main() { //auto l = spdlog::create_lite(); - spdlog::lite::info("HELLO info {}", 123); + //spdlog::lite::info("HELLO info {}", 123); + SPDLITE_TRACE("SOME MACRO {}", 123); + SPDLITE_INFO("SOME MACRO {}", "HHHHH"); + } \ No newline at end of file diff --git a/lite/logger.h b/lite/logger.h index b762b3f5..7246411c 100644 --- a/lite/logger.h +++ b/lite/logger.h @@ -1,28 +1,92 @@ // -// Created by gabi on 3/16/19. -// +// Copyright(c) 2015-present Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + #pragma once #include #include #include "spdlog/fmt/fmt.h" +// +// enable/disable log calls at compile time according to global level. +// +// define SPDLITE_ACTIVE_LEVEL to one of those (before including lite.h): + +#define SPDLITE_LEVEL_TRACE 0 +#define SPDLITE_LEVEL_DEBUG 1 +#define SPDLITE_LEVEL_INFO 2 +#define SPDLITE_LEVEL_WARN 3 +#define SPDLITE_LEVEL_ERROR 4 +#define SPDLITE_LEVEL_CRITICAL 5 +#define SPDLITE_LEVEL_OFF 6 + +#define SPDLITE_LOGGER_CALL(logger, level, ...) \ + if (logger.should_log(level)) \ + logger.log(level, __VA_ARGS__) + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE +#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::trace, __VA_ARGS__) +#define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 +#define SPDLITE_TRACE(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_DEBUG +#define SPDLITE_LOGGER_DEBUG(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::debug, __VA_ARGS__) +#define SPDLITE_DEBUG(...) SPDLITE_LOGGER_DEBUG(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_DEBUG(logger, ...) (void)0 +#define SPDLITE_DEBUG(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_INFO +#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::info, __VA_ARGS__) +#define SPDLITE_INFO(...) SPDLITE_LOGGER_INFO(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_INFO(logger, ...) (void)0 +#define SPDLITE_INFO(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_WARN +#define SPDLITE_LOGGER_WARN(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::warn, __VA_ARGS__) +#define SPDLITE_WARN(...) SPDLITE_LOGGER_WARN(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_WARN(logger, ...) (void)0 +#define SPDLITE_WARN(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_ERROR +#define SPDLITE_LOGGER_ERROR(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::err, __VA_ARGS__) +#define SPDLITE_ERROR(...) SPDLITE_LOGGER_ERROR(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_ERROR(logger, ...) (void)0 +#define SPDLITE_ERROR(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_CRITICAL +#define SPDLITE_LOGGER_CRITICAL(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::critical, __VA_ARGS__) +#define SPDLITE_CRITICAL(...) SPDLITE_LOGGER_CRITICAL(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_CRITICAL(logger, ...) (void)0 +#define SPDLITE_CRITICAL(...) (void)0 +#endif + -//#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::info, __VA_ARGS__) -//#define SPDLITE_INFO(...) SPDLOG_LOGGER_INFO(spdlog::default_logger_raw(), __VA_ARGS__) namespace spdlog { class logger; namespace lite { enum class level{ - trace, - debug, - info, - warn, - err, - critical, - off + trace = SPDLITE_LEVEL_TRACE, + debug =SPDLITE_LEVEL_DEBUG, + info = SPDLITE_LEVEL_INFO, + warn = SPDLITE_LEVEL_WARN, + err = SPDLITE_LEVEL_ERROR, + critical = SPDLITE_LEVEL_CRITICAL, + off = SPDLITE_LEVEL_OFF }; struct src_loc { From 6b0bf33f8ef792c30d93618215f1f3bfa822807d Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 16:39:32 +0200 Subject: [PATCH 028/157] clang-format --- include/spdlog/common.h | 5 +- include/spdlog/sinks/rotating_file_sink.h | 4 +- include/spdlog/sinks/systemd_sink.h | 48 ++-- lite-example/create_lite.cpp | 8 +- lite-example/example.cpp | 5 +- lite/logger.cpp | 8 +- lite/logger.h | 294 +++++++++++----------- tests/test_file_logging.cpp | 2 +- 8 files changed, 183 insertions(+), 191 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index dd9a4785..71273d30 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -128,7 +128,10 @@ enum level_enum static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES; #if !defined(SPDLOG_SHORT_LEVEL_NAMES) -#define SPDLOG_SHORT_LEVEL_NAMES {"T", "D", "I", "W", "E", "C", "O"} +#define SPDLOG_SHORT_LEVEL_NAMES \ + { \ + "T", "D", "I", "W", "E", "C", "O" \ + } #endif static const char *short_level_names[] SPDLOG_SHORT_LEVEL_NAMES; diff --git a/include/spdlog/sinks/rotating_file_sink.h b/include/spdlog/sinks/rotating_file_sink.h index ae0f70f6..35f33a4d 100644 --- a/include/spdlog/sinks/rotating_file_sink.h +++ b/include/spdlog/sinks/rotating_file_sink.h @@ -31,7 +31,7 @@ template class rotating_file_sink final : public base_sink { 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)) , max_size_(max_size) , max_files_(max_files) @@ -150,7 +150,7 @@ using rotating_file_sink_st = rotating_file_sink; template inline std::shared_ptr 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(logger_name, filename, max_file_size, max_files, rotate_on_open); } diff --git a/include/spdlog/sinks/systemd_sink.h b/include/spdlog/sinks/systemd_sink.h index fa9efd83..be143194 100644 --- a/include/spdlog/sinks/systemd_sink.h +++ b/include/spdlog/sinks/systemd_sink.h @@ -18,22 +18,24 @@ namespace spdlog { namespace sinks { -inline int syslog_level(level::level_enum l) { - switch(l) { - case level::off: - case level::trace: - case level::debug: - return LOG_DEBUG; - case level::info: - return LOG_INFO; - case level::warn: - return LOG_WARNING; - case level::err: - return LOG_ERR; - case level::critical: - return LOG_CRIT; - default: - throw std::invalid_argument("systemd_sink.h syslog_level()"); +inline int syslog_level(level::level_enum l) +{ + switch (l) + { + case level::off: + case level::trace: + case level::debug: + return LOG_DEBUG; + case level::info: + return LOG_INFO; + case level::warn: + return LOG_WARNING; + case level::err: + return LOG_ERR; + case level::critical: + return LOG_CRIT; + default: + throw std::invalid_argument("systemd_sink.h syslog_level()"); } } @@ -57,13 +59,7 @@ public: protected: void sink_it_(const details::log_msg &msg) override { - if( sd_journal_print( - syslog_level(msg.level), - "%.*s", - static_cast(msg.payload.size()), - msg.payload.data() - ) - ) + if (sd_journal_print(syslog_level(msg.level), "%.*s", static_cast(msg.payload.size()), msg.payload.data())) throw spdlog_ex("Failed writing to systemd"); } @@ -76,15 +72,13 @@ using systemd_sink_st = systemd_sink; // Create and register a syslog logger template -inline std::shared_ptr systemd_logger_mt( - const std::string &logger_name) +inline std::shared_ptr systemd_logger_mt(const std::string &logger_name) { return Factory::template create(logger_name); } template -inline std::shared_ptr systemd_logger_st( - const std::string &logger_name) +inline std::shared_ptr systemd_logger_st(const std::string &logger_name) { return Factory::template create(logger_name); } diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp index aa375d4e..5345237f 100644 --- a/lite-example/create_lite.cpp +++ b/lite-example/create_lite.cpp @@ -1,15 +1,13 @@ #include "logger.h" #include "spdlog/spdlog.h" - -spdlog::lite::logger spdlog::create_lite(void* ctx) +spdlog::lite::logger spdlog::create_lite(void *ctx) { - if(ctx) { + if (ctx) + { //.. } auto logger_impl = spdlog::default_logger(); logger_impl->set_level(spdlog::level::trace); return spdlog::lite::logger(logger_impl); } - - diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 929e75dd..376d9a68 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -3,9 +3,8 @@ int main() { - //auto l = spdlog::create_lite(); - //spdlog::lite::info("HELLO info {}", 123); + // auto l = spdlog::create_lite(); + // spdlog::lite::info("HELLO info {}", 123); SPDLITE_TRACE("SOME MACRO {}", 123); SPDLITE_INFO("SOME MACRO {}", "HHHHH"); - } \ No newline at end of file diff --git a/lite/logger.cpp b/lite/logger.cpp index 39841553..0cbe766f 100644 --- a/lite/logger.cpp +++ b/lite/logger.cpp @@ -2,9 +2,9 @@ #include "spdlog/spdlog.h" #include "spdlog/logger.h" -static spdlog::level::level_enum to_spdlog_level(spdlog::lite::level level) +static spdlog::level::level_enum to_spdlog_level(spdlog::lite::level level) { - return static_cast(level); + return static_cast(level); } static spdlog::lite::level to_lite_level(spdlog::level::level_enum level) @@ -20,7 +20,7 @@ spdlog::lite::logger::logger(std::shared_ptr impl) bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NOEXCEPT { auto spd_level = to_spdlog_level(level); - return impl_->should_log(spd_level);//TODO level + return impl_->should_log(spd_level); // TODO level } void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt::memory_buffer &formatted) @@ -29,7 +29,6 @@ void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt:: impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); } - void spdlog::lite::logger::log_formatted_src(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) { auto spd_level = to_spdlog_level(lvl); @@ -75,7 +74,6 @@ void spdlog::lite::logger::set_pattern(std::string pattern) impl_->set_pattern(std::move(pattern)); } - spdlog::lite::logger &spdlog::lite::default_logger() { static spdlog::lite::logger s_default(spdlog::default_logger()); diff --git a/lite/logger.h b/lite/logger.h index 7246411c..b55a7159 100644 --- a/lite/logger.h +++ b/lite/logger.h @@ -21,8 +21,8 @@ #define SPDLITE_LEVEL_CRITICAL 5 #define SPDLITE_LEVEL_OFF 6 -#define SPDLITE_LOGGER_CALL(logger, level, ...) \ - if (logger.should_log(level)) \ +#define SPDLITE_LOGGER_CALL(logger, level, ...) \ + if (logger.should_log(level)) \ logger.log(level, __VA_ARGS__) #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE @@ -73,169 +73,169 @@ #define SPDLITE_CRITICAL(...) (void)0 #endif - - namespace spdlog { - class logger; +class logger; - namespace lite { - enum class level{ - trace = SPDLITE_LEVEL_TRACE, - debug =SPDLITE_LEVEL_DEBUG, - info = SPDLITE_LEVEL_INFO, - warn = SPDLITE_LEVEL_WARN, - err = SPDLITE_LEVEL_ERROR, - critical = SPDLITE_LEVEL_CRITICAL, - off = SPDLITE_LEVEL_OFF - }; +namespace lite { +enum class level +{ + trace = SPDLITE_LEVEL_TRACE, + debug = SPDLITE_LEVEL_DEBUG, + info = SPDLITE_LEVEL_INFO, + warn = SPDLITE_LEVEL_WARN, + err = SPDLITE_LEVEL_ERROR, + critical = SPDLITE_LEVEL_CRITICAL, + off = SPDLITE_LEVEL_OFF +}; - struct src_loc { - const char *filename; - int line; - const char* funcname; - }; +struct src_loc +{ + const char *filename; + int line; + const char *funcname; +}; - class logger { - public: - logger() = default; +class logger +{ +public: + logger() = default; - logger(std::shared_ptr impl); - logger(const logger&) = default; - logger(logger&&) = default; - logger& operator=(const logger&) = default; + logger(std::shared_ptr impl); + logger(const logger &) = default; + logger(logger &&) = default; + logger &operator=(const logger &) = default; - ~logger() = default; + ~logger() = default; - bool should_log(spdlog::lite::level lvl) const noexcept; + bool should_log(spdlog::lite::level lvl) const noexcept; - template - void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) { - if (!should_log(lvl)) { - return; - } - fmt::memory_buffer formatted_buf; - fmt::format_to(formatted_buf, fmt, args...); - log_formatted_(lvl, formatted_buf); - } - - - template - void log(const spdlog::lite::src_loc& src, spdlog::lite::level lvl, const char *fmt, const Args &... args) { - if (!should_log(lvl)) { - return; - } - fmt::memory_buffer formatted_buf; - fmt::format_to(formatted_buf, fmt, args...); - log_formatted_src(src, lvl, formatted_buf); - } - - - template - void trace(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::trace, fmt, args...); - } - - template - void trace(const char* source_file, int source_line, const char* source_func, const char *fmt, const Args &... args) - { - spdlog::lite::src_loc src{source_file, source_line, source_func}; - log(src, spdlog::lite::level::trace, fmt, args...); - } - - template - void debug(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::debug, fmt, args...); - } - - template - void info(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::info, fmt, args...); - } - - template - void warn(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::warn, fmt, args...); - } - - template - void error(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::err, fmt, args...); - } - - template - void critical(const char *fmt, const Args &... args) - { - log(spdlog::lite::level::critical, fmt, args...); - } - - std::string name() const; - - // level - void set_level(lite::level level); - lite::level get_level() const; - - // flush - void flush(); - void flush_on(spdlog::lite::level log_level); - spdlog::lite::level flush_level() const; - - // pattern - void set_pattern(std::string pattern); - - protected: - std::shared_ptr impl_; - void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); - void log_formatted_src(const spdlog::lite::src_loc& src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); - - }; - spdlog::lite::logger& default_logger(); - - - template - void trace(const char *fmt, const Args &... args) + template + void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) + { + if (!should_log(lvl)) { - default_logger().trace(fmt, args...); + return; } - template - void debug(const char *fmt, const Args &... args) + fmt::memory_buffer formatted_buf; + fmt::format_to(formatted_buf, fmt, args...); + log_formatted_(lvl, formatted_buf); + } + + template + void log(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const char *fmt, const Args &... args) + { + if (!should_log(lvl)) { - default_logger().debug(fmt, args...); + return; } + fmt::memory_buffer formatted_buf; + fmt::format_to(formatted_buf, fmt, args...); + log_formatted_src(src, lvl, formatted_buf); + } - template - void info(const char *fmt, const Args &... args) - { - default_logger().info(fmt, args...); - } + template + void trace(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::trace, fmt, args...); + } - template - void warn(const char *fmt, const Args &... args) - { - default_logger().warn(fmt, args...); - } + template + void trace(const char *source_file, int source_line, const char *source_func, const char *fmt, const Args &... args) + { + spdlog::lite::src_loc src{source_file, source_line, source_func}; + log(src, spdlog::lite::level::trace, fmt, args...); + } - template - void error(const char *fmt, const Args &... args) - { - default_logger().error(fmt, args...); - } + template + void debug(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::debug, fmt, args...); + } - template - void critical(const char *fmt, const Args &... args) - { - default_logger().critical(fmt, args...); - } + template + void info(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::info, fmt, args...); + } + template + void warn(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::warn, fmt, args...); + } - } // namespace lite + template + void error(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::err, fmt, args...); + } - // factory to create lite logger - // implement it in a dedicated compilation unit for fast compiles - spdlog::lite::logger create_lite(void* ctx = nullptr); + template + void critical(const char *fmt, const Args &... args) + { + log(spdlog::lite::level::critical, fmt, args...); + } + + std::string name() const; + + // level + void set_level(lite::level level); + lite::level get_level() const; + + // flush + void flush(); + void flush_on(spdlog::lite::level log_level); + spdlog::lite::level flush_level() const; + + // pattern + void set_pattern(std::string pattern); + +protected: + std::shared_ptr impl_; + void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + void log_formatted_src(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); +}; +spdlog::lite::logger &default_logger(); + +template +void trace(const char *fmt, const Args &... args) +{ + default_logger().trace(fmt, args...); +} +template +void debug(const char *fmt, const Args &... args) +{ + default_logger().debug(fmt, args...); +} + +template +void info(const char *fmt, const Args &... args) +{ + default_logger().info(fmt, args...); +} + +template +void warn(const char *fmt, const Args &... args) +{ + default_logger().warn(fmt, args...); +} + +template +void error(const char *fmt, const Args &... args) +{ + default_logger().error(fmt, args...); +} + +template +void critical(const char *fmt, const Args &... args) +{ + default_logger().critical(fmt, args...); +} + +} // namespace lite + +// factory to create lite logger +// implement it in a dedicated compilation unit for fast compiles +spdlog::lite::logger create_lite(void *ctx = nullptr); } // namespace spdlog \ No newline at end of file diff --git a/tests/test_file_logging.cpp b/tests/test_file_logging.cpp index dd0c8999..4de3a742 100644 --- a/tests/test_file_logging.cpp +++ b/tests/test_file_logging.cpp @@ -69,7 +69,7 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]]") logger->info("Test message {}", i); } // 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()); } From 9858f2e4997459c1b3961fdb1d154591470195b7 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 17:25:50 +0200 Subject: [PATCH 029/157] renamed --- lite-example/create_lite.cpp | 2 +- lite-example/example.cpp | 2 +- lite/CMakeLists.txt | 2 +- lite/{logger.cpp => spdlite.cpp} | 2 +- lite/{logger.h => spdlite.h} | 0 5 files changed, 4 insertions(+), 4 deletions(-) rename lite/{logger.cpp => spdlite.cpp} (99%) rename lite/{logger.h => spdlite.h} (100%) diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp index 5345237f..beea64ba 100644 --- a/lite-example/create_lite.cpp +++ b/lite-example/create_lite.cpp @@ -1,4 +1,4 @@ -#include "logger.h" +#include "spdlite.h" #include "spdlog/spdlog.h" spdlog::lite::logger spdlog::create_lite(void *ctx) diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 376d9a68..82ddef93 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -1,5 +1,5 @@ #define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_INFO -#include "logger.h" +#include "spdlite.h" int main() { diff --git a/lite/CMakeLists.txt b/lite/CMakeLists.txt index 3ed30be7..ee8a4aab 100644 --- a/lite/CMakeLists.txt +++ b/lite/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.1) project(spdlog_lite) -add_library(spdlog_lite logger.cpp) +add_library(spdlog_lite spdlite.cpp) target_link_libraries(spdlog_lite spdlog::spdlog) diff --git a/lite/logger.cpp b/lite/spdlite.cpp similarity index 99% rename from lite/logger.cpp rename to lite/spdlite.cpp index 0cbe766f..043bd1c8 100644 --- a/lite/logger.cpp +++ b/lite/spdlite.cpp @@ -1,4 +1,4 @@ -#include "logger.h" +#include "spdlite.h" #include "spdlog/spdlog.h" #include "spdlog/logger.h" diff --git a/lite/logger.h b/lite/spdlite.h similarity index 100% rename from lite/logger.h rename to lite/spdlite.h From 9219613957f10e2214b569a9576991a3474a3116 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 19:23:37 +0200 Subject: [PATCH 030/157] Dont check level in macros (redundant) --- include/spdlog/spdlog.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 79a75196..e7a9bacc 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -326,8 +326,7 @@ inline void critical(const wchar_t *fmt, const Args &... args) // SPDLOG_LEVEL_OFF // -#define SPDLOG_LOGGER_CALL(logger, level, ...) \ - if (logger->should_log(level)) \ +#define SPDLOG_LOGGER_CALL(logger, level, ...) \ logger->log(spdlog::source_loc{SPDLOG_FILE_BASENAME(__FILE__), __LINE__, SPDLOG_FUNCTION}, level, __VA_ARGS__) #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE From 90c912a5e235bd66da80b6b6db6c5ab48e441251 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 19:34:50 +0200 Subject: [PATCH 031/157] wip lite --- .clang-tidy | 2 +- clang_tidy.sh | 3 +- example/example.cpp | 12 ++++---- include/spdlog/spdlog.h | 2 +- lite-example/create_lite.cpp | 12 ++++++-- lite-example/example.cpp | 10 +++---- lite/spdlite.cpp | 15 +++++----- lite/spdlite.h | 55 +++++++++++++++++------------------- 8 files changed, 58 insertions(+), 53 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 309c7e94..9079dd9a 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,6 +1,6 @@ Checks: 'modernize-*,modernize-use-override,google-*,-google-runtime-references,misc-*,clang-analyzer-*' 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 FormatStyle: none diff --git a/clang_tidy.sh b/clang_tidy.sh index 6e043e27..4fb8644b 100755 --- a/clang_tidy.sh +++ b/clang_tidy.sh @@ -1,2 +1,3 @@ #!/bin/bash -clang-tidy example/example.cpp -- -I ./include +clang-tidy example/example.cpp -- -I ./include +clang-tidy lite-example/example.cpp -- -I./include -I./lite diff --git a/example/example.cpp b/example/example.cpp index 0c3b8395..c0971620 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -1,11 +1,11 @@ +#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE #include "spdlog/spdlog.h" int main() { - auto l = spdlog::default_logger(); - l->trace("HELLO {}!!!", "lite"); - l->debug("HELLO {}!!!", "lite"); - l->info("HELLO {}!!!", "lite"); - l->warn("HELLO {}!!!", "lite"); - l->critical("HELLO s{}!!!", "lite"); + // auto l = spdlog::create_lite(); + // spdlog::lite::info("HELLO info {}", 123); + + SPDLOG_TRACE("SOME MACRO {}", 123); + SPDLOG_INFO("SOME MACRO {}", "HHHHH"); } \ No newline at end of file diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index e7a9bacc..fd9a1d27 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -326,7 +326,7 @@ inline void critical(const wchar_t *fmt, const Args &... args) // SPDLOG_LEVEL_OFF // -#define SPDLOG_LOGGER_CALL(logger, level, ...) \ +#define SPDLOG_LOGGER_CALL(logger, level, ...) \ logger->log(spdlog::source_loc{SPDLOG_FILE_BASENAME(__FILE__), __LINE__, SPDLOG_FUNCTION}, level, __VA_ARGS__) #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp index beea64ba..a0e5e389 100644 --- a/lite-example/create_lite.cpp +++ b/lite-example/create_lite.cpp @@ -1,5 +1,9 @@ #include "spdlite.h" #include "spdlog/spdlog.h" +#include "spdlog/sinks/basic_file_sink.h" +#include "spdlog/sinks/stdout_color_sinks.h" + + spdlog::lite::logger spdlog::create_lite(void *ctx) { @@ -7,7 +11,9 @@ spdlog::lite::logger spdlog::create_lite(void *ctx) { //.. } - auto logger_impl = spdlog::default_logger(); - logger_impl->set_level(spdlog::level::trace); - return spdlog::lite::logger(logger_impl); + auto logger_impl = spdlog::stdout_color_mt("mylogger"); + auto file_sink = std::make_shared("file.txt", true); + logger_impl->sinks().push_back(file_sink); + logger_impl->set_level(spdlog::level::debug); + return spdlog::lite::logger(std::move(logger_impl)); } diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 82ddef93..87cbc895 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -1,10 +1,10 @@ -#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_INFO +#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_TRACE #include "spdlite.h" int main() { - // auto l = spdlog::create_lite(); - // spdlog::lite::info("HELLO info {}", 123); - SPDLITE_TRACE("SOME MACRO {}", 123); - SPDLITE_INFO("SOME MACRO {}", "HHHHH"); + //auto l = spdlog::create_lite(); + //l.info("Hello spdlog {}", "lite"); + SPDLITE_TRACE("HELLO TRACE"); + } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 043bd1c8..53f98fe9 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -20,22 +20,23 @@ spdlog::lite::logger::logger(std::shared_ptr impl) bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NOEXCEPT { auto spd_level = to_spdlog_level(level); - return impl_->should_log(spd_level); // TODO level + return impl_->should_log(spd_level); // TODO avoid the call using local level member? } -void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt::memory_buffer &formatted) -{ - auto spd_level = to_spdlog_level(level); - impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); -} -void spdlog::lite::logger::log_formatted_src(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) + +void spdlog::lite::logger::log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) { auto spd_level = to_spdlog_level(lvl); spdlog::source_loc source_loc{src.filename, src.line, src.funcname}; impl_->log(source_loc, spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); } +void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt::memory_buffer &formatted) +{ + log_formatted_(src_loc{}, level, formatted); +} + void spdlog::lite::logger::set_level(spdlog::lite::level level) { auto spd_level = to_spdlog_level(level); diff --git a/lite/spdlite.h b/lite/spdlite.h index b55a7159..c1ec48ba 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -21,12 +21,16 @@ #define SPDLITE_LEVEL_CRITICAL 5 #define SPDLITE_LEVEL_OFF 6 -#define SPDLITE_LOGGER_CALL(logger, level, ...) \ - if (logger.should_log(level)) \ - logger.log(level, __VA_ARGS__) + +#define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) + +//with source info +#define SPDLITE_LOGGER_CALL2(logger, level, ...) \ + logger.log(spdlog::lite::src_loc{__FILE__, __LINE__, __FUNCTION__}, level, __VA_ARGS__) + #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE -#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::trace, __VA_ARGS__) +#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL2(logger, spdlog::lite::level::trace, __VA_ARGS__) #define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlog::lite::default_logger(), __VA_ARGS__) #else #define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 @@ -90,9 +94,13 @@ enum class level struct src_loc { - const char *filename; - int line; - const char *funcname; + src_loc() = default; + src_loc(const char *filename, int line, const char *funcname): + filename(filename), line(line), funcname(funcname){} + + const char *filename = nullptr; + int line = 0; + const char *funcname = nullptr; }; class logger @@ -100,7 +108,7 @@ class logger public: logger() = default; - logger(std::shared_ptr impl); + explicit logger(std::shared_ptr impl); logger(const logger &) = default; logger(logger &&) = default; logger &operator=(const logger &) = default; @@ -109,18 +117,6 @@ public: bool should_log(spdlog::lite::level lvl) const noexcept; - template - void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) - { - if (!should_log(lvl)) - { - return; - } - fmt::memory_buffer formatted_buf; - fmt::format_to(formatted_buf, fmt, args...); - log_formatted_(lvl, formatted_buf); - } - template void log(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const char *fmt, const Args &... args) { @@ -130,7 +126,13 @@ public: } fmt::memory_buffer formatted_buf; fmt::format_to(formatted_buf, fmt, args...); - log_formatted_src(src, lvl, formatted_buf); + log_formatted_(src, lvl, formatted_buf); + } + + template + void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) + { + log(spdlog::lite::src_loc{}, lvl, fmt, args...); } template @@ -139,13 +141,7 @@ public: log(spdlog::lite::level::trace, fmt, args...); } - template - void trace(const char *source_file, int source_line, const char *source_func, const char *fmt, const Args &... args) - { - spdlog::lite::src_loc src{source_file, source_line, source_func}; - log(src, spdlog::lite::level::trace, fmt, args...); - } - + template void debug(const char *fmt, const Args &... args) { @@ -193,8 +189,9 @@ public: protected: std::shared_ptr impl_; void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); - void log_formatted_src(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + void log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); }; + spdlog::lite::logger &default_logger(); template From 5056437ca18907e408be5203674c71753b8ab0f7 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 20:06:49 +0200 Subject: [PATCH 032/157] support for const char* messages --- lite/spdlite.cpp | 13 +++++++++--- lite/spdlite.h | 51 ++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 53f98fe9..1e32a570 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -24,7 +24,6 @@ bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NO } - void spdlog::lite::logger::log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) { auto spd_level = to_spdlog_level(lvl); @@ -32,11 +31,19 @@ void spdlog::lite::logger::log_formatted_(const spdlog::lite::src_loc &src, spdl impl_->log(source_loc, spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); } -void spdlog::lite::logger::log_formatted_(spdlog::lite::level level, const fmt::memory_buffer &formatted) +void spdlog::lite::logger::log_string_view_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const string_view_t &sv) { - log_formatted_(src_loc{}, level, formatted); + auto spd_level = to_spdlog_level(lvl); + spdlog::source_loc source_loc{src.filename, src.line, src.funcname}; + impl_->log(source_loc, spd_level, sv); } +void spdlog::lite::logger::log_string_view_(spdlog::lite::level lvl, const string_view_t &sv) +{ + log_string_view_(spdlog::lite::src_loc{}, lvl, sv); +} + + void spdlog::lite::logger::set_level(spdlog::lite::level level) { auto spd_level = to_spdlog_level(level); diff --git a/lite/spdlite.h b/lite/spdlite.h index c1ec48ba..f596cf31 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -77,10 +77,22 @@ #define SPDLITE_CRITICAL(...) (void)0 #endif + + + + namespace spdlog { class logger; namespace lite { + +// string_view type - either std::string_view or fmt::string_view (pre c++17) +#if defined(FMT_USE_STD_STRING_VIEW) + using string_view_t = std::string_view; +#else + using string_view_t = fmt::string_view; +#endif + enum class level { trace = SPDLITE_LEVEL_TRACE, @@ -135,42 +147,74 @@ public: log(spdlog::lite::src_loc{}, lvl, fmt, args...); } + template void trace(const char *fmt, const Args &... args) { log(spdlog::lite::level::trace, fmt, args...); } - + void trace(const char* msg) + { + log_string_view_(spdlog::lite::level::trace, msg); + } + + template void debug(const char *fmt, const Args &... args) { log(spdlog::lite::level::debug, fmt, args...); } + void debug(const char* msg) + { + log_string_view_(spdlog::lite::level::debug, msg); + } + template void info(const char *fmt, const Args &... args) { log(spdlog::lite::level::info, fmt, args...); } + void info(const char* msg) + { + log_string_view_(spdlog::lite::level::info, msg); + } + + template void warn(const char *fmt, const Args &... args) { log(spdlog::lite::level::warn, fmt, args...); } + void warn(const char* msg) + { + log_string_view_(spdlog::lite::level::warn, msg); + } + template void error(const char *fmt, const Args &... args) { log(spdlog::lite::level::err, fmt, args...); } + void error(const char* msg) + { + log_string_view_(spdlog::lite::level::err, msg); + } + template void critical(const char *fmt, const Args &... args) { log(spdlog::lite::level::critical, fmt, args...); } + void critical(const char* msg) + { + log_string_view_(spdlog::lite::level::critical, msg); + } + std::string name() const; @@ -188,8 +232,10 @@ public: protected: std::shared_ptr impl_; - void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); void log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + void log_string_view_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const string_view_t &sv); + void log_string_view_(spdlog::lite::level lvl, const string_view_t &sv); + }; spdlog::lite::logger &default_logger(); @@ -199,6 +245,7 @@ void trace(const char *fmt, const Args &... args) { default_logger().trace(fmt, args...); } + template void debug(const char *fmt, const Args &... args) { From 019eda5b0ce1d593e75722cc56c8591c71d121a4 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 23 Mar 2019 23:13:38 +0200 Subject: [PATCH 033/157] wip lite --- lite-example/create_lite.cpp | 5 ++- lite-example/example.cpp | 11 +++--- lite/spdlite.cpp | 2 -- lite/spdlite.h | 69 ++++++++++++++++-------------------- 4 files changed, 39 insertions(+), 48 deletions(-) diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp index a0e5e389..1a6d6bfe 100644 --- a/lite-example/create_lite.cpp +++ b/lite-example/create_lite.cpp @@ -3,8 +3,6 @@ #include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/stdout_color_sinks.h" - - spdlog::lite::logger spdlog::create_lite(void *ctx) { if (ctx) @@ -13,7 +11,8 @@ spdlog::lite::logger spdlog::create_lite(void *ctx) } auto logger_impl = spdlog::stdout_color_mt("mylogger"); auto file_sink = std::make_shared("file.txt", true); + file_sink->set_level(spdlog::level::info); logger_impl->sinks().push_back(file_sink); - logger_impl->set_level(spdlog::level::debug); + logger_impl->set_level(spdlog::level::trace); return spdlog::lite::logger(std::move(logger_impl)); } diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 87cbc895..60942ebe 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -1,10 +1,11 @@ -#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_TRACE #include "spdlite.h" int main() { - //auto l = spdlog::create_lite(); - //l.info("Hello spdlog {}", "lite"); - SPDLITE_TRACE("HELLO TRACE"); - + using namespace spdlog; + auto l = spdlog::create_lite(); + l.set_level(spdlog::lite::level::trace); + lite::default_logger().set_level(l.get_level()); + lite::trace("hello"); + lite::trace("hello {}", std::string("again")); } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 1e32a570..6b4f4f87 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -23,7 +23,6 @@ bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NO return impl_->should_log(spd_level); // TODO avoid the call using local level member? } - void spdlog::lite::logger::log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) { auto spd_level = to_spdlog_level(lvl); @@ -43,7 +42,6 @@ void spdlog::lite::logger::log_string_view_(spdlog::lite::level lvl, const strin log_string_view_(spdlog::lite::src_loc{}, lvl, sv); } - void spdlog::lite::logger::set_level(spdlog::lite::level level) { auto spd_level = to_spdlog_level(level); diff --git a/lite/spdlite.h b/lite/spdlite.h index f596cf31..77656959 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -21,13 +21,10 @@ #define SPDLITE_LEVEL_CRITICAL 5 #define SPDLITE_LEVEL_OFF 6 +#define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) -#define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) - -//with source info -#define SPDLITE_LOGGER_CALL2(logger, level, ...) \ - logger.log(spdlog::lite::src_loc{__FILE__, __LINE__, __FUNCTION__}, level, __VA_ARGS__) - +// with source info +#define SPDLITE_LOGGER_CALL2(logger, level, ...) logger.log(spdlog::lite::src_loc{__FILE__, __LINE__, __FUNCTION__}, level, __VA_ARGS__) #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE #define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL2(logger, spdlog::lite::level::trace, __VA_ARGS__) @@ -77,10 +74,6 @@ #define SPDLITE_CRITICAL(...) (void)0 #endif - - - - namespace spdlog { class logger; @@ -88,9 +81,9 @@ namespace lite { // string_view type - either std::string_view or fmt::string_view (pre c++17) #if defined(FMT_USE_STD_STRING_VIEW) - using string_view_t = std::string_view; +using string_view_t = std::string_view; #else - using string_view_t = fmt::string_view; +using string_view_t = fmt::string_view; #endif enum class level @@ -107,8 +100,12 @@ enum class level struct src_loc { src_loc() = default; - src_loc(const char *filename, int line, const char *funcname): - filename(filename), line(line), funcname(funcname){} + src_loc(const char *filename, int line, const char *funcname) + : filename(filename) + , line(line) + , funcname(funcname) + { + } const char *filename = nullptr; int line = 0; @@ -147,6 +144,11 @@ public: log(spdlog::lite::src_loc{}, lvl, fmt, args...); } + // trace + void trace(const char *msg) + { + log_string_view_(spdlog::lite::level::trace, msg); + } template void trace(const char *fmt, const Args &... args) @@ -154,21 +156,22 @@ public: log(spdlog::lite::level::trace, fmt, args...); } - void trace(const char* msg) + // debug + void debug(const char *msg) { - log_string_view_(spdlog::lite::level::trace, msg); + log_string_view_(spdlog::lite::level::debug, msg); } - template void debug(const char *fmt, const Args &... args) { log(spdlog::lite::level::debug, fmt, args...); } - void debug(const char* msg) + // info + void info(const char *msg) { - log_string_view_(spdlog::lite::level::debug, msg); + log_string_view_(spdlog::lite::level::info, msg); } template @@ -177,21 +180,22 @@ public: log(spdlog::lite::level::info, fmt, args...); } - void info(const char* msg) + // warn + void warn(const char *msg) { - log_string_view_(spdlog::lite::level::info, msg); + log_string_view_(spdlog::lite::level::warn, msg); } - template void warn(const char *fmt, const Args &... args) { log(spdlog::lite::level::warn, fmt, args...); } - void warn(const char* msg) + // error + void error(const char *msg) { - log_string_view_(spdlog::lite::level::warn, msg); + log_string_view_(spdlog::lite::level::err, msg); } template @@ -200,9 +204,10 @@ public: log(spdlog::lite::level::err, fmt, args...); } - void error(const char* msg) + // critical + void critical(const char *msg) { - log_string_view_(spdlog::lite::level::err, msg); + log_string_view_(spdlog::lite::level::critical, msg); } template @@ -210,24 +215,13 @@ public: { log(spdlog::lite::level::critical, fmt, args...); } - void critical(const char* msg) - { - log_string_view_(spdlog::lite::level::critical, msg); - } - std::string name() const; - - // level void set_level(lite::level level); lite::level get_level() const; - - // flush void flush(); void flush_on(spdlog::lite::level log_level); spdlog::lite::level flush_level() const; - - // pattern void set_pattern(std::string pattern); protected: @@ -235,7 +229,6 @@ protected: void log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); void log_string_view_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const string_view_t &sv); void log_string_view_(spdlog::lite::level lvl, const string_view_t &sv); - }; spdlog::lite::logger &default_logger(); From ea3943a87a1f242c95465038c077a062ff1ff859 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 00:30:08 +0200 Subject: [PATCH 034/157] added printf syntax support for even faster compilation! --- example/example.cpp | 9 ++--- lite-example/example.cpp | 8 +++-- lite/spdlite.cpp | 74 +++++++++++++++++++++++++++++++++----- lite/spdlite.h | 76 ++++++++++++++++++++++++---------------- 4 files changed, 121 insertions(+), 46 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index c0971620..8384906d 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -3,9 +3,10 @@ int main() { - // auto l = spdlog::create_lite(); - // spdlog::lite::info("HELLO info {}", 123); + using namespace spdlog; + auto l = spdlog::default_logger(); + l->set_level(spdlog::level::trace); + + l->trace("hello123123213 "); - SPDLOG_TRACE("SOME MACRO {}", 123); - SPDLOG_INFO("SOME MACRO {}", "HHHHH"); } \ No newline at end of file diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 60942ebe..34bb3ac4 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -5,7 +5,9 @@ int main() using namespace spdlog; auto l = spdlog::create_lite(); l.set_level(spdlog::lite::level::trace); - lite::default_logger().set_level(l.get_level()); - lite::trace("hello"); - lite::trace("hello {}", std::string("again")); + + + l.trace_f("Hello %s ","GABI"); + l.info_f("Hello %d", 12346); + } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 6b4f4f87..2bcdfa1b 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -23,23 +23,71 @@ bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NO return impl_->should_log(spd_level); // TODO avoid the call using local level member? } -void spdlog::lite::logger::log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted) +void spdlog::lite::logger::log(spdlog::lite::level lvl, const string_view_t &sv) { auto spd_level = to_spdlog_level(lvl); - spdlog::source_loc source_loc{src.filename, src.line, src.funcname}; - impl_->log(source_loc, spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); + impl_->log(spd_level, sv); } -void spdlog::lite::logger::log_string_view_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const string_view_t &sv) + +void spdlog::lite::logger::log_printf(spdlog::lite::level lvl, const char* format, va_list args) { - auto spd_level = to_spdlog_level(lvl); - spdlog::source_loc source_loc{src.filename, src.line, src.funcname}; - impl_->log(source_loc, spd_level, sv); + char buffer[500]; + auto size = vsnprintf (buffer, sizeof(buffer),format, args); + if(size < 0) + { + size = snprintf(buffer, sizeof(buffer), "invalid format (%s)", format); + } + log(lvl, string_view_t{buffer, static_cast(size)}); } -void spdlog::lite::logger::log_string_view_(spdlog::lite::level lvl, const string_view_t &sv) + +void spdlog::lite::logger::trace_f(const char *format, ...) { - log_string_view_(spdlog::lite::src_loc{}, lvl, sv); + va_list args; + va_start (args, format); + log_printf(lite::level::trace, format, args); + va_end (args); +} + +void spdlog::lite::logger::debug_f(const char *format, ...) +{ + va_list args; + va_start (args, format); + log_printf(lite::level::debug, format, args); + va_end (args); +} + +void spdlog::lite::logger::info_f(const char *format, ...) +{ + va_list args; + va_start (args, format); + log_printf(lite::level::info, format, args); + va_end (args); +} + +void spdlog::lite::logger::warn_f(const char *format, ...) +{ + va_list args; + va_start (args, format); + log_printf(lite::level::warn, format, args); + va_end (args); +} + +void spdlog::lite::logger::error_f(const char *format, ...) +{ + va_list args; + va_start (args, format); + log_printf(lite::level::err, format, args); + va_end (args); +} + +void spdlog::lite::logger::critical_f(const char *format, ...) +{ + va_list args; + va_start (args, format); + log_printf(lite::level::critical, format, args); + va_end (args); } void spdlog::lite::logger::set_level(spdlog::lite::level level) @@ -80,8 +128,16 @@ void spdlog::lite::logger::set_pattern(std::string pattern) impl_->set_pattern(std::move(pattern)); } +void spdlog::lite::logger::log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted) +{ + auto spd_level = to_spdlog_level(lvl); + impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); +} + spdlog::lite::logger &spdlog::lite::default_logger() { static spdlog::lite::logger s_default(spdlog::default_logger()); return s_default; } + + diff --git a/lite/spdlite.h b/lite/spdlite.h index 77656959..51f4ed6f 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -97,20 +97,6 @@ enum class level off = SPDLITE_LEVEL_OFF }; -struct src_loc -{ - src_loc() = default; - src_loc(const char *filename, int line, const char *funcname) - : filename(filename) - , line(line) - , funcname(funcname) - { - } - - const char *filename = nullptr; - int line = 0; - const char *funcname = nullptr; -}; class logger { @@ -127,7 +113,7 @@ public: bool should_log(spdlog::lite::level lvl) const noexcept; template - void log(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const char *fmt, const Args &... args) + void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) { if (!should_log(lvl)) { @@ -135,19 +121,20 @@ public: } fmt::memory_buffer formatted_buf; fmt::format_to(formatted_buf, fmt, args...); - log_formatted_(src, lvl, formatted_buf); + log_formatted_(lvl, formatted_buf); } - template - void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) - { - log(spdlog::lite::src_loc{}, lvl, fmt, args...); - } + // log string view + void log(spdlog::lite::level lvl, const string_view_t &sv); + void log_printf(spdlog::lite::level lvl, const char* format, va_list args); + + // // trace + // void trace(const char *msg) { - log_string_view_(spdlog::lite::level::trace, msg); + log(spdlog::lite::level::trace, string_view_t(msg)); } template @@ -156,10 +143,14 @@ public: log(spdlog::lite::level::trace, fmt, args...); } + void trace_f(const char *printf_format, ...); + + // // debug + // void debug(const char *msg) { - log_string_view_(spdlog::lite::level::debug, msg); + log(spdlog::lite::level::debug, string_view_t(msg)); } template @@ -168,10 +159,14 @@ public: log(spdlog::lite::level::debug, fmt, args...); } + void debug_f(const char *printf_format, ...); + + // // info + // void info(const char *msg) { - log_string_view_(spdlog::lite::level::info, msg); + log(spdlog::lite::level::info, string_view_t(msg)); } template @@ -180,10 +175,14 @@ public: log(spdlog::lite::level::info, fmt, args...); } + void info_f(const char *printf_format, ...); + + // // warn + // void warn(const char *msg) { - log_string_view_(spdlog::lite::level::warn, msg); + log(spdlog::lite::level::warn, string_view_t(msg)); } template @@ -192,22 +191,31 @@ public: log(spdlog::lite::level::warn, fmt, args...); } + void warn_f(const char *printf_format, ...); + + // // error + // void error(const char *msg) { - log_string_view_(spdlog::lite::level::err, msg); + log(spdlog::lite::level::err, string_view_t(msg)); } + template void error(const char *fmt, const Args &... args) { log(spdlog::lite::level::err, fmt, args...); } + void error_f(const char *printf_format, ...); + + // // critical + // void critical(const char *msg) { - log_string_view_(spdlog::lite::level::critical, msg); + log(spdlog::lite::level::critical, string_view_t(msg)); } template @@ -216,9 +224,18 @@ public: log(spdlog::lite::level::critical, fmt, args...); } + void critical_f(const char *printf_format, ...); + + // + // setters/getters + // std::string name() const; void set_level(lite::level level); lite::level get_level() const; + + // + // flush + // void flush(); void flush_on(spdlog::lite::level log_level); spdlog::lite::level flush_level() const; @@ -226,9 +243,8 @@ public: protected: std::shared_ptr impl_; - void log_formatted_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const fmt::memory_buffer &formatted); - void log_string_view_(const spdlog::lite::src_loc &src, spdlog::lite::level lvl, const string_view_t &sv); - void log_string_view_(spdlog::lite::level lvl, const string_view_t &sv); + void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + }; spdlog::lite::logger &default_logger(); From 91d450df4e670e8b40a43292ffd82b0b9654f4b4 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 00:31:55 +0200 Subject: [PATCH 035/157] Removed source logging --- lite/spdlite.h | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lite/spdlite.h b/lite/spdlite.h index 51f4ed6f..2793f5c1 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -23,11 +23,8 @@ #define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) -// with source info -#define SPDLITE_LOGGER_CALL2(logger, level, ...) logger.log(spdlog::lite::src_loc{__FILE__, __LINE__, __FUNCTION__}, level, __VA_ARGS__) - #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE -#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL2(logger, spdlog::lite::level::trace, __VA_ARGS__) +#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::trace, __VA_ARGS__) #define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlog::lite::default_logger(), __VA_ARGS__) #else #define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 From 23a394d1fc3ed31fd49783829975e78007edee32 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 00:38:00 +0200 Subject: [PATCH 036/157] moved macros to seprate headers --- lite-example/example.cpp | 4 +-- lite/spdlite.cpp | 1 - lite/spdlite.h | 78 ++++------------------------------------ lite/spdlite_macros.h | 67 ++++++++++++++++++++++++++++++++++ 4 files changed, 76 insertions(+), 74 deletions(-) create mode 100644 lite/spdlite_macros.h diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 34bb3ac4..f45eeb9e 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -6,8 +6,8 @@ int main() auto l = spdlog::create_lite(); l.set_level(spdlog::lite::level::trace); - l.trace_f("Hello %s ","GABI"); l.info_f("Hello %d", 12346); - + l.warn_f("Hello %f", 12346.5656); + l.warn("Hello {}", 12346.5656); } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 2bcdfa1b..8b7ace31 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -1,6 +1,5 @@ #include "spdlite.h" #include "spdlog/spdlog.h" -#include "spdlog/logger.h" static spdlog::level::level_enum to_spdlog_level(spdlog::lite::level level) { diff --git a/lite/spdlite.h b/lite/spdlite.h index 2793f5c1..39579002 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -8,69 +8,6 @@ #include #include "spdlog/fmt/fmt.h" -// -// enable/disable log calls at compile time according to global level. -// -// define SPDLITE_ACTIVE_LEVEL to one of those (before including lite.h): - -#define SPDLITE_LEVEL_TRACE 0 -#define SPDLITE_LEVEL_DEBUG 1 -#define SPDLITE_LEVEL_INFO 2 -#define SPDLITE_LEVEL_WARN 3 -#define SPDLITE_LEVEL_ERROR 4 -#define SPDLITE_LEVEL_CRITICAL 5 -#define SPDLITE_LEVEL_OFF 6 - -#define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE -#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::trace, __VA_ARGS__) -#define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 -#define SPDLITE_TRACE(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_DEBUG -#define SPDLITE_LOGGER_DEBUG(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::debug, __VA_ARGS__) -#define SPDLITE_DEBUG(...) SPDLITE_LOGGER_DEBUG(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_DEBUG(logger, ...) (void)0 -#define SPDLITE_DEBUG(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_INFO -#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::info, __VA_ARGS__) -#define SPDLITE_INFO(...) SPDLITE_LOGGER_INFO(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_INFO(logger, ...) (void)0 -#define SPDLITE_INFO(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_WARN -#define SPDLITE_LOGGER_WARN(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::warn, __VA_ARGS__) -#define SPDLITE_WARN(...) SPDLITE_LOGGER_WARN(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_WARN(logger, ...) (void)0 -#define SPDLITE_WARN(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_ERROR -#define SPDLITE_LOGGER_ERROR(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::err, __VA_ARGS__) -#define SPDLITE_ERROR(...) SPDLITE_LOGGER_ERROR(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_ERROR(logger, ...) (void)0 -#define SPDLITE_ERROR(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_CRITICAL -#define SPDLITE_LOGGER_CRITICAL(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::critical, __VA_ARGS__) -#define SPDLITE_CRITICAL(...) SPDLITE_LOGGER_CRITICAL(spdlog::lite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_CRITICAL(logger, ...) (void)0 -#define SPDLITE_CRITICAL(...) (void)0 -#endif - namespace spdlog { class logger; @@ -85,13 +22,13 @@ using string_view_t = fmt::string_view; enum class level { - trace = SPDLITE_LEVEL_TRACE, - debug = SPDLITE_LEVEL_DEBUG, - info = SPDLITE_LEVEL_INFO, - warn = SPDLITE_LEVEL_WARN, - err = SPDLITE_LEVEL_ERROR, - critical = SPDLITE_LEVEL_CRITICAL, - off = SPDLITE_LEVEL_OFF + trace, + debug, + info, + warn, + err, + critical, + off }; @@ -121,7 +58,6 @@ public: log_formatted_(lvl, formatted_buf); } - // log string view void log(spdlog::lite::level lvl, const string_view_t &sv); void log_printf(spdlog::lite::level lvl, const char* format, va_list args); diff --git a/lite/spdlite_macros.h b/lite/spdlite_macros.h new file mode 100644 index 00000000..8d9eb4f8 --- /dev/null +++ b/lite/spdlite_macros.h @@ -0,0 +1,67 @@ +// +// Created by gabi on 3/24/19. +// + +#pragma once +// +// enable/disable log calls at compile time according to global level. +// +// define SPDLITE_ACTIVE_LEVEL to one of those (before including lite.h): + +#define SPDLITE_LEVEL_TRACE 0 +#define SPDLITE_LEVEL_DEBUG 1 +#define SPDLITE_LEVEL_INFO 2 +#define SPDLITE_LEVEL_WARN 3 +#define SPDLITE_LEVEL_ERROR 4 +#define SPDLITE_LEVEL_CRITICAL 5 +#define SPDLITE_LEVEL_OFF 6 + +#define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE +#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::trace, __VA_ARGS__) +#define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 +#define SPDLITE_TRACE(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_DEBUG +#define SPDLITE_LOGGER_DEBUG(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::debug, __VA_ARGS__) +#define SPDLITE_DEBUG(...) SPDLITE_LOGGER_DEBUG(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_DEBUG(logger, ...) (void)0 +#define SPDLITE_DEBUG(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_INFO +#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::info, __VA_ARGS__) +#define SPDLITE_INFO(...) SPDLITE_LOGGER_INFO(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_INFO(logger, ...) (void)0 +#define SPDLITE_INFO(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_WARN +#define SPDLITE_LOGGER_WARN(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::warn, __VA_ARGS__) +#define SPDLITE_WARN(...) SPDLITE_LOGGER_WARN(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_WARN(logger, ...) (void)0 +#define SPDLITE_WARN(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_ERROR +#define SPDLITE_LOGGER_ERROR(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::err, __VA_ARGS__) +#define SPDLITE_ERROR(...) SPDLITE_LOGGER_ERROR(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_ERROR(logger, ...) (void)0 +#define SPDLITE_ERROR(...) (void)0 +#endif + +#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_CRITICAL +#define SPDLITE_LOGGER_CRITICAL(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::critical, __VA_ARGS__) +#define SPDLITE_CRITICAL(...) SPDLITE_LOGGER_CRITICAL(spdlog::lite::default_logger(), __VA_ARGS__) +#else +#define SPDLITE_LOGGER_CRITICAL(logger, ...) (void)0 +#define SPDLITE_CRITICAL(...) (void)0 +#endif From 9971fd2864c6730b46a9f765ee8ccb93a346c35c Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 00:40:27 +0200 Subject: [PATCH 037/157] Fixed examples --- example/example.cpp | 237 +++++++++++++++++++++++++++++++++++++-- lite-example/example.cpp | 1 - 2 files changed, 230 insertions(+), 8 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 8384906d..88b0b415 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -1,12 +1,235 @@ -#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// +// +// spdlog usage example +// +// + +#include + +void stdout_logger_example(); +void basic_example(); +void rotating_example(); +void daily_example(); +void async_example(); +void binary_example(); +void trace_example(); +void multi_sink_example(); +void user_defined_example(); +void err_handler_example(); +void syslog_example(); +void clone_example(); + #include "spdlog/spdlog.h" -int main() +int main(int, char *[]) { - using namespace spdlog; - auto l = spdlog::default_logger(); - l->set_level(spdlog::level::trace); + 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::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); + spdlog::info("Support for floats {:03.2f}", 1.23456); + spdlog::info("Positional args are {1} {0}..", "too", "supported"); + spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left"); - l->trace("hello123123213 "); + // Runtime log levels + spdlog::set_level(spdlog::level::info); // Set global log level to info + spdlog::debug("This message should not be displayed!"); + spdlog::set_level(spdlog::level::trace); // Set specific logger's log level + spdlog::debug("This message should be displayed.."); -} \ No newline at end of file + // Customize msg format for all loggers + spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v"); + spdlog::info("This an info message with custom format"); + spdlog::set_pattern("%+"); // back to default format + + try + { + stdout_logger_example(); + basic_example(); + rotating_example(); + daily_example(); + clone_example(); + async_example(); + binary_example(); + multi_sink_example(); + user_defined_example(); + err_handler_example(); + trace_example(); + + // Flush all *registered* loggers using a worker thread every 3 seconds. + // note: registered loggers *must* be thread safe for this to work correctly! + spdlog::flush_every(std::chrono::seconds(3)); + + // Apply some function on all registered loggers + spdlog::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); + + // Release all spdlog resources, and drop all loggers in the registry. + // This is optional (only mandatory if using windows + async log). + spdlog::shutdown(); + } + + // Exceptions will only be thrown upon failed logger or sink construction (not during logging). + catch (const spdlog::spdlog_ex &ex) + { + std::printf("Log initialization failed: %s\n", ex.what()); + return 1; + } +} + +#include "spdlog/sinks/stdout_color_sinks.h" +// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed. +void stdout_logger_example() +{ + // Create color multi threaded logger. + auto console = spdlog::stdout_color_mt("console"); + // or for stderr: + // auto console = spdlog::stderr_color_mt("error-logger"); +} + +#include "spdlog/sinks/basic_file_sink.h" +void basic_example() +{ + // Create basic file logger (not rotated). + auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt"); +} + +#include "spdlog/sinks/rotating_file_sink.h" +void rotating_example() +{ + // Create a file rotating logger with 5mb size max and 3 rotated files. + auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); +} + +#include "spdlog/sinks/daily_file_sink.h" +void daily_example() +{ + // Create a daily logger - a new file is created every day on 2:30am. + auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); +} + +// Clone a logger and give it new name. +// Useful for creating component/subsystem loggers from some "root" logger. +void clone_example() +{ + auto network_logger = spdlog::default_logger()->clone("network"); + network_logger->info("Logging network stuff.."); +} + +#include "spdlog/async.h" +void async_example() +{ + // Default thread pool settings can be modified *before* creating the async logger: + // spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread. + auto async_file = spdlog::basic_logger_mt("async_file_logger", "logs/async_log.txt"); + // alternatively: + // auto async_file = spdlog::create_async("async_file_logger", "logs/async_log.txt"); + + for (int i = 1; i < 101; ++i) + { + async_file->info("Async message #{}", i); + } +} + +// Log binary data as hex. +// Many types of std::container types can be used. +// Iterator ranges are supported too. +// Format flags: +// {:X} - print in uppercase. +// {:s} - don't separate each byte with space. +// {:p} - don't print the position on each line start. +// {:n} - don't split the output to lines. + +#include "spdlog/fmt/bin_to_hex.h" +void binary_example() +{ + std::vector buf; + for (int i = 0; i < 80; i++) + { + buf.push_back(static_cast(i & 0xff)); + } + spdlog::info("Binary example: {}", spdlog::to_hex(buf)); + spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10)); + // more examples: + // logger->info("uppercase: {:X}", spdlog::to_hex(buf)); + // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf)); + // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf)); +} + +// Compile time log levels. +// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE) +void trace_example() +{ + // trace from default logger + SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23); + // debug from default logger + SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23); + + // trace from logger object + auto logger = spdlog::get("file_logger"); + SPDLOG_LOGGER_TRACE(logger, "another trace message"); +} + +// A logger with multiple sinks (stdout and file) - each with a different format and log level. +void multi_sink_example() +{ + auto console_sink = std::make_shared(); + console_sink->set_level(spdlog::level::warn); + console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v"); + + auto file_sink = std::make_shared("logs/multisink.txt", true); + file_sink->set_level(spdlog::level::trace); + + spdlog::logger logger("multi_sink", {console_sink, file_sink}); + logger.set_level(spdlog::level::debug); + logger.warn("this should appear in both console and file"); + logger.info("this message should not appear in the console, only in the file"); +} + +// User defined types logging by implementing operator<< +#include "spdlog/fmt/ostr.h" // must be included +struct my_type +{ + int i; + template + friend OStream &operator<<(OStream &os, const my_type &c) + { + return os << "[my_type i=" << c.i << "]"; + } +}; + +void user_defined_example() +{ + spdlog::info("user defined type: {}", my_type{14}); +} + +// Custom error handler. Will be triggered on log failure. +void err_handler_example() +{ + // can be set globally or per logger(logger->set_error_handler(..)) + spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); }); +} + +// syslog example (linux/osx/freebsd) +#ifndef _WIN32 +#include "spdlog/sinks/syslog_sink.h" +void syslog_example() +{ + std::string ident = "spdlog-example"; + auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID); + syslog_logger->warn("This is warning that will end up in syslog."); +} +#endif + +// Android example. +#if defined(__ANDROID__) +#include "spdlog/sinks/android_sink.h" +void android_example() +{ + std::string tag = "spdlog-android"; + auto android_logger = spdlog::android_logger_mt("android", tag); + android_logger->critical("Use \"adb shell logcat\" to view this message."); +} + +#endif diff --git a/lite-example/example.cpp b/lite-example/example.cpp index f45eeb9e..d0ce4562 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -2,7 +2,6 @@ int main() { - using namespace spdlog; auto l = spdlog::create_lite(); l.set_level(spdlog::lite::level::trace); From 2f907e3a92710ba95a39026549d59f711db8cf94 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 00:41:22 +0200 Subject: [PATCH 038/157] clang-format --- example/example.cpp | 2 +- lite-example/example.cpp | 2 +- lite/spdlite.cpp | 34 +++++++++++++++------------------- lite/spdlite.h | 15 ++++++--------- 4 files changed, 23 insertions(+), 30 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 88b0b415..345f8bd1 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -70,7 +70,7 @@ int main(int, char *[]) spdlog::shutdown(); } - // Exceptions will only be thrown upon failed logger or sink construction (not during logging). + // Exceptions will only be thrown upon failed logger or sink construction (not during logging). catch (const spdlog::spdlog_ex &ex) { std::printf("Log initialization failed: %s\n", ex.what()); diff --git a/lite-example/example.cpp b/lite-example/example.cpp index d0ce4562..e4185131 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -5,7 +5,7 @@ int main() auto l = spdlog::create_lite(); l.set_level(spdlog::lite::level::trace); - l.trace_f("Hello %s ","GABI"); + l.trace_f("Hello %s ", "GABI"); l.info_f("Hello %d", 12346); l.warn_f("Hello %f", 12346.5656); l.warn("Hello {}", 12346.5656); diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 8b7ace31..80c0388b 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -28,65 +28,63 @@ void spdlog::lite::logger::log(spdlog::lite::level lvl, const string_view_t &sv) impl_->log(spd_level, sv); } - -void spdlog::lite::logger::log_printf(spdlog::lite::level lvl, const char* format, va_list args) +void spdlog::lite::logger::log_printf(spdlog::lite::level lvl, const char *format, va_list args) { char buffer[500]; - auto size = vsnprintf (buffer, sizeof(buffer),format, args); - if(size < 0) + auto size = vsnprintf(buffer, sizeof(buffer), format, args); + if (size < 0) { size = snprintf(buffer, sizeof(buffer), "invalid format (%s)", format); } log(lvl, string_view_t{buffer, static_cast(size)}); } - void spdlog::lite::logger::trace_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::trace, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::debug_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::debug, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::info_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::info, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::warn_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::warn, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::error_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::err, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::critical_f(const char *format, ...) { va_list args; - va_start (args, format); + va_start(args, format); log_printf(lite::level::critical, format, args); - va_end (args); + va_end(args); } void spdlog::lite::logger::set_level(spdlog::lite::level level) @@ -138,5 +136,3 @@ spdlog::lite::logger &spdlog::lite::default_logger() static spdlog::lite::logger s_default(spdlog::default_logger()); return s_default; } - - diff --git a/lite/spdlite.h b/lite/spdlite.h index 39579002..ddfc4b27 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -31,7 +31,6 @@ enum class level off }; - class logger { public: @@ -60,7 +59,7 @@ public: // log string view void log(spdlog::lite::level lvl, const string_view_t &sv); - void log_printf(spdlog::lite::level lvl, const char* format, va_list args); + void log_printf(spdlog::lite::level lvl, const char *format, va_list args); // // trace @@ -76,7 +75,7 @@ public: log(spdlog::lite::level::trace, fmt, args...); } - void trace_f(const char *printf_format, ...); + void trace_f(const char *printf_format, ...); // // debug @@ -92,7 +91,7 @@ public: log(spdlog::lite::level::debug, fmt, args...); } - void debug_f(const char *printf_format, ...); + void debug_f(const char *printf_format, ...); // // info @@ -124,7 +123,7 @@ public: log(spdlog::lite::level::warn, fmt, args...); } - void warn_f(const char *printf_format, ...); + void warn_f(const char *printf_format, ...); // // error @@ -134,14 +133,13 @@ public: log(spdlog::lite::level::err, string_view_t(msg)); } - template void error(const char *fmt, const Args &... args) { log(spdlog::lite::level::err, fmt, args...); } - void error_f(const char *printf_format, ...); + void error_f(const char *printf_format, ...); // // critical @@ -157,7 +155,7 @@ public: log(spdlog::lite::level::critical, fmt, args...); } - void critical_f(const char *printf_format, ...); + void critical_f(const char *printf_format, ...); // // setters/getters @@ -177,7 +175,6 @@ public: protected: std::shared_ptr impl_; void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); - }; spdlog::lite::logger &default_logger(); From 59b4dd4c46d3511352620b7362eae3e7b6049908 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:18:05 +0200 Subject: [PATCH 039/157] update example --- lite-example/create_lite.cpp | 23 ++++++++++++-------- lite-example/example.cpp | 2 +- lite/spdlite.h | 42 ++++++++++++++++++++---------------- 3 files changed, 38 insertions(+), 29 deletions(-) diff --git a/lite-example/create_lite.cpp b/lite-example/create_lite.cpp index 1a6d6bfe..74892d64 100644 --- a/lite-example/create_lite.cpp +++ b/lite-example/create_lite.cpp @@ -3,16 +3,21 @@ #include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/stdout_color_sinks.h" +#define UNUSED(x) (void)(x) + +// example of creating lite logger with console and file sink spdlog::lite::logger spdlog::create_lite(void *ctx) { - if (ctx) - { - //.. - } - auto logger_impl = spdlog::stdout_color_mt("mylogger"); - auto file_sink = std::make_shared("file.txt", true); - file_sink->set_level(spdlog::level::info); - logger_impl->sinks().push_back(file_sink); - logger_impl->set_level(spdlog::level::trace); + UNUSED(ctx); + std::shared_ptr logger_impl; + + auto console_sink = std::make_shared (); + console_sink->set_level(spdlog::level::debug); + + auto file_sink = std::make_shared ("log.txt", true); + file_sink ->set_level(spdlog::level::info); + + logger_impl = std::make_shared("my-logger", spdlog::sinks_init_list{console_sink, file_sink}); + logger_impl->set_level(spdlog::level::debug); return spdlog::lite::logger(std::move(logger_impl)); } diff --git a/lite-example/example.cpp b/lite-example/example.cpp index e4185131..bffd0a2f 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -2,7 +2,7 @@ int main() { - auto l = spdlog::create_lite(); + auto l = spdlog::create_lite((void*)"async"); l.set_level(spdlog::lite::level::trace); l.trace_f("Hello %s ", "GABI"); diff --git a/lite/spdlite.h b/lite/spdlite.h index ddfc4b27..4429b50d 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -43,10 +43,10 @@ public: ~logger() = default; - bool should_log(spdlog::lite::level lvl) const noexcept; + bool should_log(lite::level lvl) const noexcept; template - void log(spdlog::lite::level lvl, const char *fmt, const Args &... args) + void log(lite::level lvl, const char *fmt, const Args &... args) { if (!should_log(lvl)) { @@ -58,21 +58,21 @@ public: } // log string view - void log(spdlog::lite::level lvl, const string_view_t &sv); - void log_printf(spdlog::lite::level lvl, const char *format, va_list args); + void log(lite::level lvl, const string_view_t &sv); + void log_printf(lite::level lvl, const char *format, va_list args); // // trace // void trace(const char *msg) { - log(spdlog::lite::level::trace, string_view_t(msg)); + log(lite::level::trace, string_view_t(msg)); } template void trace(const char *fmt, const Args &... args) { - log(spdlog::lite::level::trace, fmt, args...); + log(lite::level::trace, fmt, args...); } void trace_f(const char *printf_format, ...); @@ -82,13 +82,13 @@ public: // void debug(const char *msg) { - log(spdlog::lite::level::debug, string_view_t(msg)); + log(lite::level::debug, string_view_t(msg)); } template void debug(const char *fmt, const Args &... args) { - log(spdlog::lite::level::debug, fmt, args...); + log(lite::level::debug, fmt, args...); } void debug_f(const char *printf_format, ...); @@ -98,13 +98,13 @@ public: // void info(const char *msg) { - log(spdlog::lite::level::info, string_view_t(msg)); + log(lite::level::info, string_view_t(msg)); } template void info(const char *fmt, const Args &... args) { - log(spdlog::lite::level::info, fmt, args...); + log(lite::level::info, fmt, args...); } void info_f(const char *printf_format, ...); @@ -114,13 +114,13 @@ public: // void warn(const char *msg) { - log(spdlog::lite::level::warn, string_view_t(msg)); + log(lite::level::warn, string_view_t(msg)); } template void warn(const char *fmt, const Args &... args) { - log(spdlog::lite::level::warn, fmt, args...); + log(lite::level::warn, fmt, args...); } void warn_f(const char *printf_format, ...); @@ -130,13 +130,13 @@ public: // void error(const char *msg) { - log(spdlog::lite::level::err, string_view_t(msg)); + log(lite::level::err, string_view_t(msg)); } template void error(const char *fmt, const Args &... args) { - log(spdlog::lite::level::err, fmt, args...); + log(lite::level::err, fmt, args...); } void error_f(const char *printf_format, ...); @@ -146,13 +146,13 @@ public: // void critical(const char *msg) { - log(spdlog::lite::level::critical, string_view_t(msg)); + log(lite::level::critical, string_view_t(msg)); } template void critical(const char *fmt, const Args &... args) { - log(spdlog::lite::level::critical, fmt, args...); + log(lite::level::critical, fmt, args...); } void critical_f(const char *printf_format, ...); @@ -168,13 +168,17 @@ public: // flush // void flush(); - void flush_on(spdlog::lite::level log_level); - spdlog::lite::level flush_level() const; + void flush_on(lite::level log_level); + lite::level flush_level() const; + + // + // set pattern + // void set_pattern(std::string pattern); protected: std::shared_ptr impl_; - void log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted); + void log_formatted_(lite::level lvl, const fmt::memory_buffer &formatted); }; spdlog::lite::logger &default_logger(); From 775a4112159a477502832518b7082bae3620b7c1 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:21:07 +0200 Subject: [PATCH 040/157] renamed printf --- lite-example/example.cpp | 6 +++--- lite/spdlite.cpp | 12 ++++++------ lite/spdlite.h | 12 ++++++------ 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/lite-example/example.cpp b/lite-example/example.cpp index bffd0a2f..1a08bcc7 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -5,8 +5,8 @@ int main() auto l = spdlog::create_lite((void*)"async"); l.set_level(spdlog::lite::level::trace); - l.trace_f("Hello %s ", "GABI"); - l.info_f("Hello %d", 12346); - l.warn_f("Hello %f", 12346.5656); + l.trace_printf("Hello %s ", "GABI"); + l.info_printf("Hello %d", 12346); + l.warn_printf("Hello %f", 12346.5656); l.warn("Hello {}", 12346.5656); } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 80c0388b..e3af7bb7 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -39,7 +39,7 @@ void spdlog::lite::logger::log_printf(spdlog::lite::level lvl, const char *forma log(lvl, string_view_t{buffer, static_cast(size)}); } -void spdlog::lite::logger::trace_f(const char *format, ...) +void spdlog::lite::logger::trace_printf(const char *format, ...) { va_list args; va_start(args, format); @@ -47,7 +47,7 @@ void spdlog::lite::logger::trace_f(const char *format, ...) va_end(args); } -void spdlog::lite::logger::debug_f(const char *format, ...) +void spdlog::lite::logger::debug_printf(const char *format, ...) { va_list args; va_start(args, format); @@ -55,7 +55,7 @@ void spdlog::lite::logger::debug_f(const char *format, ...) va_end(args); } -void spdlog::lite::logger::info_f(const char *format, ...) +void spdlog::lite::logger::info_printf(const char *format, ...) { va_list args; va_start(args, format); @@ -63,7 +63,7 @@ void spdlog::lite::logger::info_f(const char *format, ...) va_end(args); } -void spdlog::lite::logger::warn_f(const char *format, ...) +void spdlog::lite::logger::warn_printf(const char *format, ...) { va_list args; va_start(args, format); @@ -71,7 +71,7 @@ void spdlog::lite::logger::warn_f(const char *format, ...) va_end(args); } -void spdlog::lite::logger::error_f(const char *format, ...) +void spdlog::lite::logger::error_printf(const char *format, ...) { va_list args; va_start(args, format); @@ -79,7 +79,7 @@ void spdlog::lite::logger::error_f(const char *format, ...) va_end(args); } -void spdlog::lite::logger::critical_f(const char *format, ...) +void spdlog::lite::logger::critical_printf(const char *format, ...) { va_list args; va_start(args, format); diff --git a/lite/spdlite.h b/lite/spdlite.h index 4429b50d..5642df79 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -75,7 +75,7 @@ public: log(lite::level::trace, fmt, args...); } - void trace_f(const char *printf_format, ...); + void trace_printf(const char *format, ...); // // debug @@ -91,7 +91,7 @@ public: log(lite::level::debug, fmt, args...); } - void debug_f(const char *printf_format, ...); + void debug_printf(const char *format, ...); // // info @@ -107,7 +107,7 @@ public: log(lite::level::info, fmt, args...); } - void info_f(const char *printf_format, ...); + void info_printf(const char *format, ...); // // warn @@ -123,7 +123,7 @@ public: log(lite::level::warn, fmt, args...); } - void warn_f(const char *printf_format, ...); + void warn_printf(const char *format, ...); // // error @@ -139,7 +139,7 @@ public: log(lite::level::err, fmt, args...); } - void error_f(const char *printf_format, ...); + void error_printf(const char *format, ...); // // critical @@ -155,7 +155,7 @@ public: log(lite::level::critical, fmt, args...); } - void critical_f(const char *printf_format, ...); + void critical_printf(const char *format, ...); // // setters/getters From c4291510e8f4a8bfe4925cdc2d11cc07d462a05a Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:23:14 +0200 Subject: [PATCH 041/157] renamed printf --- lite-example/example.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 1a08bcc7..b89ddc09 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -2,11 +2,11 @@ int main() { - auto l = spdlog::create_lite((void*)"async"); + auto l = spdlog::create_lite(); l.set_level(spdlog::lite::level::trace); l.trace_printf("Hello %s ", "GABI"); l.info_printf("Hello %d", 12346); l.warn_printf("Hello %f", 12346.5656); - l.warn("Hello {}", 12346.5656); + l.warn("Hello {}", "LITE :) "); } \ No newline at end of file From 099812d219663f648b412d9c60da6946b30dbe16 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:27:05 +0200 Subject: [PATCH 042/157] Renamed source file --- lite-example/CMakeLists.txt | 2 +- lite-example/{create_lite.cpp => create_logger.cpp} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename lite-example/{create_lite.cpp => create_logger.cpp} (100%) diff --git a/lite-example/CMakeLists.txt b/lite-example/CMakeLists.txt index d152ecd1..5f309a6b 100644 --- a/lite-example/CMakeLists.txt +++ b/lite-example/CMakeLists.txt @@ -2,7 +2,7 @@ project(spdlog-lite-example CXX) find_package(Threads REQUIRED) -set(LITE_SOURCES example.cpp create_lite.cpp) +set(LITE_SOURCES example.cpp create_logger.cpp) add_executable(${PROJECT_NAME} ${LITE_SOURCES}) diff --git a/lite-example/create_lite.cpp b/lite-example/create_logger.cpp similarity index 100% rename from lite-example/create_lite.cpp rename to lite-example/create_logger.cpp From 84fb11599ea2deb3521ff30f11fb7fa084c54875 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:34:21 +0200 Subject: [PATCH 043/157] Removed default ctor from lite logger --- lite/spdlite.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/lite/spdlite.h b/lite/spdlite.h index 5642df79..e969678a 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -34,8 +34,6 @@ enum class level class logger { public: - logger() = default; - explicit logger(std::shared_ptr impl); logger(const logger &) = default; logger(logger &&) = default; From eba37e8fbe022c42a529ce5f95f8b8101583af15 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:40:20 +0200 Subject: [PATCH 044/157] clone support in lite logger --- lite-example/example.cpp | 4 ++++ lite/spdlite.cpp | 5 +++++ lite/spdlite.h | 5 +++++ 3 files changed, 14 insertions(+) diff --git a/lite-example/example.cpp b/lite-example/example.cpp index b89ddc09..34771028 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -9,4 +9,8 @@ int main() l.info_printf("Hello %d", 12346); l.warn_printf("Hello %f", 12346.5656); l.warn("Hello {}", "LITE :) "); + + auto l2 = l.clone("logger2"); + l2.debug("HELLO"); + } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index e3af7bb7..71a1aacb 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -125,6 +125,11 @@ void spdlog::lite::logger::set_pattern(std::string pattern) impl_->set_pattern(std::move(pattern)); } +spdlog::lite::logger spdlog::lite::logger::clone(std::string logger_name) +{ + return spdlog::lite::logger(impl_->clone(std::move(logger_name))); +} + void spdlog::lite::logger::log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted) { auto spd_level = to_spdlog_level(lvl); diff --git a/lite/spdlite.h b/lite/spdlite.h index e969678a..36a7b7af 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -174,6 +174,11 @@ public: // void set_pattern(std::string pattern); + // + //clone with new name + // + spdlog::lite::logger clone(std::string logger_name); + protected: std::shared_ptr impl_; void log_formatted_(lite::level lvl, const fmt::memory_buffer &formatted); From f74d3e7e94694b12814d0e7306ef3f3ef54fb510 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:44:40 +0200 Subject: [PATCH 045/157] comment --- lite/spdlite.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lite/spdlite.h b/lite/spdlite.h index 36a7b7af..425a762c 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -4,6 +4,10 @@ #pragma once +// lite logger - a lite wrapper around spdlog::logger shared_ptr pimpl +// main purpose is much faster compile time and very cheap copy and move. +// also supports printf format for even faster compile times (by avoiding variadic templates) + #include #include #include "spdlog/fmt/fmt.h" From b78ae5ab100a9902564d3214bfb3982a86d7df68 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 24 Mar 2019 01:50:56 +0200 Subject: [PATCH 046/157] comment --- lite/spdlite.h | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lite/spdlite.h b/lite/spdlite.h index 425a762c..bb9972ee 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -4,9 +4,13 @@ #pragma once -// lite logger - a lite wrapper around spdlog::logger shared_ptr pimpl -// main purpose is much faster compile time and very cheap copy and move. -// also supports printf format for even faster compile times (by avoiding variadic templates) +// lite logger - a pimpl around spdlog::logger shared_ptr: +// much faster compile times. +// can be used as lib or separate compilation unit. +// very cheap copy and move. +// supports printf format for even faster compile (by avoiding variadic templates). +// +// see lite-example/ for usage. #include #include From 99a5484dfbd466d3137feb54d2f978731dca1e68 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 29 Mar 2019 13:56:44 +0300 Subject: [PATCH 047/157] added header to cmake --- lite/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lite/CMakeLists.txt b/lite/CMakeLists.txt index ee8a4aab..f0769a0d 100644 --- a/lite/CMakeLists.txt +++ b/lite/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.1) project(spdlog_lite) -add_library(spdlog_lite spdlite.cpp) +add_library(spdlog_lite spdlite.cpp spdlite.h) target_link_libraries(spdlog_lite spdlog::spdlog) From c7535a91a6b61f94a54a658ff076639028787b76 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 29 Mar 2019 14:38:40 +0300 Subject: [PATCH 048/157] wip lite --- lite-example/create_logger.cpp | 4 +-- lite-example/example.cpp | 9 ++++-- lite/spdlite.cpp | 10 +++---- lite/spdlite.h | 50 ++++++++++++---------------------- 4 files changed, 30 insertions(+), 43 deletions(-) diff --git a/lite-example/create_logger.cpp b/lite-example/create_logger.cpp index 74892d64..07608139 100644 --- a/lite-example/create_logger.cpp +++ b/lite-example/create_logger.cpp @@ -6,7 +6,7 @@ #define UNUSED(x) (void)(x) // example of creating lite logger with console and file sink -spdlog::lite::logger spdlog::create_lite(void *ctx) +spdlog::lite::logger spdlog::lite::create_logger(void *ctx) { UNUSED(ctx); std::shared_ptr logger_impl; @@ -17,7 +17,7 @@ spdlog::lite::logger spdlog::create_lite(void *ctx) auto file_sink = std::make_shared ("log.txt", true); file_sink ->set_level(spdlog::level::info); - logger_impl = std::make_shared("my-logger", spdlog::sinks_init_list{console_sink, file_sink}); + logger_impl = std::make_unique("my-logger", spdlog::sinks_init_list{console_sink, file_sink}); logger_impl->set_level(spdlog::level::debug); return spdlog::lite::logger(std::move(logger_impl)); } diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 34771028..3668a400 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -2,15 +2,18 @@ int main() { - auto l = spdlog::create_lite(); + auto l = spdlog::lite::create_logger(); l.set_level(spdlog::lite::level::trace); - l.trace_printf("Hello %s ", "GABI"); + l.trace_printf("Hello %s ", "GABI"); l.info_printf("Hello %d", 12346); l.warn_printf("Hello %f", 12346.5656); l.warn("Hello {}", "LITE :) "); - auto l2 = l.clone("logger2"); + auto l2 = l.clone("logger2"); l2.debug("HELLO"); + auto l3 = std::move(l); + l3.warn("HELLO FROM L3"); + } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 71a1aacb..f3557543 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -87,18 +87,18 @@ void spdlog::lite::logger::critical_printf(const char *format, ...) va_end(args); } -void spdlog::lite::logger::set_level(spdlog::lite::level level) +void spdlog::lite::logger::set_level(spdlog::lite::level level) noexcept { auto spd_level = to_spdlog_level(level); impl_->set_level(spd_level); } -spdlog::lite::level spdlog::lite::logger::get_level() const +spdlog::lite::level spdlog::lite::logger::level() const noexcept { return to_lite_level(impl_->level()); } -std::string spdlog::lite::logger::name() const +std::string spdlog::lite::logger::name() const noexcept { return impl_->name(); } @@ -114,13 +114,13 @@ void spdlog::lite::logger::flush_on(spdlog::lite::level level) impl_->flush_on(spd_level); } -spdlog::lite::level spdlog::lite::logger::flush_level() const +spdlog::lite::level spdlog::lite::logger::flush_level() const noexcept { return to_lite_level(impl_->flush_level()); } // pattern -void spdlog::lite::logger::set_pattern(std::string pattern) +void spdlog::lite::logger::set_pattern(std::string pattern) noexcept { impl_->set_pattern(std::move(pattern)); } diff --git a/lite/spdlite.h b/lite/spdlite.h index bb9972ee..636dbdab 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -42,7 +42,7 @@ enum class level class logger { public: - explicit logger(std::shared_ptr impl); + explicit logger(std::shared_ptr impl); logger(const logger &) = default; logger(logger &&) = default; logger &operator=(const logger &) = default; @@ -65,6 +65,8 @@ public: // log string view void log(lite::level lvl, const string_view_t &sv); + + // log using printf format void log_printf(lite::level lvl, const char *format, va_list args); // @@ -98,10 +100,8 @@ public: } void debug_printf(const char *format, ...); - - // - // info - // + + // info void info(const char *msg) { log(lite::level::info, string_view_t(msg)); @@ -115,9 +115,7 @@ public: void info_printf(const char *format, ...); - // // warn - // void warn(const char *msg) { log(lite::level::warn, string_view_t(msg)); @@ -131,9 +129,7 @@ public: void warn_printf(const char *format, ...); - // // error - // void error(const char *msg) { log(lite::level::err, string_view_t(msg)); @@ -147,9 +143,7 @@ public: void error_printf(const char *format, ...); - // // critical - // void critical(const char *msg) { log(lite::level::critical, string_view_t(msg)); @@ -163,28 +157,18 @@ public: void critical_printf(const char *format, ...); - // - // setters/getters - // - std::string name() const; - void set_level(lite::level level); - lite::level get_level() const; + // setters/getters + void set_level(lite::level level) noexcept; + void set_pattern(std::string pattern) noexcept; + lite::level level() const noexcept; + std::string name() const noexcept; + lite::level flush_level() const noexcept; - // // flush - // void flush(); void flush_on(lite::level log_level); - lite::level flush_level() const; - - // - // set pattern - // - void set_pattern(std::string pattern); - - // + //clone with new name - // spdlog::lite::logger clone(std::string logger_name); protected: @@ -230,10 +214,10 @@ void critical(const char *fmt, const Args &... args) default_logger().critical(fmt, args...); } +// user implemented factory to create lite logger +// implement it in a seperated and dedicated compilation unit for fast compiles. +logger create_logger(void *ctx = nullptr); + } // namespace lite +} // namespace spdlog -// factory to create lite logger -// implement it in a dedicated compilation unit for fast compiles -spdlog::lite::logger create_lite(void *ctx = nullptr); - -} // namespace spdlog \ No newline at end of file From bc7cd2ccc24e476831039eea837fc3af48a6cf00 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 30 Mar 2019 10:58:56 +0300 Subject: [PATCH 049/157] move lite namespace to topelevel spdlite --- lite-example/create_logger.cpp | 4 +-- lite-example/example.cpp | 4 +-- lite/spdlite.cpp | 62 +++++++++++++++++----------------- lite/spdlite.h | 53 ++++++++++++++--------------- 4 files changed, 61 insertions(+), 62 deletions(-) diff --git a/lite-example/create_logger.cpp b/lite-example/create_logger.cpp index 07608139..bc1b1a8e 100644 --- a/lite-example/create_logger.cpp +++ b/lite-example/create_logger.cpp @@ -6,7 +6,7 @@ #define UNUSED(x) (void)(x) // example of creating lite logger with console and file sink -spdlog::lite::logger spdlog::lite::create_logger(void *ctx) +spdlite::logger spdlite::create_logger(void *ctx) { UNUSED(ctx); std::shared_ptr logger_impl; @@ -19,5 +19,5 @@ spdlog::lite::logger spdlog::lite::create_logger(void *ctx) logger_impl = std::make_unique("my-logger", spdlog::sinks_init_list{console_sink, file_sink}); logger_impl->set_level(spdlog::level::debug); - return spdlog::lite::logger(std::move(logger_impl)); + return spdlite::logger(std::move(logger_impl)); } diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 3668a400..5c945ecf 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -2,8 +2,8 @@ int main() { - auto l = spdlog::lite::create_logger(); - l.set_level(spdlog::lite::level::trace); + auto l = spdlite::create_logger(); + l.set_level(spdlite::level::trace); l.trace_printf("Hello %s ", "GABI"); l.info_printf("Hello %d", 12346); diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index f3557543..945e867d 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -1,34 +1,34 @@ #include "spdlite.h" #include "spdlog/spdlog.h" -static spdlog::level::level_enum to_spdlog_level(spdlog::lite::level level) +static spdlog::level::level_enum to_spdlog_level(spdlite::level level) { return static_cast(level); } -static spdlog::lite::level to_lite_level(spdlog::level::level_enum level) +static spdlite::level to_lite_level(spdlog::level::level_enum level) { - return static_cast(level); + return static_cast(level); } -spdlog::lite::logger::logger(std::shared_ptr impl) +spdlite::logger::logger(std::shared_ptr impl) { impl_ = std::move(impl); } -bool spdlog::lite::logger::should_log(spdlog::lite::level level) const SPDLOG_NOEXCEPT +bool spdlite::logger::should_log(spdlite::level level) const SPDLOG_NOEXCEPT { auto spd_level = to_spdlog_level(level); return impl_->should_log(spd_level); // TODO avoid the call using local level member? } -void spdlog::lite::logger::log(spdlog::lite::level lvl, const string_view_t &sv) +void spdlite::logger::log(spdlite::level lvl, const string_view_t &sv) { auto spd_level = to_spdlog_level(lvl); impl_->log(spd_level, sv); } -void spdlog::lite::logger::log_printf(spdlog::lite::level lvl, const char *format, va_list args) +void spdlite::logger::log_printf(spdlite::level lvl, const char *format, va_list args) { char buffer[500]; auto size = vsnprintf(buffer, sizeof(buffer), format, args); @@ -39,105 +39,105 @@ void spdlog::lite::logger::log_printf(spdlog::lite::level lvl, const char *forma log(lvl, string_view_t{buffer, static_cast(size)}); } -void spdlog::lite::logger::trace_printf(const char *format, ...) +void spdlite::logger::trace_printf(const char *format, ...) { va_list args; va_start(args, format); - log_printf(lite::level::trace, format, args); + log_printf(spdlite::level::trace, format, args); va_end(args); } -void spdlog::lite::logger::debug_printf(const char *format, ...) +void spdlite::logger::debug_printf(const char *format, ...) { va_list args; va_start(args, format); - log_printf(lite::level::debug, format, args); + log_printf(spdlite::level::debug, format, args); va_end(args); } -void spdlog::lite::logger::info_printf(const char *format, ...) +void spdlite::logger::info_printf(const char *format, ...) { va_list args; va_start(args, format); - log_printf(lite::level::info, format, args); + log_printf(spdlite::level::info, format, args); va_end(args); } -void spdlog::lite::logger::warn_printf(const char *format, ...) +void spdlite::logger::warn_printf(const char *format, ...) { va_list args; va_start(args, format); - log_printf(lite::level::warn, format, args); + log_printf(spdlite::level::warn, format, args); va_end(args); } -void spdlog::lite::logger::error_printf(const char *format, ...) +void spdlite::logger::error_printf(const char *format, ...) { va_list args; va_start(args, format); - log_printf(lite::level::err, format, args); + log_printf(spdlite::level::err, format, args); va_end(args); } -void spdlog::lite::logger::critical_printf(const char *format, ...) +void spdlite::logger::critical_printf(const char *format, ...) { va_list args; va_start(args, format); - log_printf(lite::level::critical, format, args); + log_printf(spdlite::level::critical, format, args); va_end(args); } -void spdlog::lite::logger::set_level(spdlog::lite::level level) noexcept +void spdlite::logger::set_level(spdlite::level level) noexcept { auto spd_level = to_spdlog_level(level); impl_->set_level(spd_level); } -spdlog::lite::level spdlog::lite::logger::level() const noexcept +spdlite::level spdlite::logger::level() const noexcept { return to_lite_level(impl_->level()); } -std::string spdlog::lite::logger::name() const noexcept +std::string spdlite::logger::name() const noexcept { return impl_->name(); } -void spdlog::lite::logger::flush() +void spdlite::logger::flush() { impl_->flush(); } -void spdlog::lite::logger::flush_on(spdlog::lite::level level) +void spdlite::logger::flush_on(spdlite::level level) { auto spd_level = to_spdlog_level(level); impl_->flush_on(spd_level); } -spdlog::lite::level spdlog::lite::logger::flush_level() const noexcept +spdlite::level spdlite::logger::flush_level() const noexcept { return to_lite_level(impl_->flush_level()); } // pattern -void spdlog::lite::logger::set_pattern(std::string pattern) noexcept +void spdlite::logger::set_pattern(std::string pattern) noexcept { impl_->set_pattern(std::move(pattern)); } -spdlog::lite::logger spdlog::lite::logger::clone(std::string logger_name) +spdlite::logger spdlite::logger::clone(std::string logger_name) { - return spdlog::lite::logger(impl_->clone(std::move(logger_name))); + return spdlite::logger(impl_->clone(std::move(logger_name))); } -void spdlog::lite::logger::log_formatted_(spdlog::lite::level lvl, const fmt::memory_buffer &formatted) +void spdlite::logger::log_formatted_(spdlite::level lvl, const fmt::memory_buffer &formatted) { auto spd_level = to_spdlog_level(lvl); impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); } -spdlog::lite::logger &spdlog::lite::default_logger() +spdlite::logger &spdlite::default_logger() { - static spdlog::lite::logger s_default(spdlog::default_logger()); + static spdlite::logger s_default(spdlog::default_logger()); return s_default; } diff --git a/lite/spdlite.h b/lite/spdlite.h index 636dbdab..da4e589c 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -18,8 +18,8 @@ namespace spdlog { class logger; - -namespace lite { +} +namespace spdlite { // string_view type - either std::string_view or fmt::string_view (pre c++17) #if defined(FMT_USE_STD_STRING_VIEW) @@ -49,10 +49,10 @@ public: ~logger() = default; - bool should_log(lite::level lvl) const noexcept; + bool should_log(spdlite::level lvl) const noexcept; template - void log(lite::level lvl, const char *fmt, const Args &... args) + void log(spdlite::level lvl, const char *fmt, const Args &... args) { if (!should_log(lvl)) { @@ -64,23 +64,23 @@ public: } // log string view - void log(lite::level lvl, const string_view_t &sv); + void log(spdlite::level lvl, const string_view_t &sv); // log using printf format - void log_printf(lite::level lvl, const char *format, va_list args); + void log_printf(spdlite::level lvl, const char *format, va_list args); // // trace // void trace(const char *msg) { - log(lite::level::trace, string_view_t(msg)); + log(spdlite::level::trace, string_view_t(msg)); } template void trace(const char *fmt, const Args &... args) { - log(lite::level::trace, fmt, args...); + log(spdlite::level::trace, fmt, args...); } void trace_printf(const char *format, ...); @@ -90,13 +90,13 @@ public: // void debug(const char *msg) { - log(lite::level::debug, string_view_t(msg)); + log(spdlite::level::debug, string_view_t(msg)); } template void debug(const char *fmt, const Args &... args) { - log(lite::level::debug, fmt, args...); + log(spdlite::level::debug, fmt, args...); } void debug_printf(const char *format, ...); @@ -104,13 +104,13 @@ public: // info void info(const char *msg) { - log(lite::level::info, string_view_t(msg)); + log(spdlite::level::info, string_view_t(msg)); } template void info(const char *fmt, const Args &... args) { - log(lite::level::info, fmt, args...); + log(spdlite::level::info, fmt, args...); } void info_printf(const char *format, ...); @@ -118,13 +118,13 @@ public: // warn void warn(const char *msg) { - log(lite::level::warn, string_view_t(msg)); + log(spdlite::level::warn, string_view_t(msg)); } template void warn(const char *fmt, const Args &... args) { - log(lite::level::warn, fmt, args...); + log(spdlite::level::warn, fmt, args...); } void warn_printf(const char *format, ...); @@ -132,13 +132,13 @@ public: // error void error(const char *msg) { - log(lite::level::err, string_view_t(msg)); + log(spdlite::level::err, string_view_t(msg)); } template void error(const char *fmt, const Args &... args) { - log(lite::level::err, fmt, args...); + log(spdlite::level::err, fmt, args...); } void error_printf(const char *format, ...); @@ -146,37 +146,37 @@ public: // critical void critical(const char *msg) { - log(lite::level::critical, string_view_t(msg)); + log(spdlite::level::critical, string_view_t(msg)); } template void critical(const char *fmt, const Args &... args) { - log(lite::level::critical, fmt, args...); + log(spdlite::level::critical, fmt, args...); } void critical_printf(const char *format, ...); // setters/getters - void set_level(lite::level level) noexcept; + void set_level(spdlite::level level) noexcept; void set_pattern(std::string pattern) noexcept; - lite::level level() const noexcept; + spdlite::level level() const noexcept; std::string name() const noexcept; - lite::level flush_level() const noexcept; + spdlite::level flush_level() const noexcept; // flush void flush(); - void flush_on(lite::level log_level); + void flush_on(spdlite::level log_level); //clone with new name - spdlog::lite::logger clone(std::string logger_name); + spdlite::logger clone(std::string logger_name); protected: std::shared_ptr impl_; - void log_formatted_(lite::level lvl, const fmt::memory_buffer &formatted); + void log_formatted_(spdlite::level lvl, const fmt::memory_buffer &formatted); }; -spdlog::lite::logger &default_logger(); +spdlite::logger &default_logger(); template void trace(const char *fmt, const Args &... args) @@ -218,6 +218,5 @@ void critical(const char *fmt, const Args &... args) // implement it in a seperated and dedicated compilation unit for fast compiles. logger create_logger(void *ctx = nullptr); -} // namespace lite -} // namespace spdlog +} // namespace spdlite From e32c856a04f8b9f8605604a8922bd94a511f8e38 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 30 Mar 2019 13:49:54 +0300 Subject: [PATCH 050/157] wip lite --- lite-example/create_logger.cpp | 15 +---- lite-example/example.cpp | 23 +++---- lite/spdlite.cpp | 71 ++++++++++++++++++++- lite/spdlite.h | 112 +++++++++++++++++++++++---------- 4 files changed, 158 insertions(+), 63 deletions(-) diff --git a/lite-example/create_logger.cpp b/lite-example/create_logger.cpp index bc1b1a8e..6d7e7690 100644 --- a/lite-example/create_logger.cpp +++ b/lite-example/create_logger.cpp @@ -2,22 +2,13 @@ #include "spdlog/spdlog.h" #include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/stdout_color_sinks.h" +#include "spdlog/sinks/stdout_sinks.h" #define UNUSED(x) (void)(x) // example of creating lite logger with console and file sink -spdlite::logger spdlite::create_logger(void *ctx) +spdlite::logger create_logger(void *ctx) { UNUSED(ctx); - std::shared_ptr logger_impl; - - auto console_sink = std::make_shared (); - console_sink->set_level(spdlog::level::debug); - - auto file_sink = std::make_shared ("log.txt", true); - file_sink ->set_level(spdlog::level::info); - - logger_impl = std::make_unique("my-logger", spdlog::sinks_init_list{console_sink, file_sink}); - logger_impl->set_level(spdlog::level::debug); - return spdlite::logger(std::move(logger_impl)); + return spdlite::default_logger(); } diff --git a/lite-example/example.cpp b/lite-example/example.cpp index 5c945ecf..cb3e2446 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -1,19 +1,12 @@ #include "spdlite.h" int main() -{ - auto l = spdlite::create_logger(); - l.set_level(spdlite::level::trace); - - l.trace_printf("Hello %s ", "GABI"); - l.info_printf("Hello %d", 12346); - l.warn_printf("Hello %f", 12346.5656); - l.warn("Hello {}", "LITE :) "); - - auto l2 = l.clone("logger2"); - l2.debug("HELLO"); - - auto l3 = std::move(l); - l3.warn("HELLO FROM L3"); - +{ + spdlite::default_logger().set_level(spdlite::level::trace); + spdlite::trace_printf("Hello %d", 123); + spdlite::debug_printf("Hello %d", 123); + spdlite::info_printf("Hello %d", 123); + spdlite::warn_printf("Hello %d", 123); + spdlite::error_printf("Hello %d", 123); + spdlite::critical_printf("Hello %d", 123); } \ No newline at end of file diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 945e867d..88e5e23d 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -16,6 +16,11 @@ spdlite::logger::logger(std::shared_ptr impl) impl_ = std::move(impl); } +void spdlite::logger::set_impl(std::shared_ptr impl) +{ + impl_ = std::move(impl); +} + bool spdlite::logger::should_log(spdlite::level level) const SPDLOG_NOEXCEPT { auto spd_level = to_spdlog_level(level); @@ -30,7 +35,7 @@ void spdlite::logger::log(spdlite::level lvl, const string_view_t &sv) void spdlite::logger::log_printf(spdlite::level lvl, const char *format, va_list args) { - char buffer[500]; + char buffer[256]; auto size = vsnprintf(buffer, sizeof(buffer), format, args); if (size < 0) { @@ -136,8 +141,68 @@ void spdlite::logger::log_formatted_(spdlite::level lvl, const fmt::memory_buffe impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); } +spdlite::logger &spdlite::logger::default_logger() +{ + static spdlite::logger default_inst_ = spdlite::logger(spdlog::default_logger()); + return default_inst_; +} + spdlite::logger &spdlite::default_logger() { - static spdlite::logger s_default(spdlog::default_logger()); - return s_default; + return spdlite::logger::default_logger(); } + +// printf +void spdlite::log_printf(spdlite::level lvl, const char *format, va_list args) +{ + default_logger().log_printf(lvl, format, args); +} + +void spdlite::trace_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::trace, format, args); + va_end(args); +} + +void spdlite::debug_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::debug, format, args); + va_end(args); +} + +void spdlite::info_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::info, format, args); + va_end(args); +} + +void spdlite::warn_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::warn, format, args); + va_end(args); +} + +void spdlite::error_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::err, format, args); + va_end(args); +} + +void spdlite::critical_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::critical, format, args); + va_end(args); +} + diff --git a/lite/spdlite.h b/lite/spdlite.h index da4e589c..cadb1ccb 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -42,13 +42,15 @@ enum class level class logger { public: - explicit logger(std::shared_ptr impl); + explicit logger(std::shared_ptr impl); + // logger() = default; //logger with nullptr impl logger(const logger &) = default; logger(logger &&) = default; logger &operator=(const logger &) = default; ~logger() = default; + void set_impl(std::shared_ptr impl); bool should_log(spdlite::level lvl) const noexcept; template @@ -65,26 +67,28 @@ public: // log string view void log(spdlite::level lvl, const string_view_t &sv); - - // log using printf format - void log_printf(spdlite::level lvl, const char *format, va_list args); - + // // trace // + void trace(const char *msg) { log(spdlite::level::trace, string_view_t(msg)); } + template + void trace(const T &msg) + { + log(spdlite::level::trace, string_view_t(msg)); + } + template void trace(const char *fmt, const Args &... args) { log(spdlite::level::trace, fmt, args...); } - - void trace_printf(const char *format, ...); - + // // debug // @@ -93,72 +97,101 @@ public: log(spdlite::level::debug, string_view_t(msg)); } + template + void debug(const T &msg) + { + log(spdlite::level::debug, string_view_t(msg)); + } + template void debug(const char *fmt, const Args &... args) { log(spdlite::level::debug, fmt, args...); } - - void debug_printf(const char *format, ...); - - // info + + // info void info(const char *msg) { log(spdlite::level::info, string_view_t(msg)); } + template + void info(const T &msg) + { + log(spdlite::level::info, string_view_t(msg)); + } + template void info(const char *fmt, const Args &... args) { log(spdlite::level::info, fmt, args...); } - void info_printf(const char *format, ...); - // warn void warn(const char *msg) { log(spdlite::level::warn, string_view_t(msg)); } + template + void warn(const T &msg) + { + log(spdlite::level::warn, string_view_t(msg)); + } + template void warn(const char *fmt, const Args &... args) { log(spdlite::level::warn, fmt, args...); } - - void warn_printf(const char *format, ...); - + // error void error(const char *msg) { log(spdlite::level::err, string_view_t(msg)); } + template + void error(const T &msg) + { + log(spdlite::level::err, string_view_t(msg)); + } + template void error(const char *fmt, const Args &... args) { log(spdlite::level::err, fmt, args...); } - void error_printf(const char *format, ...); - // critical void critical(const char *msg) { log(spdlite::level::critical, string_view_t(msg)); } + template + void critical(const T &msg) + { + log(spdlite::level::critical, string_view_t(msg)); + } + template void critical(const char *fmt, const Args &... args) { log(spdlite::level::critical, fmt, args...); } + // printf formatting + void log_printf(spdlite::level lvl, const char *format, va_list args); + void trace_printf(const char *format, ...); + void debug_printf(const char *format, ...); + void info_printf(const char *format, ...); + void warn_printf(const char *format, ...); + void error_printf(const char *format, ...); void critical_printf(const char *format, ...); - - // setters/getters - void set_level(spdlite::level level) noexcept; + + // setters/getters + void set_level(spdlite::level level) noexcept; void set_pattern(std::string pattern) noexcept; spdlite::level level() const noexcept; std::string name() const noexcept; @@ -167,56 +200,69 @@ public: // flush void flush(); void flush_on(spdlite::level log_level); - - //clone with new name + + // clone with new name spdlite::logger clone(std::string logger_name); + static spdlite::logger &default_logger(); + protected: std::shared_ptr impl_; void log_formatted_(spdlite::level lvl, const fmt::memory_buffer &formatted); }; +// +// spdlite namespace functions - forward the calls to the default_logger. +// spdlite::logger &default_logger(); template -void trace(const char *fmt, const Args &... args) +inline void trace(const char *fmt, const Args &... args) { default_logger().trace(fmt, args...); } template -void debug(const char *fmt, const Args &... args) +inline void debug(const char *fmt, const Args &... args) { default_logger().debug(fmt, args...); } + template -void info(const char *fmt, const Args &... args) +inline void info(const char *fmt, const Args &... args) { default_logger().info(fmt, args...); } template -void warn(const char *fmt, const Args &... args) +inline void warn(const char *fmt, const Args &... args) { default_logger().warn(fmt, args...); } template -void error(const char *fmt, const Args &... args) +inline void error(const char *fmt, const Args &... args) { default_logger().error(fmt, args...); } template -void critical(const char *fmt, const Args &... args) +inline void critical(const char *fmt, const Args &... args) { default_logger().critical(fmt, args...); } -// user implemented factory to create lite logger -// implement it in a seperated and dedicated compilation unit for fast compiles. -logger create_logger(void *ctx = nullptr); +void log_printf(spdlite::level lvl, const char *format, va_list args); +void trace_printf(const char *format, ...); +void debug_printf(const char *format, ...); +void info_printf(const char *format, ...); +void warn_printf(const char *format, ...); +void error_printf(const char *format, ...); +void critical_printf(const char *format, ...); } // namespace spdlite +// user implemented factory to create lite logger +// implement it in a seperated and dedicated compilation unit for fast compiles. +spdlite::logger create_logger(void *ctx = nullptr); From c2b0e223faa3a10fb307d5bd2bef26cab3708e51 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 30 Mar 2019 14:53:02 +0300 Subject: [PATCH 051/157] wip lite --- lite-example/create_logger.cpp | 8 +-- lite-example/example.cpp | 18 +++---- lite/CMakeLists.txt | 2 +- lite/spdlite.cpp | 63 ++-------------------- lite/spdlite.h | 50 ------------------ lite/spdlite_global.cpp | 63 ++++++++++++++++++++++ lite/spdlite_global.h | 95 ++++++++++++++++++++++++++++++++++ lite/spdlite_macros.h | 40 ++++++++------ 8 files changed, 202 insertions(+), 137 deletions(-) create mode 100644 lite/spdlite_global.cpp create mode 100644 lite/spdlite_global.h diff --git a/lite-example/create_logger.cpp b/lite-example/create_logger.cpp index 6d7e7690..696994a4 100644 --- a/lite-example/create_logger.cpp +++ b/lite-example/create_logger.cpp @@ -1,8 +1,10 @@ +// Copyright(c) 2015-present Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + #include "spdlite.h" #include "spdlog/spdlog.h" #include "spdlog/sinks/basic_file_sink.h" -#include "spdlog/sinks/stdout_color_sinks.h" -#include "spdlog/sinks/stdout_sinks.h" + #define UNUSED(x) (void)(x) @@ -10,5 +12,5 @@ spdlite::logger create_logger(void *ctx) { UNUSED(ctx); - return spdlite::default_logger(); + return spdlite::logger(spdlog::basic_logger_mt("logger-name", "log.txt", true)); } diff --git a/lite-example/example.cpp b/lite-example/example.cpp index cb3e2446..9eb7d569 100644 --- a/lite-example/example.cpp +++ b/lite-example/example.cpp @@ -1,12 +1,12 @@ -#include "spdlite.h" +// Copyright(c) 2015-present Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +#include "spdlite.h" +#include "spdlite_global.h" + +#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_TRACE +#include "spdlite_macros.h" int main() -{ - spdlite::default_logger().set_level(spdlite::level::trace); - spdlite::trace_printf("Hello %d", 123); - spdlite::debug_printf("Hello %d", 123); - spdlite::info_printf("Hello %d", 123); - spdlite::warn_printf("Hello %d", 123); - spdlite::error_printf("Hello %d", 123); - spdlite::critical_printf("Hello %d", 123); +{ + SPDLITE_TRACE("SOME INFO {}", 123); } \ No newline at end of file diff --git a/lite/CMakeLists.txt b/lite/CMakeLists.txt index f0769a0d..162727e6 100644 --- a/lite/CMakeLists.txt +++ b/lite/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.1) project(spdlog_lite) -add_library(spdlog_lite spdlite.cpp spdlite.h) +add_library(spdlog_lite spdlite.cpp spdlite.h spdlite_global.cpp spdlite_global.h spdlite_macros.h) target_link_libraries(spdlog_lite spdlog::spdlog) diff --git a/lite/spdlite.cpp b/lite/spdlite.cpp index 88e5e23d..b1e2ae6e 100644 --- a/lite/spdlite.cpp +++ b/lite/spdlite.cpp @@ -1,3 +1,8 @@ +// +// Copyright(c) 2019-present spdlog +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + #include "spdlite.h" #include "spdlog/spdlog.h" @@ -147,62 +152,4 @@ spdlite::logger &spdlite::logger::default_logger() return default_inst_; } -spdlite::logger &spdlite::default_logger() -{ - return spdlite::logger::default_logger(); -} - -// printf -void spdlite::log_printf(spdlite::level lvl, const char *format, va_list args) -{ - default_logger().log_printf(lvl, format, args); -} - -void spdlite::trace_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::trace, format, args); - va_end(args); -} - -void spdlite::debug_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::debug, format, args); - va_end(args); -} - -void spdlite::info_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::info, format, args); - va_end(args); -} - -void spdlite::warn_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::warn, format, args); - va_end(args); -} - -void spdlite::error_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::err, format, args); - va_end(args); -} - -void spdlite::critical_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::critical, format, args); - va_end(args); -} diff --git a/lite/spdlite.h b/lite/spdlite.h index cadb1ccb..762c0b41 100644 --- a/lite/spdlite.h +++ b/lite/spdlite.h @@ -1,4 +1,3 @@ -// // Copyright(c) 2015-present Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) @@ -211,55 +210,6 @@ protected: void log_formatted_(spdlite::level lvl, const fmt::memory_buffer &formatted); }; -// -// spdlite namespace functions - forward the calls to the default_logger. -// -spdlite::logger &default_logger(); - -template -inline void trace(const char *fmt, const Args &... args) -{ - default_logger().trace(fmt, args...); -} - -template -inline void debug(const char *fmt, const Args &... args) -{ - default_logger().debug(fmt, args...); -} - - -template -inline void info(const char *fmt, const Args &... args) -{ - default_logger().info(fmt, args...); -} - -template -inline void warn(const char *fmt, const Args &... args) -{ - default_logger().warn(fmt, args...); -} - -template -inline void error(const char *fmt, const Args &... args) -{ - default_logger().error(fmt, args...); -} - -template -inline void critical(const char *fmt, const Args &... args) -{ - default_logger().critical(fmt, args...); -} - -void log_printf(spdlite::level lvl, const char *format, va_list args); -void trace_printf(const char *format, ...); -void debug_printf(const char *format, ...); -void info_printf(const char *format, ...); -void warn_printf(const char *format, ...); -void error_printf(const char *format, ...); -void critical_printf(const char *format, ...); } // namespace spdlite diff --git a/lite/spdlite_global.cpp b/lite/spdlite_global.cpp new file mode 100644 index 00000000..dd05b31f --- /dev/null +++ b/lite/spdlite_global.cpp @@ -0,0 +1,63 @@ +// Copyright(c) 2015-present Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#include "spdlite_global.h" + +spdlite::logger &spdlite::default_logger() +{ + return spdlite::logger::default_logger(); +} + +// printf +void spdlite::log_printf(spdlite::level lvl, const char *format, va_list args) +{ + default_logger().log_printf(lvl, format, args); +} + +void spdlite::trace_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::trace, format, args); + va_end(args); +} + +void spdlite::debug_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::debug, format, args); + va_end(args); +} + +void spdlite::info_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::info, format, args); + va_end(args); +} + +void spdlite::warn_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::warn, format, args); + va_end(args); +} + +void spdlite::error_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::err, format, args); + va_end(args); +} + +void spdlite::critical_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::critical, format, args); + va_end(args); +} \ No newline at end of file diff --git a/lite/spdlite_global.h b/lite/spdlite_global.h new file mode 100644 index 00000000..64e44137 --- /dev/null +++ b/lite/spdlite_global.h @@ -0,0 +1,95 @@ +// Copyright(c) 2015-present Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + +#include "spdlite.h" +namespace spdlite +{ +// +// spdlite namespace functions - forward the calls to the default_logger. +// +spdlite::logger &default_logger(); + +template +inline void trace(const char *fmt, const Args &... args) +{ + default_logger().trace(fmt, args...); +} + +template +inline void debug(const char *fmt, const Args &... args) +{ + default_logger().debug(fmt, args...); +} + +template +inline void info(const char *fmt, const Args &... args) +{ + default_logger().info(fmt, args...); +} + +template +inline void warn(const char *fmt, const Args &... args) +{ + default_logger().warn(fmt, args...); +} + +template +inline void error(const char *fmt, const Args &... args) +{ + default_logger().error(fmt, args...); +} + +template +inline void critical(const char *fmt, const Args &... args) +{ + default_logger().critical(fmt, args...); +} + +// string view convertable +template +inline void trace(const T &msg) +{ + default_logger().trace(msg); +} + +template +inline void debug(const T &msg) +{ + default_logger().debug(msg); +} + +template +inline void info(const T &msg) +{ + default_logger().info(msg); +} + +template +inline void warn(const T &msg) +{ + default_logger().warn(msg); +} + +template +inline void error(const T &msg) +{ + default_logger().error(msg); +} + +template +inline void critical(const T &msg) +{ + default_logger().critical(msg); +} + +void log_printf(spdlite::level lvl, const char *format, va_list args); +void trace_printf(const char *format, ...); +void debug_printf(const char *format, ...); +void info_printf(const char *format, ...); +void warn_printf(const char *format, ...); +void error_printf(const char *format, ...); +void critical_printf(const char *format, ...); + +} diff --git a/lite/spdlite_macros.h b/lite/spdlite_macros.h index 8d9eb4f8..58c4066d 100644 --- a/lite/spdlite_macros.h +++ b/lite/spdlite_macros.h @@ -1,6 +1,5 @@ -// -// Created by gabi on 3/24/19. -// +// Copyright(c) 2015-present Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once // @@ -8,6 +7,7 @@ // // define SPDLITE_ACTIVE_LEVEL to one of those (before including lite.h): + #define SPDLITE_LEVEL_TRACE 0 #define SPDLITE_LEVEL_DEBUG 1 #define SPDLITE_LEVEL_INFO 2 @@ -18,49 +18,57 @@ #define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_TRACE -#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::trace, __VA_ARGS__) -#define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlog::lite::default_logger(), __VA_ARGS__) +// default level is info +#ifndef SPDLITE_ACTIVE_LEVEL +#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_INFO +#endif + +static_assert(SPDLITE_ACTIVE_LEVEL >= SPDLITE_LEVEL_TRACE && SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_OFF, "SPDLITE_ACTIVE_LEVEL"); + + +#if SPDLITE_ACTIVE_LEVEL == SPDLITE_LEVEL_TRACE +#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::trace, __VA_ARGS__) +#define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlite::default_logger(), __VA_ARGS__) #else #define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 #define SPDLITE_TRACE(...) (void)0 #endif #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_DEBUG -#define SPDLITE_LOGGER_DEBUG(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::debug, __VA_ARGS__) -#define SPDLITE_DEBUG(...) SPDLITE_LOGGER_DEBUG(spdlog::lite::default_logger(), __VA_ARGS__) +#define SPDLITE_LOGGER_DEBUG(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::debug, __VA_ARGS__) +#define SPDLITE_DEBUG(...) SPDLITE_LOGGER_DEBUG(spdlite::default_logger(), __VA_ARGS__) #else #define SPDLITE_LOGGER_DEBUG(logger, ...) (void)0 #define SPDLITE_DEBUG(...) (void)0 #endif #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_INFO -#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::info, __VA_ARGS__) -#define SPDLITE_INFO(...) SPDLITE_LOGGER_INFO(spdlog::lite::default_logger(), __VA_ARGS__) +#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::info, __VA_ARGS__) +#define SPDLITE_INFO(...) SPDLITE_LOGGER_INFO(spdlite::default_logger(), __VA_ARGS__) #else #define SPDLITE_LOGGER_INFO(logger, ...) (void)0 #define SPDLITE_INFO(...) (void)0 #endif #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_WARN -#define SPDLITE_LOGGER_WARN(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::warn, __VA_ARGS__) -#define SPDLITE_WARN(...) SPDLITE_LOGGER_WARN(spdlog::lite::default_logger(), __VA_ARGS__) +#define SPDLITE_LOGGER_WARN(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::warn, __VA_ARGS__) +#define SPDLITE_WARN(...) SPDLITE_LOGGER_WARN(spdlite::default_logger(), __VA_ARGS__) #else #define SPDLITE_LOGGER_WARN(logger, ...) (void)0 #define SPDLITE_WARN(...) (void)0 #endif #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_ERROR -#define SPDLITE_LOGGER_ERROR(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::err, __VA_ARGS__) -#define SPDLITE_ERROR(...) SPDLITE_LOGGER_ERROR(spdlog::lite::default_logger(), __VA_ARGS__) +#define SPDLITE_LOGGER_ERROR(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::err, __VA_ARGS__) +#define SPDLITE_ERROR(...) SPDLITE_LOGGER_ERROR(spdlite::default_logger(), __VA_ARGS__) #else #define SPDLITE_LOGGER_ERROR(logger, ...) (void)0 #define SPDLITE_ERROR(...) (void)0 #endif #if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_CRITICAL -#define SPDLITE_LOGGER_CRITICAL(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlog::lite::level::critical, __VA_ARGS__) -#define SPDLITE_CRITICAL(...) SPDLITE_LOGGER_CRITICAL(spdlog::lite::default_logger(), __VA_ARGS__) +#define SPDLITE_LOGGER_CRITICAL(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::critical, __VA_ARGS__) +#define SPDLITE_CRITICAL(...) SPDLITE_LOGGER_CRITICAL(spdlite::default_logger(), __VA_ARGS__) #else #define SPDLITE_LOGGER_CRITICAL(logger, ...) (void)0 #define SPDLITE_CRITICAL(...) (void)0 From f36be4d5e4a2d3f6fbca5d1133939a8c0d6b1da9 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 30 Mar 2019 16:49:02 +0300 Subject: [PATCH 052/157] Moved lite source to folders| --- CMakeLists.txt | 333 +++++++++--------- lite/CMakeLists.txt | 6 - spdlite/CMakeLists.txt | 14 + .../example}/CMakeLists.txt | 8 +- .../example}/create_logger.cpp | 2 +- {lite-example => spdlite/example}/example.cpp | 22 +- {lite => spdlite/include/spdlite}/spdlite.h | 0 .../include/spdlite}/spdlite_global.h | 0 .../include/spdlite}/spdlite_macros.h | 0 {lite => spdlite/src}/spdlite.cpp | 310 ++++++++-------- {lite => spdlite/src}/spdlite_global.cpp | 124 +++---- 11 files changed, 412 insertions(+), 407 deletions(-) delete mode 100644 lite/CMakeLists.txt create mode 100644 spdlite/CMakeLists.txt rename {lite-example => spdlite/example}/CMakeLists.txt (51%) rename {lite-example => spdlite/example}/create_logger.cpp (93%) rename {lite-example => spdlite/example}/example.cpp (66%) rename {lite => spdlite/include/spdlite}/spdlite.h (100%) rename {lite => spdlite/include/spdlite}/spdlite_global.h (100%) rename {lite => spdlite/include/spdlite}/spdlite_macros.h (100%) rename {lite => spdlite/src}/spdlite.cpp (95%) rename {lite => spdlite/src}/spdlite_global.cpp (92%) diff --git a/CMakeLists.txt b/CMakeLists.txt index c4093403..9aa992cf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,167 +1,166 @@ -# -# Copyright(c) 2015 Ruslan Baratov. -# Distributed under the MIT License (http://opensource.org/licenses/MIT) -# - -cmake_minimum_required(VERSION 3.1) -project(spdlog VERSION 1.3.1 LANGUAGES CXX) -include(CMakeDependentOption) -include(GNUInstallDirs) - -#--------------------------------------------------------------------------------------- -# set default build to release -#--------------------------------------------------------------------------------------- -if(NOT CMAKE_BUILD_TYPE) - set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE) -endif() - -message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) - -#--------------------------------------------------------------------------------------- -# compiler config -#--------------------------------------------------------------------------------------- -set(CMAKE_CXX_STANDARD 11) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") - 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 -#--------------------------------------------------------------------------------------- -include(cmake/sanitizers.cmake) - -#--------------------------------------------------------------------------------------- -# spdlog target -#--------------------------------------------------------------------------------------- -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_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) -option(SPDLOG_BUILD_LITE "Build spdlog lite" ${SPDLOG_MASTER_PROJECT}) - - -if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) - find_package(fmt REQUIRED CONFIG) -endif() - -target_include_directories( - spdlog - INTERFACE - "$" - "$" -) - -if(SPDLOG_FMT_EXTERNAL) - target_compile_definitions(spdlog INTERFACE SPDLOG_FMT_EXTERNAL) - target_link_libraries(spdlog INTERFACE fmt::fmt) -endif() - -set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include") - -if(SPDLOG_BUILD_EXAMPLES) - add_subdirectory(example) -endif() - -if(SPDLOG_BUILD_TESTS) - include(CTest) - add_subdirectory(tests) -endif() - -if(SPDLOG_BUILD_BENCH) - add_subdirectory(bench) -endif() - -if(SPDLOG_BUILD_LITE) - add_subdirectory(lite) - add_subdirectory(lite-example) -endif() - -#--------------------------------------------------------------------------------------- -# Install/export targets and files -#--------------------------------------------------------------------------------------- -if(SPDLOG_INSTALL) - # set files and directories - set(config_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") - set(include_install_dir "${CMAKE_INSTALL_INCLUDEDIR}") - set(pkgconfig_install_dir "${CMAKE_INSTALL_LIBDIR}/pkgconfig") - set(version_config "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.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") - set(targets_export_name "${PROJECT_NAME}Targets") - set(namespace "${PROJECT_NAME}::") - - # generate package version file - include(CMakePackageConfigHelpers) - write_basic_package_version_file( - "${version_config}" COMPATIBILITY SameMajorVersion - ) - - # configure pkg config file - configure_file("cmake/spdlog.pc.in" "${pkg_config}" @ONLY) - # configure spdlogConfig.cmake file - configure_file("cmake/Config.cmake.in" "${project_config}" @ONLY) - - # install targets - 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}) +# +# Copyright(c) 2015 Ruslan Baratov. +# Distributed under the MIT License (http://opensource.org/licenses/MIT) +# + +cmake_minimum_required(VERSION 3.1) +project(spdlog VERSION 1.3.1 LANGUAGES CXX) +include(CMakeDependentOption) +include(GNUInstallDirs) + +#--------------------------------------------------------------------------------------- +# set default build to release +#--------------------------------------------------------------------------------------- +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE) +endif() + +message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) + +#--------------------------------------------------------------------------------------- +# compiler config +#--------------------------------------------------------------------------------------- +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") + 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 +#--------------------------------------------------------------------------------------- +include(cmake/sanitizers.cmake) + +#--------------------------------------------------------------------------------------- +# spdlog target +#--------------------------------------------------------------------------------------- +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_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) +option(SPDLOG_BUILD_LITE "Build spdlog lite" ${SPDLOG_MASTER_PROJECT}) + + +if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) + find_package(fmt REQUIRED CONFIG) +endif() + +target_include_directories( + spdlog + INTERFACE + "$" + "$" +) + +if(SPDLOG_FMT_EXTERNAL) + target_compile_definitions(spdlog INTERFACE SPDLOG_FMT_EXTERNAL) + target_link_libraries(spdlog INTERFACE fmt::fmt) +endif() + +set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include") + +if(SPDLOG_BUILD_EXAMPLES) + add_subdirectory(example) +endif() + +if(SPDLOG_BUILD_TESTS) + include(CTest) + add_subdirectory(tests) +endif() + +if(SPDLOG_BUILD_BENCH) + add_subdirectory(bench) +endif() + +if(SPDLOG_BUILD_LITE) + add_subdirectory(spdlite) +endif() + +#--------------------------------------------------------------------------------------- +# Install/export targets and files +#--------------------------------------------------------------------------------------- +if(SPDLOG_INSTALL) + # set files and directories + set(config_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") + set(include_install_dir "${CMAKE_INSTALL_INCLUDEDIR}") + set(pkgconfig_install_dir "${CMAKE_INSTALL_LIBDIR}/pkgconfig") + set(version_config "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.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") + set(targets_export_name "${PROJECT_NAME}Targets") + set(namespace "${PROJECT_NAME}::") + + # generate package version file + include(CMakePackageConfigHelpers) + write_basic_package_version_file( + "${version_config}" COMPATIBILITY SameMajorVersion + ) + + # configure pkg config file + configure_file("cmake/spdlog.pc.in" "${pkg_config}" @ONLY) + # configure spdlogConfig.cmake file + configure_file("cmake/Config.cmake.in" "${project_config}" @ONLY) + + # install targets + 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}) diff --git a/lite/CMakeLists.txt b/lite/CMakeLists.txt deleted file mode 100644 index 162727e6..00000000 --- a/lite/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -cmake_minimum_required(VERSION 3.1) -project(spdlog_lite) - -add_library(spdlog_lite spdlite.cpp spdlite.h spdlite_global.cpp spdlite_global.h spdlite_macros.h) - -target_link_libraries(spdlog_lite spdlog::spdlog) diff --git a/spdlite/CMakeLists.txt b/spdlite/CMakeLists.txt new file mode 100644 index 00000000..e2b58148 --- /dev/null +++ b/spdlite/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.1) +project(spdlite) + +include_directories(${PROJECT_SOURCE_DIR}/include) +file(GLOB SRC_FILES ${PROJECT_SOURCE_DIR}/src/*.cpp) +file(GLOB HEADER_FILES ${PROJECT_SOURCE_DIR}/include/*.h) + +add_library(spdlite ${SRC_FILES} ${HEADER_FILES}) + +target_link_libraries(spdlite spdlog::spdlog) + +add_subdirectory(example) + + diff --git a/lite-example/CMakeLists.txt b/spdlite/example/CMakeLists.txt similarity index 51% rename from lite-example/CMakeLists.txt rename to spdlite/example/CMakeLists.txt index 5f309a6b..bb0e8244 100644 --- a/lite-example/CMakeLists.txt +++ b/spdlite/example/CMakeLists.txt @@ -1,13 +1,11 @@ -project(spdlog-lite-example CXX) - -find_package(Threads REQUIRED) +project(spdlite-example CXX) set(LITE_SOURCES example.cpp create_logger.cpp) add_executable(${PROJECT_NAME} ${LITE_SOURCES}) -include_directories(../lite) +find_package(Threads) target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) -target_link_libraries(${PROJECT_NAME} PRIVATE spdlog_lite) +target_link_libraries(${PROJECT_NAME} PRIVATE spdlite) diff --git a/lite-example/create_logger.cpp b/spdlite/example/create_logger.cpp similarity index 93% rename from lite-example/create_logger.cpp rename to spdlite/example/create_logger.cpp index 696994a4..b1ab0bf3 100644 --- a/lite-example/create_logger.cpp +++ b/spdlite/example/create_logger.cpp @@ -1,7 +1,7 @@ // Copyright(c) 2015-present Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -#include "spdlite.h" +#include "spdlite/spdlite.h" #include "spdlog/spdlog.h" #include "spdlog/sinks/basic_file_sink.h" diff --git a/lite-example/example.cpp b/spdlite/example/example.cpp similarity index 66% rename from lite-example/example.cpp rename to spdlite/example/example.cpp index 9eb7d569..c816946a 100644 --- a/lite-example/example.cpp +++ b/spdlite/example/example.cpp @@ -1,12 +1,12 @@ -// Copyright(c) 2015-present Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) - -#include "spdlite.h" -#include "spdlite_global.h" - -#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_TRACE -#include "spdlite_macros.h" -int main() -{ - SPDLITE_TRACE("SOME INFO {}", 123); +// Copyright(c) 2015-present Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#include "spdlite/spdlite.h" +#include "spdlite/spdlite_global.h" + +#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_TRACE +#include "spdlite/spdlite_macros.h" +int main() +{ + SPDLITE_TRACE("SOME INFO {}", 123); } \ No newline at end of file diff --git a/lite/spdlite.h b/spdlite/include/spdlite/spdlite.h similarity index 100% rename from lite/spdlite.h rename to spdlite/include/spdlite/spdlite.h diff --git a/lite/spdlite_global.h b/spdlite/include/spdlite/spdlite_global.h similarity index 100% rename from lite/spdlite_global.h rename to spdlite/include/spdlite/spdlite_global.h diff --git a/lite/spdlite_macros.h b/spdlite/include/spdlite/spdlite_macros.h similarity index 100% rename from lite/spdlite_macros.h rename to spdlite/include/spdlite/spdlite_macros.h diff --git a/lite/spdlite.cpp b/spdlite/src/spdlite.cpp similarity index 95% rename from lite/spdlite.cpp rename to spdlite/src/spdlite.cpp index b1e2ae6e..1cc96101 100644 --- a/lite/spdlite.cpp +++ b/spdlite/src/spdlite.cpp @@ -1,155 +1,155 @@ -// -// Copyright(c) 2019-present spdlog -// Distributed under the MIT License (http://opensource.org/licenses/MIT) -// - -#include "spdlite.h" -#include "spdlog/spdlog.h" - -static spdlog::level::level_enum to_spdlog_level(spdlite::level level) -{ - return static_cast(level); -} - -static spdlite::level to_lite_level(spdlog::level::level_enum level) -{ - return static_cast(level); -} - -spdlite::logger::logger(std::shared_ptr impl) -{ - impl_ = std::move(impl); -} - -void spdlite::logger::set_impl(std::shared_ptr impl) -{ - impl_ = std::move(impl); -} - -bool spdlite::logger::should_log(spdlite::level level) const SPDLOG_NOEXCEPT -{ - auto spd_level = to_spdlog_level(level); - return impl_->should_log(spd_level); // TODO avoid the call using local level member? -} - -void spdlite::logger::log(spdlite::level lvl, const string_view_t &sv) -{ - auto spd_level = to_spdlog_level(lvl); - impl_->log(spd_level, sv); -} - -void spdlite::logger::log_printf(spdlite::level lvl, const char *format, va_list args) -{ - char buffer[256]; - auto size = vsnprintf(buffer, sizeof(buffer), format, args); - if (size < 0) - { - size = snprintf(buffer, sizeof(buffer), "invalid format (%s)", format); - } - log(lvl, string_view_t{buffer, static_cast(size)}); -} - -void spdlite::logger::trace_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::trace, format, args); - va_end(args); -} - -void spdlite::logger::debug_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::debug, format, args); - va_end(args); -} - -void spdlite::logger::info_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::info, format, args); - va_end(args); -} - -void spdlite::logger::warn_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::warn, format, args); - va_end(args); -} - -void spdlite::logger::error_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::err, format, args); - va_end(args); -} - -void spdlite::logger::critical_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::critical, format, args); - va_end(args); -} - -void spdlite::logger::set_level(spdlite::level level) noexcept -{ - auto spd_level = to_spdlog_level(level); - impl_->set_level(spd_level); -} - -spdlite::level spdlite::logger::level() const noexcept -{ - return to_lite_level(impl_->level()); -} - -std::string spdlite::logger::name() const noexcept -{ - return impl_->name(); -} - -void spdlite::logger::flush() -{ - impl_->flush(); -} - -void spdlite::logger::flush_on(spdlite::level level) -{ - auto spd_level = to_spdlog_level(level); - impl_->flush_on(spd_level); -} - -spdlite::level spdlite::logger::flush_level() const noexcept -{ - return to_lite_level(impl_->flush_level()); -} - -// pattern -void spdlite::logger::set_pattern(std::string pattern) noexcept -{ - impl_->set_pattern(std::move(pattern)); -} - -spdlite::logger spdlite::logger::clone(std::string logger_name) -{ - return spdlite::logger(impl_->clone(std::move(logger_name))); -} - -void spdlite::logger::log_formatted_(spdlite::level lvl, const fmt::memory_buffer &formatted) -{ - auto spd_level = to_spdlog_level(lvl); - impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); -} - -spdlite::logger &spdlite::logger::default_logger() -{ - static spdlite::logger default_inst_ = spdlite::logger(spdlog::default_logger()); - return default_inst_; -} - - +// +// Copyright(c) 2019-present spdlog +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include "spdlite/spdlite.h" +#include "spdlog/spdlog.h" + +static spdlog::level::level_enum to_spdlog_level(spdlite::level level) +{ + return static_cast(level); +} + +static spdlite::level to_lite_level(spdlog::level::level_enum level) +{ + return static_cast(level); +} + +spdlite::logger::logger(std::shared_ptr impl) +{ + impl_ = std::move(impl); +} + +void spdlite::logger::set_impl(std::shared_ptr impl) +{ + impl_ = std::move(impl); +} + +bool spdlite::logger::should_log(spdlite::level level) const SPDLOG_NOEXCEPT +{ + auto spd_level = to_spdlog_level(level); + return impl_->should_log(spd_level); // TODO avoid the call using local level member? +} + +void spdlite::logger::log(spdlite::level lvl, const string_view_t &sv) +{ + auto spd_level = to_spdlog_level(lvl); + impl_->log(spd_level, sv); +} + +void spdlite::logger::log_printf(spdlite::level lvl, const char *format, va_list args) +{ + char buffer[256]; + auto size = vsnprintf(buffer, sizeof(buffer), format, args); + if (size < 0) + { + size = snprintf(buffer, sizeof(buffer), "invalid format (%s)", format); + } + log(lvl, string_view_t{buffer, static_cast(size)}); +} + +void spdlite::logger::trace_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(spdlite::level::trace, format, args); + va_end(args); +} + +void spdlite::logger::debug_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(spdlite::level::debug, format, args); + va_end(args); +} + +void spdlite::logger::info_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(spdlite::level::info, format, args); + va_end(args); +} + +void spdlite::logger::warn_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(spdlite::level::warn, format, args); + va_end(args); +} + +void spdlite::logger::error_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(spdlite::level::err, format, args); + va_end(args); +} + +void spdlite::logger::critical_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(spdlite::level::critical, format, args); + va_end(args); +} + +void spdlite::logger::set_level(spdlite::level level) noexcept +{ + auto spd_level = to_spdlog_level(level); + impl_->set_level(spd_level); +} + +spdlite::level spdlite::logger::level() const noexcept +{ + return to_lite_level(impl_->level()); +} + +std::string spdlite::logger::name() const noexcept +{ + return impl_->name(); +} + +void spdlite::logger::flush() +{ + impl_->flush(); +} + +void spdlite::logger::flush_on(spdlite::level level) +{ + auto spd_level = to_spdlog_level(level); + impl_->flush_on(spd_level); +} + +spdlite::level spdlite::logger::flush_level() const noexcept +{ + return to_lite_level(impl_->flush_level()); +} + +// pattern +void spdlite::logger::set_pattern(std::string pattern) noexcept +{ + impl_->set_pattern(std::move(pattern)); +} + +spdlite::logger spdlite::logger::clone(std::string logger_name) +{ + return spdlite::logger(impl_->clone(std::move(logger_name))); +} + +void spdlite::logger::log_formatted_(spdlite::level lvl, const fmt::memory_buffer &formatted) +{ + auto spd_level = to_spdlog_level(lvl); + impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); +} + +spdlite::logger &spdlite::logger::default_logger() +{ + static spdlite::logger default_inst_ = spdlite::logger(spdlog::default_logger()); + return default_inst_; +} + + diff --git a/lite/spdlite_global.cpp b/spdlite/src/spdlite_global.cpp similarity index 92% rename from lite/spdlite_global.cpp rename to spdlite/src/spdlite_global.cpp index dd05b31f..59e82b1d 100644 --- a/lite/spdlite_global.cpp +++ b/spdlite/src/spdlite_global.cpp @@ -1,63 +1,63 @@ -// Copyright(c) 2015-present Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) - -#include "spdlite_global.h" - -spdlite::logger &spdlite::default_logger() -{ - return spdlite::logger::default_logger(); -} - -// printf -void spdlite::log_printf(spdlite::level lvl, const char *format, va_list args) -{ - default_logger().log_printf(lvl, format, args); -} - -void spdlite::trace_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::trace, format, args); - va_end(args); -} - -void spdlite::debug_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::debug, format, args); - va_end(args); -} - -void spdlite::info_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::info, format, args); - va_end(args); -} - -void spdlite::warn_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::warn, format, args); - va_end(args); -} - -void spdlite::error_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::err, format, args); - va_end(args); -} - -void spdlite::critical_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::critical, format, args); - va_end(args); +// Copyright(c) 2015-present Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#include "spdlite/spdlite_global.h" + +spdlite::logger &spdlite::default_logger() +{ + return spdlite::logger::default_logger(); +} + +// printf +void spdlite::log_printf(spdlite::level lvl, const char *format, va_list args) +{ + default_logger().log_printf(lvl, format, args); +} + +void spdlite::trace_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::trace, format, args); + va_end(args); +} + +void spdlite::debug_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::debug, format, args); + va_end(args); +} + +void spdlite::info_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::info, format, args); + va_end(args); +} + +void spdlite::warn_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::warn, format, args); + va_end(args); +} + +void spdlite::error_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::err, format, args); + va_end(args); +} + +void spdlite::critical_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + log_printf(level::critical, format, args); + va_end(args); } \ No newline at end of file From b57d514b1e9108d336ffe4df3342c3488bd2d347 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 30 Mar 2019 16:56:37 +0300 Subject: [PATCH 053/157] added missing files --- spdlite/example/example.cpp | 2 +- spdlite/include/spdlite/{spdlite_global.h => default_api.h} | 0 spdlite/src/{spdlite_global.cpp => spdlite_default_api.cpp} | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) rename spdlite/include/spdlite/{spdlite_global.h => default_api.h} (100%) rename spdlite/src/{spdlite_global.cpp => spdlite_default_api.cpp} (92%) diff --git a/spdlite/example/example.cpp b/spdlite/example/example.cpp index c816946a..47fdf06e 100644 --- a/spdlite/example/example.cpp +++ b/spdlite/example/example.cpp @@ -2,7 +2,7 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) #include "spdlite/spdlite.h" -#include "spdlite/spdlite_global.h" +#include "spdlite/default_api.h" #define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_TRACE #include "spdlite/spdlite_macros.h" diff --git a/spdlite/include/spdlite/spdlite_global.h b/spdlite/include/spdlite/default_api.h similarity index 100% rename from spdlite/include/spdlite/spdlite_global.h rename to spdlite/include/spdlite/default_api.h diff --git a/spdlite/src/spdlite_global.cpp b/spdlite/src/spdlite_default_api.cpp similarity index 92% rename from spdlite/src/spdlite_global.cpp rename to spdlite/src/spdlite_default_api.cpp index 59e82b1d..73a0704d 100644 --- a/spdlite/src/spdlite_global.cpp +++ b/spdlite/src/spdlite_default_api.cpp @@ -1,7 +1,7 @@ // Copyright(c) 2015-present Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -#include "spdlite/spdlite_global.h" +#include "spdlite/default_api.h" spdlite::logger &spdlite::default_logger() { From ef8773a89b63e956863fb4cee15d3265960f18d8 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 5 Apr 2019 13:26:33 +0300 Subject: [PATCH 054/157] Moved logger_impl back into logger.h --- example/example.cpp | 234 +------- include/spdlog/details/logger_impl.h | 762 +++++++++++++-------------- include/spdlog/logger.h | 416 +++++++++++++-- 3 files changed, 751 insertions(+), 661 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 345f8bd1..b42c9440 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -7,229 +7,19 @@ // // -#include +#include "spdlog/logger.h" + + +namespace spdlog { +class logger; +} + +spdlog::logger *get_logger(); -void stdout_logger_example(); -void basic_example(); -void rotating_example(); -void daily_example(); -void async_example(); -void binary_example(); -void trace_example(); -void multi_sink_example(); -void user_defined_example(); -void err_handler_example(); -void syslog_example(); -void clone_example(); -#include "spdlog/spdlog.h" int main(int, char *[]) -{ - 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::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); - spdlog::info("Support for floats {:03.2f}", 1.23456); - spdlog::info("Positional args are {1} {0}..", "too", "supported"); - spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left"); - - // Runtime log levels - spdlog::set_level(spdlog::level::info); // Set global log level to info - spdlog::debug("This message should not be displayed!"); - spdlog::set_level(spdlog::level::trace); // Set specific logger's log level - spdlog::debug("This message should be displayed.."); - - // Customize msg format for all loggers - spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v"); - spdlog::info("This an info message with custom format"); - spdlog::set_pattern("%+"); // back to default format - - try - { - stdout_logger_example(); - basic_example(); - rotating_example(); - daily_example(); - clone_example(); - async_example(); - binary_example(); - multi_sink_example(); - user_defined_example(); - err_handler_example(); - trace_example(); - - // Flush all *registered* loggers using a worker thread every 3 seconds. - // note: registered loggers *must* be thread safe for this to work correctly! - spdlog::flush_every(std::chrono::seconds(3)); - - // Apply some function on all registered loggers - spdlog::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); - - // Release all spdlog resources, and drop all loggers in the registry. - // This is optional (only mandatory if using windows + async log). - spdlog::shutdown(); - } - - // Exceptions will only be thrown upon failed logger or sink construction (not during logging). - catch (const spdlog::spdlog_ex &ex) - { - std::printf("Log initialization failed: %s\n", ex.what()); - return 1; - } -} - -#include "spdlog/sinks/stdout_color_sinks.h" -// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed. -void stdout_logger_example() -{ - // Create color multi threaded logger. - auto console = spdlog::stdout_color_mt("console"); - // or for stderr: - // auto console = spdlog::stderr_color_mt("error-logger"); -} - -#include "spdlog/sinks/basic_file_sink.h" -void basic_example() -{ - // Create basic file logger (not rotated). - auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt"); -} - -#include "spdlog/sinks/rotating_file_sink.h" -void rotating_example() -{ - // Create a file rotating logger with 5mb size max and 3 rotated files. - auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); -} - -#include "spdlog/sinks/daily_file_sink.h" -void daily_example() -{ - // Create a daily logger - a new file is created every day on 2:30am. - auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); -} - -// Clone a logger and give it new name. -// Useful for creating component/subsystem loggers from some "root" logger. -void clone_example() -{ - auto network_logger = spdlog::default_logger()->clone("network"); - network_logger->info("Logging network stuff.."); -} - -#include "spdlog/async.h" -void async_example() -{ - // Default thread pool settings can be modified *before* creating the async logger: - // spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread. - auto async_file = spdlog::basic_logger_mt("async_file_logger", "logs/async_log.txt"); - // alternatively: - // auto async_file = spdlog::create_async("async_file_logger", "logs/async_log.txt"); - - for (int i = 1; i < 101; ++i) - { - async_file->info("Async message #{}", i); - } -} - -// Log binary data as hex. -// Many types of std::container types can be used. -// Iterator ranges are supported too. -// Format flags: -// {:X} - print in uppercase. -// {:s} - don't separate each byte with space. -// {:p} - don't print the position on each line start. -// {:n} - don't split the output to lines. - -#include "spdlog/fmt/bin_to_hex.h" -void binary_example() -{ - std::vector buf; - for (int i = 0; i < 80; i++) - { - buf.push_back(static_cast(i & 0xff)); - } - spdlog::info("Binary example: {}", spdlog::to_hex(buf)); - spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10)); - // more examples: - // logger->info("uppercase: {:X}", spdlog::to_hex(buf)); - // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf)); - // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf)); -} - -// Compile time log levels. -// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE) -void trace_example() -{ - // trace from default logger - SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23); - // debug from default logger - SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23); - - // trace from logger object - auto logger = spdlog::get("file_logger"); - SPDLOG_LOGGER_TRACE(logger, "another trace message"); -} - -// A logger with multiple sinks (stdout and file) - each with a different format and log level. -void multi_sink_example() -{ - auto console_sink = std::make_shared(); - console_sink->set_level(spdlog::level::warn); - console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v"); - - auto file_sink = std::make_shared("logs/multisink.txt", true); - file_sink->set_level(spdlog::level::trace); - - spdlog::logger logger("multi_sink", {console_sink, file_sink}); - logger.set_level(spdlog::level::debug); - logger.warn("this should appear in both console and file"); - logger.info("this message should not appear in the console, only in the file"); -} - -// User defined types logging by implementing operator<< -#include "spdlog/fmt/ostr.h" // must be included -struct my_type -{ - int i; - template - friend OStream &operator<<(OStream &os, const my_type &c) - { - return os << "[my_type i=" << c.i << "]"; - } -}; - -void user_defined_example() -{ - spdlog::info("user defined type: {}", my_type{14}); -} - -// Custom error handler. Will be triggered on log failure. -void err_handler_example() -{ - // can be set globally or per logger(logger->set_error_handler(..)) - spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); }); -} - -// syslog example (linux/osx/freebsd) -#ifndef _WIN32 -#include "spdlog/sinks/syslog_sink.h" -void syslog_example() -{ - std::string ident = "spdlog-example"; - auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID); - syslog_logger->warn("This is warning that will end up in syslog."); -} -#endif - -// Android example. -#if defined(__ANDROID__) -#include "spdlog/sinks/android_sink.h" -void android_example() -{ - std::string tag = "spdlog-android"; - auto android_logger = spdlog::android_logger_mt("android", tag); - android_logger->critical("Use \"adb shell logcat\" to view this message."); -} - -#endif +{ + auto *l = get_logger(); + l->info("HELLO"); +} \ No newline at end of file diff --git a/include/spdlog/details/logger_impl.h b/include/spdlog/details/logger_impl.h index d44652b5..80245ba1 100644 --- a/include/spdlog/details/logger_impl.h +++ b/include/spdlog/details/logger_impl.h @@ -10,426 +10,426 @@ #include #include -#define SPDLOG_CATCH_AND_HANDLE \ - catch (const std::exception &ex) \ - { \ - err_handler_(ex.what()); \ - } \ - catch (...) \ - { \ - err_handler_("Unknown exception in logger"); \ - } +//#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 -inline spdlog::logger::logger(std::string logger_name, It begin, It end) - : name_(std::move(logger_name)) - , sinks_(begin, end) -{ -} +//template +//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 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(std::string logger_name, spdlog::sink_ptr single_sink) +// : logger(std::move(logger_name), {std::move(single_sink)}) +//{ +//} -inline spdlog::logger::~logger() = default; +//inline spdlog::logger::~logger() = default; -inline void spdlog::logger::set_formatter(std::unique_ptr f) -{ - for (auto &sink : sinks_) - { - sink->set_formatter(f->clone()); - } -} +//inline void spdlog::logger::set_formatter(std::unique_ptr 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(std::move(pattern), time_type); - set_formatter(std::move(new_formatter)); -} +//inline void spdlog::logger::set_pattern(std::string pattern, pattern_time_type time_type) +//{ +// auto new_formatter = details::make_unique(std::move(pattern), time_type); +// set_formatter(std::move(new_formatter)); +//} -template -inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const char *fmt, const Args &... args) -{ - if (!should_log(lvl)) - { - return; - } +//template +//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 +//} - 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 +//inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) +//{ +// log(source_loc{}, lvl, fmt, args...); +//} -template -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(source_loc source, level::level_enum lvl, const char *msg) -{ - if (!should_log(lvl)) - { - return; - } +//inline void spdlog::logger::log(level::level_enum lvl, const char *msg) +//{ +// log(source_loc{}, lvl, msg); +//} - try - { - details::log_msg log_msg(source, &name_, lvl, spdlog::string_view_t(msg)); - sink_it_(log_msg); - } - SPDLOG_CATCH_AND_HANDLE -} +//template +//inline void spdlog::logger::log(level::level_enum lvl, const T &msg) +//{ +// log(source_loc{}, lvl, msg); +//} +// +//template::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 +//} -inline void spdlog::logger::log(level::level_enum lvl, const char *msg) -{ - log(source_loc{}, lvl, msg); -} +//template::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 -inline void spdlog::logger::log(level::level_enum lvl, const T &msg) -{ - log(source_loc{}, lvl, msg); -} +//template +//inline void spdlog::logger::trace(const char *fmt, const Args &... args) +//{ +// log(level::trace, fmt, args...); +//} +// +//template +//inline void spdlog::logger::debug(const char *fmt, const Args &... args) +//{ +// log(level::debug, fmt, args...); +//} +// +//template +//inline void spdlog::logger::info(const char *fmt, const Args &... args) +//{ +// log(level::info, fmt, args...); +//} +// +//template +//inline void spdlog::logger::warn(const char *fmt, const Args &... args) +//{ +// log(level::warn, fmt, args...); +//} +// +//template +//inline void spdlog::logger::error(const char *fmt, const Args &... args) +//{ +// log(level::err, fmt, args...); +//} +// +//template +//inline void spdlog::logger::critical(const char *fmt, const Args &... args) +//{ +// log(level::critical, fmt, args...); +//} +// +//template +//inline void spdlog::logger::trace(const T &msg) +//{ +// log(level::trace, msg); +//} +// +//template +//inline void spdlog::logger::debug(const T &msg) +//{ +// log(level::debug, msg); +//} +// +//template +//inline void spdlog::logger::info(const T &msg) +//{ +// log(level::info, msg); +//} +// +//template +//inline void spdlog::logger::warn(const T &msg) +//{ +// log(level::warn, msg); +//} +// +//template +//inline void spdlog::logger::error(const T &msg) +//{ +// log(level::err, msg); +//} +// +//template +//inline void spdlog::logger::critical(const T &msg) +//{ +// log(level::critical, msg); +//} -template::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 -} +//#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT -template::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 -} +//inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target) +//{ +// int wbuf_size = static_cast(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 -inline void spdlog::logger::trace(const char *fmt, const Args &... args) -{ - log(level::trace, fmt, args...); -} +//template +//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 -inline void spdlog::logger::debug(const char *fmt, const Args &... args) -{ - log(level::debug, fmt, args...); -} - -template -inline void spdlog::logger::info(const char *fmt, const Args &... args) -{ - log(level::info, fmt, args...); -} - -template -inline void spdlog::logger::warn(const char *fmt, const Args &... args) -{ - log(level::warn, fmt, args...); -} - -template -inline void spdlog::logger::error(const char *fmt, const Args &... args) -{ - log(level::err, fmt, args...); -} - -template -inline void spdlog::logger::critical(const char *fmt, const Args &... args) -{ - log(level::critical, fmt, args...); -} - -template -inline void spdlog::logger::trace(const T &msg) -{ - log(level::trace, msg); -} - -template -inline void spdlog::logger::debug(const T &msg) -{ - log(level::debug, msg); -} - -template -inline void spdlog::logger::info(const T &msg) -{ - log(level::info, msg); -} - -template -inline void spdlog::logger::warn(const T &msg) -{ - log(level::warn, msg); -} - -template -inline void spdlog::logger::error(const T &msg) -{ - log(level::err, msg); -} - -template -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(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 -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 -inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) -{ - log(source_loc{}, lvl, fmt, args...); -} - -template -inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args) -{ - log(level::trace, fmt, args...); -} - -template -inline void spdlog::logger::debug(const wchar_t *fmt, const Args &... args) -{ - log(level::debug, fmt, args...); -} - -template -inline void spdlog::logger::info(const wchar_t *fmt, const Args &... args) -{ - log(level::info, fmt, args...); -} - -template -inline void spdlog::logger::warn(const wchar_t *fmt, const Args &... args) -{ - log(level::warn, fmt, args...); -} - -template -inline void spdlog::logger::error(const wchar_t *fmt, const Args &... args) -{ - log(level::err, fmt, args...); -} - -template -inline void spdlog::logger::critical(const wchar_t *fmt, const Args &... args) -{ - log(level::critical, fmt, args...); -} - -#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT +//template +//inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) +//{ +// log(source_loc{}, lvl, fmt, args...); +//} +// +//template +//inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args) +//{ +// log(level::trace, fmt, args...); +//} +// +//template +//inline void spdlog::logger::debug(const wchar_t *fmt, const Args &... args) +//{ +// log(level::debug, fmt, args...); +//} +// +//template +//inline void spdlog::logger::info(const wchar_t *fmt, const Args &... args) +//{ +// log(level::info, fmt, args...); +//} +// +//template +//inline void spdlog::logger::warn(const wchar_t *fmt, const Args &... args) +//{ +// log(level::warn, fmt, args...); +//} +// +//template +//inline void spdlog::logger::error(const wchar_t *fmt, const Args &... args) +//{ +// log(level::err, fmt, args...); +//} +// +//template +//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 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_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 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 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() +//{ +// try +// { +// flush_(); +// } +// SPDLOG_CATCH_AND_HANDLE +//} -inline void spdlog::logger::flush_on(level::level_enum log_level) -{ - flush_level_.store(log_level); -} +//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(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::flush_level() const -{ - return static_cast(flush_level_.load(std::memory_order_relaxed)); -} +//inline spdlog::level::level_enum spdlog::logger::default_level() +//{ +// return static_cast(SPDLOG_ACTIVE_LEVEL); +//} -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::level() const +//{ +// return static_cast(level_.load(std::memory_order_relaxed)); +//} -inline spdlog::level::level_enum spdlog::logger::default_level() -{ - return static_cast(SPDLOG_ACTIVE_LEVEL); -} - -inline spdlog::level::level_enum spdlog::logger::level() const -{ - return static_cast(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); -} +//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); - } - } +//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_(); +// } +//} - if (should_flush_(msg)) - { - flush_(); - } -} +//inline void spdlog::logger::flush_() +//{ +// for (auto &sink : sinks_) +// { +// sink->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::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::logger::sinks() const +//{ +// return sinks_; +//} -inline void spdlog::logger::incr_msg_counter_(details::log_msg &msg) -{ - msg.msg_id = msg_counter_.fetch_add(1, std::memory_order_relaxed); -} +//inline std::vector &spdlog::logger::sinks() +//{ +// return sinks_; +//} -inline const std::vector &spdlog::logger::sinks() const -{ - return sinks_; -} - -inline std::vector &spdlog::logger::sinks() -{ - return sinks_; -} - -inline std::shared_ptr spdlog::logger::clone(std::string logger_name) -{ - auto cloned = std::make_shared(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; -} +//inline std::shared_ptr spdlog::logger::clone(std::string logger_name) +//{ +// auto cloned = std::make_shared(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; +//} diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index ec06828f..446a5076 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -21,154 +21,455 @@ #include "spdlog/common.h" #include "spdlog/formatter.h" #include "spdlog/sinks/sink.h" +#include "spdlog/details/fmt_helper.h" #include #include #include +#ifndef SPDLOG_CATCH_AND_HANDLE + +#define SPDLOG_CATCH_AND_HANDLE \ + catch (const std::exception &ex) \ + { \ + err_handler_(ex.what()); \ + } \ + catch (...) \ + { \ + err_handler_("Unknown exception in logger"); \ + } + +#endif // ! SPDLOG_CATCH_AND_HANDLE + + namespace spdlog { class logger { public: - logger(std::string name, sink_ptr single_sink); - logger(std::string name, sinks_init_list sinks); - + template - 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 &operator=(const logger &) = delete; - template - void log(level::level_enum lvl, const char *fmt, const Args &... args); + template + void log(source_loc loc, 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(loc, &name_, lvl, to_string_view(buf)); + sink_it_(log_msg); + } + SPDLOG_CATCH_AND_HANDLE + } template - 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) + { + log(source_loc{}, lvl, fmt, args...); + } - void log(level::level_enum lvl, const char *msg); + + void log(source_loc loc, level::level_enum lvl, const char *msg) + { + if (!should_log(lvl)) + { + return; + } - void log(source_loc loc, level::level_enum lvl, const char *msg); + try + { + details::log_msg log_msg(loc, &name_, lvl, spdlog::string_view_t(msg)); + sink_it_(log_msg); + } + SPDLOG_CATCH_AND_HANDLE + } + + void log(level::level_enum lvl, const char *msg) + { + log(source_loc{}, lvl, msg); + } + + template - void trace(const char *fmt, const Args &... args); + void trace(const char *fmt, const Args &... args) + { + log(level::trace, fmt, args...); + } + template - void debug(const char *fmt, const Args &... args); + void debug(const char *fmt, const Args &... args) + { + log(level::debug, fmt, args...); + } + template - void info(const char *fmt, const Args &... args); + void info(const char *fmt, const Args &... args) + { + log(level::info, fmt, args...); + } template - void warn(const char *fmt, const Args &... args); + void warn(const char *fmt, const Args &... args) + { + log(level::warn, fmt, args...); + } template - void error(const char *fmt, const Args &... args); + void error(const char *fmt, const Args &... args) + { + log(level::err, fmt, args...); + } template - void critical(const char *fmt, const Args &... args); + void critical(const char *fmt, const Args &... args) + { + log(level::critical, fmt, args...); + } + #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT #ifndef _WIN32 #error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows #else - template - void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); + inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target) + { + int wbuf_size = static_cast(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 + 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 + 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 - 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 + void trace(const wchar_t *fmt, const Args &... args) + { + log(level::trace, fmt, args...); + } template - void trace(const wchar_t *fmt, const Args &... args); + void debug(const wchar_t *fmt, const Args &... args) + { + log(level::debug, fmt, args...); + } template - void debug(const wchar_t *fmt, const Args &... args); + void info(const wchar_t *fmt, const Args &... args) + { + log(level::info, fmt, args...); + } template - void info(const wchar_t *fmt, const Args &... args); + void warn(const wchar_t *fmt, const Args &... args) + { + log(level::warn, fmt, args...); + } template - void warn(const wchar_t *fmt, const Args &... args); + void error(const wchar_t *fmt, const Args &... args) + { + log(level::err, fmt, args...); + } template - void error(const wchar_t *fmt, const Args &... args); - - template - 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 // SPDLOG_WCHAR_TO_UTF8_SUPPORT - template - void log(level::level_enum lvl, const T &); + template + void log(level::level_enum lvl, const T &msg) + { + log(source_loc{}, lvl, msg); + } // T can be statically converted to string_view template::value, T>::type * = nullptr> - void log(source_loc loc, level::level_enum lvl, const T &); + 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); + } + SPDLOG_CATCH_AND_HANDLE + } // T cannot be statically converted to string_view template::value, T>::type * = nullptr> - void log(source_loc loc, level::level_enum lvl, const T &); + void log(source_loc loc, 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(loc, &name_, lvl, to_string_view(buf)); + sink_it_(log_msg); + } + SPDLOG_CATCH_AND_HANDLE + } template - void trace(const T &msg); + void trace(const T &msg) + { + log(level::trace, msg); + } template - void debug(const T &msg); + void debug(const T &msg) + { + log(level::debug, msg); + } template - void info(const T &msg); + void info(const T &msg) + { + log(level::info, msg); + } template - void warn(const T &msg); + void warn(const T &msg) + { + log(level::warn, msg); + } template - void error(const T &msg); + void error(const T &msg) + { + log(level::err, msg); + } template - void critical(const T &msg); + void critical(const T &msg) + { + log(level::critical, msg); + } - bool should_log(level::level_enum msg_level) const; - void set_level(level::level_enum log_level); + bool should_log(level::level_enum msg_level) const + { + return msg_level >= level_.load(std::memory_order_relaxed); + } - static level::level_enum default_level(); - level::level_enum level() const; - const std::string &name() const; + void set_level(level::level_enum log_level) + { + level_.store(log_level); + } + + static level::level_enum default_level() + { + return static_cast(SPDLOG_ACTIVE_LEVEL); + } + + level::level_enum level() const + { + return static_cast(level_.load(std::memory_order_relaxed)); + } + + const std::string &name() const + { + return name_; + } // set formatting for the sinks in this logger. // each sink will get a seperate instance of the formatter object. - void set_formatter(std::unique_ptr formatter); - void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local); + void set_formatter(std::unique_ptr f) + { + for (auto &sink : sinks_) + { + sink->set_formatter(f->clone()); + } + } + + void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local) + { + auto new_formatter = details::make_unique(std::move(pattern), time_type); + set_formatter(std::move(new_formatter)); + } // flush functions - void flush(); - void flush_on(level::level_enum log_level); - level::level_enum flush_level() const; + void flush() + { + try + { + flush_(); + } + SPDLOG_CATCH_AND_HANDLE + } + + void flush_on(level::level_enum log_level) + { + flush_level_.store(log_level); + } + + level::level_enum flush_level() const + { + return static_cast(flush_level_.load(std::memory_order_relaxed)); + } // sinks - const std::vector &sinks() const; - std::vector &sinks(); + const std::vector &sinks() const + { + return sinks_; + } + + std::vector &sinks() + { + return sinks_; + } // error handler - void set_error_handler(log_err_handler err_handler); - log_err_handler error_handler() const; + void set_error_handler(log_err_handler err_handler) + { + err_handler_ = std::move(err_handler); + } + + log_err_handler error_handler() const + { + return err_handler_; + } // create new logger with same sinks and configuration. - virtual std::shared_ptr clone(std::string logger_name); + virtual std::shared_ptr clone(std::string logger_name) + { + auto cloned = std::make_shared(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; + } + protected: - virtual void sink_it_(details::log_msg &msg); - virtual void flush_(); + virtual void 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); + } + } - bool should_flush_(const details::log_msg &msg); + if (should_flush_(msg)) + { + flush_(); + } + } + + virtual void flush_() + { + for (auto &sink : sinks_) + { + sink->flush(); + } + } + + bool 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); + } // default error handler. // print the error to stderr with the max rate of 1 message/minute. - void default_err_handler_(const std::string &msg); + void 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); + } // increment the message count (only if defined(SPDLOG_ENABLE_MESSAGE_COUNTER)) - void incr_msg_counter_(details::log_msg &msg); + void incr_msg_counter_(details::log_msg &msg) + { + msg.msg_id = msg_counter_.fetch_add(1, std::memory_order_relaxed); + } const std::string name_; std::vector sinks_; @@ -180,4 +481,3 @@ protected: }; } // namespace spdlog -#include "details/logger_impl.h" From e2e3df9013ca514652d8104fede59a97378cc612 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 5 Apr 2019 16:44:17 +0300 Subject: [PATCH 055/157] static lib wip --- example/example.cpp | 11 +- include/spdlog/common.h | 7 + include/spdlog/details/async_logger_impl.h | 18 +- include/spdlog/details/fmt_helper.h | 1 + include/spdlog/details/log_msg.h | 26 +- include/spdlog/details/logger_impl.h | 435 ------------- include/spdlog/details/os.h | 369 +---------- include/spdlog/details/pattern_formatter.h | 1 - include/spdlog/details/registry.h | 1 + include/spdlog/logger.h | 724 +++++++++------------ include/spdlog/sinks/sink.h | 38 +- src/log_msg.cpp | 29 + src/logger.cpp | 187 ++++++ src/os.cpp | 406 ++++++++++++ src/sink.cpp | 31 + 15 files changed, 1029 insertions(+), 1255 deletions(-) delete mode 100644 include/spdlog/details/logger_impl.h create mode 100644 src/log_msg.cpp create mode 100644 src/logger.cpp create mode 100644 src/os.cpp create mode 100644 src/sink.cpp diff --git a/example/example.cpp b/example/example.cpp index b42c9440..e7d9559d 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -10,16 +10,15 @@ #include "spdlog/logger.h" -namespace spdlog { -class logger; -} spdlog::logger *get_logger(); - - int main(int, char *[]) { auto *l = get_logger(); - l->info("HELLO"); + l->info("HELLO {}", "World"); + l->warn("SOME WARNINNG"); + l->error("Some {}", "error"); + + } \ No newline at end of file diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 71273d30..f76aedea 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -27,6 +27,13 @@ #include "spdlog/fmt/fmt.h" +#ifdef SPDLOG_HEADER_ONLY +#define SPDLOG_INLINE inline +#else +#define SPDLOG_INLINE +#endif + + // visual studio upto 2013 does not support noexcept nor constexpr #if defined(_MSC_VER) && (_MSC_VER < 1900) #define SPDLOG_NOEXCEPT throw() diff --git a/include/spdlog/details/async_logger_impl.h b/include/spdlog/details/async_logger_impl.h index aafcae65..88bd5e7c 100644 --- a/include/spdlog/details/async_logger_impl.h +++ b/include/spdlog/details/async_logger_impl.h @@ -79,7 +79,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)) { @@ -96,7 +103,14 @@ inline void spdlog::async_logger::backend_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::async_logger::clone(std::string new_name) diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index d76aac45..16035555 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -7,6 +7,7 @@ #include #include #include "spdlog/fmt/fmt.h" +#include "spdlog/common.h" // Some fmt helpers to efficiently format and pad ints and strings namespace spdlog { diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 69422ba3..1507eac1 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -6,36 +6,16 @@ #pragma once #include "spdlog/common.h" -#include "spdlog/details/os.h" - #include -#include namespace spdlog { namespace details { struct log_msg { - log_msg(source_loc loc, 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(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); log_msg(const log_msg &other) = default; const std::string *logger_name{nullptr}; diff --git a/include/spdlog/details/logger_impl.h b/include/spdlog/details/logger_impl.h deleted file mode 100644 index 80245ba1..00000000 --- a/include/spdlog/details/logger_impl.h +++ /dev/null @@ -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 -#include - -//#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 -//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 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(std::move(pattern), time_type); -// set_formatter(std::move(new_formatter)); -//} - -//template -//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 -//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 -//inline void spdlog::logger::log(level::level_enum lvl, const T &msg) -//{ -// log(source_loc{}, lvl, msg); -//} -// -//template::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::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 -//inline void spdlog::logger::trace(const char *fmt, const Args &... args) -//{ -// log(level::trace, fmt, args...); -//} -// -//template -//inline void spdlog::logger::debug(const char *fmt, const Args &... args) -//{ -// log(level::debug, fmt, args...); -//} -// -//template -//inline void spdlog::logger::info(const char *fmt, const Args &... args) -//{ -// log(level::info, fmt, args...); -//} -// -//template -//inline void spdlog::logger::warn(const char *fmt, const Args &... args) -//{ -// log(level::warn, fmt, args...); -//} -// -//template -//inline void spdlog::logger::error(const char *fmt, const Args &... args) -//{ -// log(level::err, fmt, args...); -//} -// -//template -//inline void spdlog::logger::critical(const char *fmt, const Args &... args) -//{ -// log(level::critical, fmt, args...); -//} -// -//template -//inline void spdlog::logger::trace(const T &msg) -//{ -// log(level::trace, msg); -//} -// -//template -//inline void spdlog::logger::debug(const T &msg) -//{ -// log(level::debug, msg); -//} -// -//template -//inline void spdlog::logger::info(const T &msg) -//{ -// log(level::info, msg); -//} -// -//template -//inline void spdlog::logger::warn(const T &msg) -//{ -// log(level::warn, msg); -//} -// -//template -//inline void spdlog::logger::error(const T &msg) -//{ -// log(level::err, msg); -//} -// -//template -//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(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 -//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 -//inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) -//{ -// log(source_loc{}, lvl, fmt, args...); -//} -// -//template -//inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args) -//{ -// log(level::trace, fmt, args...); -//} -// -//template -//inline void spdlog::logger::debug(const wchar_t *fmt, const Args &... args) -//{ -// log(level::debug, fmt, args...); -//} -// -//template -//inline void spdlog::logger::info(const wchar_t *fmt, const Args &... args) -//{ -// log(level::info, fmt, args...); -//} -// -//template -//inline void spdlog::logger::warn(const wchar_t *fmt, const Args &... args) -//{ -// log(level::warn, fmt, args...); -//} -// -//template -//inline void spdlog::logger::error(const wchar_t *fmt, const Args &... args) -//{ -// log(level::err, fmt, args...); -//} -// -//template -//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(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_ACTIVE_LEVEL); -//} - -//inline spdlog::level::level_enum spdlog::logger::level() const -//{ -// return static_cast(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::logger::sinks() const -//{ -// return sinks_; -//} - -//inline std::vector &spdlog::logger::sinks() -//{ -// return sinks_; -//} - -//inline std::shared_ptr spdlog::logger::clone(std::string logger_name) -//{ -// auto cloned = std::make_shared(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; -//} diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 646805e6..7b1e5219 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -18,95 +18,19 @@ #include #include -#ifdef _WIN32 - -#ifndef NOMINMAX -#define NOMINMAX // prevent windows redefining min/max -#endif - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include // _get_osfhandle and _isatty support -#include // _get_pid support -#include - -#ifdef __MINGW32__ -#include -#endif - -#else // unix - -#include -#include - -#ifdef __linux__ -#include //Use gettid() syscall under linux to get thread id - -#elif __FreeBSD__ -#include //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 { -inline spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT -{ +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( - std::chrono::duration_cast(std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec))); +std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT; -#else - return log_clock::now(); -#endif -} -inline std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT -{ +std::tm localtime() SPDLOG_NOEXCEPT; -#ifdef _WIN32 - std::tm tm; - localtime_s(&tm, &time_tt); -#else - std::tm tm; - localtime_r(&time_tt, &tm); -#endif - return tm; -} +std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT; -inline std::tm localtime() 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); -} +std::tm gmtime() SPDLOG_NOEXCEPT; // eol definition #if !defined(SPDLOG_EOL) @@ -121,301 +45,56 @@ SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL; // folder separator #ifdef _WIN32 -SPDLOG_CONSTEXPR static const char folder_sep = '\\'; +const char folder_sep = '\\'; #else SPDLOG_CONSTEXPR static const char folder_sep = '/'; #endif -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 -} +void prevent_child_fd(FILE *f); // fopen_s on non windows for writing -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 +bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode); -#ifdef SPDLOG_PREVENT_CHILD_FD - if (*fp != nullptr) - { - prevent_child_fd(*fp); - } -#endif - return *fp == nullptr; -} +int remove(const filename_t &filename) SPDLOG_NOEXCEPT; -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 -} - -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 -} +int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT; // Return if file exists -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 -} +bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT; // Return file size according to open FILE* object -inline size_t filesize(FILE *f) -{ - if (f == nullptr) - { - throw spdlog_ex("Failed getting file size. fd is null"); - } -#if defined(_WIN32) && !defined(__CYGWIN__) - int fd = _fileno(f); -#if _WIN64 // 64 bits - __int64 ret = _filelengthi64(fd); - if (ret >= 0) - { - return static_cast(ret); - } - -#else // windows 32 bits - long ret = _filelength(fd); - if (ret >= 0) - { - return static_cast(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(st.st_size); - } -#else // unix 32 bits or cygwin - struct stat st; - - if (fstat(fd, &st) == 0) - { - return static_cast(st.st_size); - } -#endif -#endif - throw spdlog_ex("Failed getting file size from fd", errno); -} +size_t filesize(FILE *f); // Return utc offset in minutes or throw spdlog_ex on failure -inline 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(offset_seconds / 60); -#endif -} +int utc_minutes_offset(const std::tm &tm = details::os::localtime()); // Return current thread id as size_t // It exists because the std::this_thread::get_id() is much slower(especially // under VS 2013) -inline size_t _thread_id() SPDLOG_NOEXCEPT -{ -#ifdef _WIN32 - return static_cast(::GetCurrentThreadId()); -#elif __linux__ -#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21) -#define SYS_gettid __NR_gettid -#endif - return static_cast(syscall(SYS_gettid)); -#elif __FreeBSD__ - long tid; - thr_self(&tid); - return static_cast(tid); -#elif __APPLE__ - uint64_t tid; - pthread_threadid_np(nullptr, &tid); - return static_cast(tid); -#else // Default to standard C++11 (other Unix) - return static_cast(std::hash()(std::this_thread::get_id())); -#endif -} +size_t _thread_id() SPDLOG_NOEXCEPT; // Return current thread id as size_t (from thread local storage) -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 -} +size_t thread_id() SPDLOG_NOEXCEPT; // This is avoid msvc issue in sleep_for that happens if the clock changes. // See https://github.com/gabime/spdlog/issues/609 -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 -} +void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT; -// wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined) -#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) -#define SPDLOG_FILENAME_T(s) L##s -inline std::string filename_to_str(const filename_t &filename) -{ - std::wstring_convert, 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 +std::string filename_to_str(const filename_t &filename); -inline int pid() -{ - -#ifdef _WIN32 - return static_cast(::GetCurrentProcessId()); -#else - return static_cast(::getpid()); -#endif -} +int pid(); // Determine if the terminal supports colors // Source: https://github.com/agauniyal/rang/ -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 -} +bool is_color_terminal() SPDLOG_NOEXCEPT; // Detrmine if the terminal attached // Source: https://github.com/agauniyal/rang/ -inline bool in_terminal(FILE *file) SPDLOG_NOEXCEPT -{ - -#ifdef _WIN32 - return _isatty(_fileno(file)) != 0; -#else - return isatty(fileno(file)) != 0; -#endif -} +bool in_terminal(FILE *file) SPDLOG_NOEXCEPT; } // namespace os } // namespace details } // namespace spdlog + +#ifdef SPDLOG_HEADER_ONLY +#include "../src/os.cpp" +#endif diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index c0ad86e8..c9532293 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -4,7 +4,6 @@ // #pragma once - #include "spdlog/details/fmt_helper.h" #include "spdlog/details/log_msg.h" #include "spdlog/details/os.h" diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index ccd53955..ab4cf3f8 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -13,6 +13,7 @@ #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 diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 446a5076..f178281d 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -15,469 +15,353 @@ // and send to its destination. // // The use of private formatter per sink provides the opportunity to cache some -// formatted data, -// and support customize format per each sink. +// formatted data, and support for different format per sink. + #include "spdlog/common.h" -#include "spdlog/formatter.h" -#include "spdlog/sinks/sink.h" -#include "spdlog/details/fmt_helper.h" +#include "spdlog/details/log_msg.h" + +//#include "spdlog/formatter.h" +//#include "spdlog/sinks/sink.h" #include #include #include -#ifndef SPDLOG_CATCH_AND_HANDLE - -#define SPDLOG_CATCH_AND_HANDLE \ - catch (const std::exception &ex) \ - { \ - err_handler_(ex.what()); \ - } \ - catch (...) \ - { \ - err_handler_("Unknown exception in logger"); \ - } - -#endif // ! SPDLOG_CATCH_AND_HANDLE - - -namespace spdlog { - -class logger +namespace spdlog { -public: - - template - logger(std::string name, It begin, It end) - : name_(std::move(name)) - , sinks_(begin, end) - {} - - 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 &operator=(const logger &) = delete; - - template - void log(source_loc loc, level::level_enum lvl, const char *fmt, const Args &... args) - { - if (!should_log(lvl)) + class logger + { + public: + template + logger(std::string name, It begin, It end) + : name_(std::move(name)) + , sinks_(begin, end) { - return; } - try + logger(std::string name, sink_ptr single_sink) + : logger(std::move(name), {std::move(single_sink)}) { - using details::fmt_helper::to_string_view; - fmt::memory_buffer buf; - fmt::format_to(buf, fmt, args...); - details::log_msg log_msg(loc, &name_, lvl, to_string_view(buf)); - sink_it_(log_msg); } - SPDLOG_CATCH_AND_HANDLE - } - - template - void log(level::level_enum lvl, const char *fmt, const Args &... args) - { - log(source_loc{}, lvl, fmt, args...); - } - - - void log(source_loc loc, level::level_enum lvl, const char *msg) - { - if (!should_log(lvl)) + logger(std::string name, sinks_init_list sinks) + : logger(std::move(name), sinks.begin(), sinks.end()) { - return; } - try + virtual ~logger() = default; + + logger(const logger &) = delete; + logger &operator=(const logger &) = delete; + + template + void log(source_loc loc, level::level_enum lvl, const char *fmt, const Args &... args) { - details::log_msg log_msg(loc, &name_, lvl, spdlog::string_view_t(msg)); - sink_it_(log_msg); + 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"); + } } - SPDLOG_CATCH_AND_HANDLE - } - void log(level::level_enum lvl, const char *msg) - { - log(source_loc{}, lvl, msg); - } + template + void log(level::level_enum lvl, const char *fmt, const Args &... args) + { + log(source_loc{}, lvl, fmt, args...); + } + void log(source_loc loc, level::level_enum lvl, const char *msg); + void log(level::level_enum lvl, const char *msg); - + template + void trace(const char *fmt, const Args &... args) + { + log(level::trace, fmt, args...); + } - template - void trace(const char *fmt, const Args &... args) - { - log(level::trace, fmt, args...); - } + template + void debug(const char *fmt, const Args &... args) + { + log(level::debug, fmt, args...); + } + template + void info(const char *fmt, const Args &... args) + { + log(level::info, fmt, args...); + } - template - void debug(const char *fmt, const Args &... args) - { - log(level::debug, fmt, args...); - } + template + void warn(const char *fmt, const Args &... args) + { + log(level::warn, fmt, args...); + } + template + void error(const char *fmt, const Args &... args) + { + log(level::err, fmt, args...); + } - template - void info(const char *fmt, const Args &... args) - { - log(level::info, fmt, args...); - } - - template - void warn(const char *fmt, const Args &... args) - { - log(level::warn, fmt, args...); - } - - template - void error(const char *fmt, const Args &... args) - { - log(level::err, fmt, args...); - } - - template - void critical(const char *fmt, const Args &... args) - { - log(level::critical, fmt, args...); - } - + template + void critical(const char *fmt, const Args &... args) + { + log(level::critical, fmt, args...); + } #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT #ifndef _WIN32 #error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows #else - inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target) - { - int wbuf_size = static_cast(wbuf.size()); - if (wbuf_size == 0) + inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target) { - 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 - 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 - 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 - void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) - { - log(source_loc{}, lvl, fmt, args...); - } - - template - void trace(const wchar_t *fmt, const Args &... args) - { - log(level::trace, fmt, args...); - } - - template - void debug(const wchar_t *fmt, const Args &... args) - { - log(level::debug, fmt, args...); - } - - template - void info(const wchar_t *fmt, const Args &... args) - { - log(level::info, fmt, args...); - } - - template - void warn(const wchar_t *fmt, const Args &... args) - { - log(level::warn, fmt, args...); - } - - template - void error(const wchar_t *fmt, const Args &... args) - { - log(level::err, fmt, args...); - } - - template - void critical(const wchar_t *fmt, const Args &... args) - { - log(level::critical, fmt, args...); - } -#endif // _WIN32 -#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT - - template - void log(level::level_enum lvl, const T &msg) - { - log(source_loc{}, lvl, msg); - } - - // T can be statically converted to string_view - template::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); - } - SPDLOG_CATCH_AND_HANDLE - } - - // T cannot be statically converted to string_view - template::value, T>::type * = nullptr> - void log(source_loc loc, 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(loc, &name_, lvl, to_string_view(buf)); - sink_it_(log_msg); - } - SPDLOG_CATCH_AND_HANDLE - } - - template - void trace(const T &msg) - { - log(level::trace, msg); - } - - template - void debug(const T &msg) - { - log(level::debug, msg); - } - - template - void info(const T &msg) - { - log(level::info, msg); - } - - template - void warn(const T &msg) - { - log(level::warn, msg); - } - - template - void error(const T &msg) - { - log(level::err, msg); - } - - template - void critical(const T &msg) - { - log(level::critical, msg); - } - - 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) - { - level_.store(log_level); - } - - static level::level_enum default_level() - { - return static_cast(SPDLOG_ACTIVE_LEVEL); - } - - level::level_enum level() const - { - return static_cast(level_.load(std::memory_order_relaxed)); - } - - const std::string &name() const - { - return name_; - } - - // set formatting for the sinks in this logger. - // each sink will get a seperate instance of the formatter object. - void set_formatter(std::unique_ptr f) - { - for (auto &sink : sinks_) - { - sink->set_formatter(f->clone()); - } - } - - void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local) - { - auto new_formatter = details::make_unique(std::move(pattern), time_type); - set_formatter(std::move(new_formatter)); - } - - // flush functions - void flush() - { - try - { - flush_(); - } - SPDLOG_CATCH_AND_HANDLE - } - - void flush_on(level::level_enum log_level) - { - flush_level_.store(log_level); - } - - level::level_enum flush_level() const - { - return static_cast(flush_level_.load(std::memory_order_relaxed)); - } - - // sinks - const std::vector &sinks() const - { - return sinks_; - } - - std::vector &sinks() - { - return sinks_; - } - - // error handler - void set_error_handler(log_err_handler err_handler) - { - err_handler_ = std::move(err_handler); - } - - log_err_handler error_handler() const - { - return err_handler_; - } - - // create new logger with same sinks and configuration. - virtual std::shared_ptr clone(std::string logger_name) - { - auto cloned = std::make_shared(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; - } - - -protected: - virtual void 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)) + int wbuf_size = static_cast(wbuf.size()); + if (wbuf_size == 0) { - sink->log(msg); + 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())); } } - if (should_flush_(msg)) + template + void log(source_loc source, level::level_enum lvl, const wchar_t *fmt, const Args &... args) { - flush_(); - } - } + if (!should_log(lvl)) + { + return; + } - virtual void flush_() - { - for (auto &sink : sinks_) + 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 + void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) { - sink->flush(); + log(source_loc{}, lvl, fmt, args...); } - } - bool 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); - } - - // default error handler. - // print the error to stderr with the max rate of 1 message/minute. - void default_err_handler_(const std::string &msg) - { - auto now = time(nullptr); - if (now - last_err_time_ < 60) + template + void trace(const wchar_t *fmt, const Args &... args) { - return; + log(level::trace, fmt, args...); } - 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); - } - // increment the message count (only if defined(SPDLOG_ENABLE_MESSAGE_COUNTER)) - void incr_msg_counter_(details::log_msg &msg) - { - msg.msg_id = msg_counter_.fetch_add(1, std::memory_order_relaxed); - } + template + void debug(const wchar_t *fmt, const Args &... args) + { + log(level::debug, fmt, args...); + } - const std::string name_; - std::vector sinks_; - spdlog::level_t level_{spdlog::logger::default_level()}; - spdlog::level_t flush_level_{level::off}; - log_err_handler err_handler_{[this](const std::string &msg) { this->default_err_handler_(msg); }}; - std::atomic last_err_time_{0}; - std::atomic msg_counter_{1}; -}; + template + void info(const wchar_t *fmt, const Args &... args) + { + log(level::info, fmt, args...); + } + + template + void warn(const wchar_t *fmt, const Args &... args) + { + log(level::warn, fmt, args...); + } + + template + void error(const wchar_t *fmt, const Args &... args) + { + log(level::err, fmt, args...); + } + + template + void critical(const wchar_t *fmt, const Args &... args) + { + log(level::critical, fmt, args...); + } +#endif // _WIN32 +#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT + + template + void log(level::level_enum lvl, const T &msg) + { + log(source_loc{}, lvl, msg); + } + + // T can be statically converted to string_view + template::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::value, T>::type * = nullptr> + void log(source_loc loc, 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(loc, &name_, lvl, to_string_view(buf)); + sink_it_(log_msg); + } + catch (const std::exception &ex) + { + err_handler_(ex.what()); + } + catch (...) + { + err_handler_("Unknown exception in logger"); + } + } + + template + void trace(const T &msg) + { + log(level::trace, msg); + } + + template + void debug(const T &msg) + { + log(level::debug, msg); + } + + template + void info(const T &msg) + { + log(level::info, msg); + } + + template + void warn(const T &msg) + { + log(level::warn, msg); + } + + template + void error(const T &msg) + { + log(level::err, msg); + } + + template + void critical(const T &msg) + { + log(level::critical, msg); + } + + bool should_log(level::level_enum msg_level) const; + + void set_level(level::level_enum log_level); + + static level::level_enum default_level(); + + level::level_enum level() const; + + const std::string &name() const; + + // set formatting for the sinks in this logger. + // each sink will get a seperate instance of the formatter object. + void set_formatter(std::unique_ptr f); + + void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local); + + // flush functions + void flush(); + void flush_on(level::level_enum log_level); + level::level_enum flush_level() const; + + // sinks + const std::vector &sinks() const; + + std::vector &sinks(); + + // error handler + void set_error_handler(log_err_handler err_handler); + + log_err_handler error_handler() const; + + // create new logger with same sinks and configuration. + virtual std::shared_ptr clone(std::string logger_name); + + protected: + virtual void sink_it_(details::log_msg &msg); + + virtual void flush_(); + bool should_flush_(const details::log_msg &msg); + + // default error handler. + // print the error to stderr with the max rate of 1 message/minute. + void default_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_; + std::vector sinks_; + spdlog::level_t level_{spdlog::logger::default_level()}; + spdlog::level_t flush_level_{level::off}; + log_err_handler err_handler_{[this](const std::string &msg) { this->default_err_handler_(msg); }}; + std::atomic last_err_time_{0}; + std::atomic msg_counter_{1}; + }; } // namespace spdlog +#ifdef SPDLOG_HEADER_ONLY +#include "../src/logger.cpp" +#endif // SPDLOG_HEADER_ONLY diff --git a/include/spdlog/sinks/sink.h b/include/spdlog/sinks/sink.h index d8325233..11c54fb6 100644 --- a/include/spdlog/sinks/sink.h +++ b/include/spdlog/sinks/sink.h @@ -6,49 +6,41 @@ #pragma once #include "spdlog/details/log_msg.h" -#include "spdlog/details/pattern_formatter.h" +//#include "spdlog/details/pattern_formatter.h" #include "spdlog/formatter.h" namespace spdlog { + namespace sinks { class sink { public: - sink() = default; - - explicit sink(std::unique_ptr formatter) - : formatter_{std::move(formatter)} - { - } + sink(); + explicit sink(std::unique_ptr formatter); virtual ~sink() = default; virtual void log(const details::log_msg &msg) = 0; virtual void flush() = 0; virtual void set_pattern(const std::string &pattern) = 0; virtual void set_formatter(std::unique_ptr sink_formatter) = 0; - 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) - { - level_.store(log_level); - } - - level::level_enum level() const - { - return static_cast(level_.load(std::memory_order_relaxed)); - } + bool should_log(level::level_enum msg_level) const; + + void set_level(level::level_enum log_level); + + level::level_enum level() const; protected: // sink log level - default is all level_t level_{level::trace}; - // sink formatter - default is full format - std::unique_ptr formatter_{details::make_unique()}; + // sink formatter + std::unique_ptr formatter_; }; } // namespace sinks } // namespace spdlog + +#ifdef SPDLOG_HEADER_ONLY +#include "../src/sink.cpp" +#endif // SPDLOG_HEADER_ONLY diff --git a/src/log_msg.cpp b/src/log_msg.cpp new file mode 100644 index 00000000..241bcf5d --- /dev/null +++ b/src/log_msg.cpp @@ -0,0 +1,29 @@ +#include "spdlog/details/os.h" +#include "spdlog/sinks/sink.h" + +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/details/log_msg.h" +#endif + + + +SPDLOG_INLINE spdlog::details::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 spdlog::details::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) +{ +} \ No newline at end of file diff --git a/src/logger.cpp b/src/logger.cpp new file mode 100644 index 00000000..88ff4d3b --- /dev/null +++ b/src/logger.cpp @@ -0,0 +1,187 @@ +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/logger.h" +#endif + +#include "spdlog/sinks/sink.h" +#include "spdlog/details/pattern_formatter.h" + +// public methods +SPDLOG_INLINE void spdlog::logger::log(spdlog::source_loc loc, spdlog::level::level_enum lvl, const char *msg) +{ + if (!should_log(lvl)) + { + return; + } + + try + { + details::log_msg log_msg(loc, &name_, lvl, spdlog::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 spdlog::logger::log(level::level_enum lvl, const char *msg) +{ + log(source_loc{}, lvl, msg); +} + +SPDLOG_INLINE bool spdlog::logger::should_log(spdlog::level::level_enum msg_level) const +{ + return msg_level >= level_.load(std::memory_order_relaxed); +} + +SPDLOG_INLINE void spdlog::logger::set_level(spdlog::level::level_enum log_level) +{ + level_.store(log_level); +} + +SPDLOG_INLINE spdlog::level::level_enum spdlog::logger::default_level() +{ + return static_cast(SPDLOG_ACTIVE_LEVEL); +} + +SPDLOG_INLINE spdlog::level::level_enum spdlog::logger::level() const +{ + return static_cast(level_.load(std::memory_order_relaxed)); +} + +SPDLOG_INLINE const std::string &spdlog::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 spdlog::logger::set_formatter(std::unique_ptr f) +{ + for (auto &sink : sinks_) + { + sink->set_formatter(f->clone()); + } +} + +SPDLOG_INLINE void spdlog::logger::set_pattern(std::string pattern, spdlog::pattern_time_type time_type) +{ + auto new_formatter = details::make_unique(std::move(pattern), time_type); + set_formatter(std::move(new_formatter)); +} + +// flush functions +SPDLOG_INLINE void spdlog::logger::flush() +{ + try + { + flush_(); + } + catch (const std::exception &ex) + { + err_handler_(ex.what()); + } + catch (...) + { + err_handler_("Unknown exception in logger"); + } +} + +SPDLOG_INLINE void spdlog::logger::flush_on(level::level_enum log_level) +{ + flush_level_.store(log_level); +} + +SPDLOG_INLINE spdlog::level::level_enum spdlog::logger::flush_level() const +{ + return static_cast(flush_level_.load(std::memory_order_relaxed)); +} + +// sinks +SPDLOG_INLINE const std::vector &spdlog::logger::sinks() const +{ + return sinks_; +} + +SPDLOG_INLINE std::vector &spdlog::logger::sinks() +{ + return sinks_; +} + +// error handler +SPDLOG_INLINE void spdlog::logger::set_error_handler(spdlog::log_err_handler err_handler) +{ + err_handler_ = std::move(err_handler); +} + +SPDLOG_INLINE spdlog::log_err_handler spdlog::logger::error_handler() const +{ + return err_handler_; +} + +// create new logger with same sinks and configuration. +SPDLOG_INLINE std::shared_ptr spdlog::logger::clone(std::string logger_name) +{ + auto cloned = std::make_shared(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; +} + +// protected methods +SPDLOG_INLINE void spdlog::logger::sink_it_(spdlog::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_(); + } +} + +SPDLOG_INLINE void spdlog::logger::flush_() +{ + for (auto &sink : sinks_) + { + sink->flush(); + } +} + +SPDLOG_INLINE bool spdlog::logger::should_flush_(const spdlog::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 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); +} + +SPDLOG_INLINE void spdlog::logger::incr_msg_counter_(spdlog::details::log_msg &msg) +{ + msg.msg_id = msg_counter_.fetch_add(1, std::memory_order_relaxed); +} diff --git a/src/os.cpp b/src/os.cpp new file mode 100644 index 00000000..4a8248f0 --- /dev/null +++ b/src/os.cpp @@ -0,0 +1,406 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// +#pragma once + +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/details/os.h" +#include "spdlog/common.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 + +#ifndef NOMINMAX +#define NOMINMAX // prevent windows redefining min/max +#endif + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include // _get_osfhandle and _isatty support +#include // _get_pid support +#include + +#ifdef __MINGW32__ +#include +#endif + +#else // unix + +#include +#include + +#ifdef __linux__ +#include //Use gettid() syscall under linux to get thread id + +#elif __FreeBSD__ +#include //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( + std::chrono::duration_cast(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(ret); + } + +#else // windows 32 bits + long ret = _filelength(fd); + if (ret >= 0) + { + return static_cast(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(st.st_size); + } +#else // unix 32 bits or cygwin + struct stat st; + + if (fstat(fd, &st) == 0) + { + return static_cast(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(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(::GetCurrentThreadId()); +#elif __linux__ +#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21) +#define SYS_gettid __NR_gettid +#endif + return static_cast(syscall(SYS_gettid)); +#elif __FreeBSD__ + long tid; + thr_self(&tid); + return static_cast(tid); +#elif __APPLE__ + uint64_t tid; + pthread_threadid_np(nullptr, &tid); + return static_cast(tid); +#else // Default to standard C++11 (other Unix) + return static_cast(std::hash()(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) +#define SPDLOG_FILENAME_T(s) L##s +SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) +{ + std::wstring_convert, wchar_t> c; + return c.to_bytes(filename); +} +#else +#define SPDLOG_FILENAME_T(s) s +SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) +{ + return filename; +} +#endif + +SPDLOG_INLINE int pid() +{ + +#ifdef _WIN32 + return static_cast(::GetCurrentProcessId()); +#else + return static_cast(::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 +} +} // namespace os +} // namespace details +} // namespace spdlog diff --git a/src/sink.cpp b/src/sink.cpp new file mode 100644 index 00000000..0d308748 --- /dev/null +++ b/src/sink.cpp @@ -0,0 +1,31 @@ +#include "spdlog/common.h" +#include "spdlog/details/pattern_formatter.h" + +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/sinks/sink.h" +#endif + +SPDLOG_INLINE spdlog::sinks::sink::sink() + : formatter_{details::make_unique()} +{} + +SPDLOG_INLINE spdlog::sinks::sink::sink(std::unique_ptr 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(level_.load(std::memory_order_relaxed)); +} + + From 156b856a809c7f8c80b1129a09730c48720dc1d7 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 5 Apr 2019 16:57:49 +0300 Subject: [PATCH 056/157] static lib wip --- example/example.cpp | 5 +---- include/spdlog/details/log_msg.h | 1 - include/spdlog/details/os.h | 14 +------------- include/spdlog/details/pattern_formatter.h | 4 ++++ 4 files changed, 6 insertions(+), 18 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index e7d9559d..a97c3507 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -9,15 +9,12 @@ #include "spdlog/logger.h" - - spdlog::logger *get_logger(); int main(int, char *[]) { auto *l = get_logger(); - l->info("HELLO {}", "World"); - l->warn("SOME WARNINNG"); + l->info("HELLO {}", "GA"); l->error("Some {}", "error"); diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 1507eac1..5d6f7ad1 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -12,7 +12,6 @@ namespace spdlog { namespace details { struct log_msg { - 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); diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 7b1e5219..d923b30f 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -4,19 +4,7 @@ // #pragma once -#include "../common.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "spdlog/common.h" namespace spdlog { namespace details { diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index c9532293..3c38e762 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -1333,3 +1333,7 @@ private: } }; } // namespace spdlog + +#ifdef SPDLOG_HEADER_ONLY +#include "../src/os.cpp" +#endif From 17f9cdd401d6eeb9a6d093b41e39391538ba3919 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 5 Apr 2019 23:05:46 +0300 Subject: [PATCH 057/157] static lib wip --- example/example.cpp | 5 +- include/spdlog/common.h | 18 +- include/spdlog/details/async_logger_impl.h | 5 +- include/spdlog/details/pattern_formatter.h | 1272 +------------------- include/spdlog/details/registry.h | 4 +- include/spdlog/logger.h | 243 ++-- include/spdlog/spdlog.h | 4 +- include/spdlog/tweakme.h | 7 - src/logger.cpp | 42 +- src/os.cpp | 2 - src/pattern_formatter.cpp | 1266 +++++++++++++++++++ tests/includes.h | 1 - tests/test_errors.cpp | 28 +- tests/test_misc.cpp | 22 +- 14 files changed, 1455 insertions(+), 1464 deletions(-) create mode 100644 src/pattern_formatter.cpp diff --git a/example/example.cpp b/example/example.cpp index a97c3507..918d19b1 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -14,8 +14,9 @@ spdlog::logger *get_logger(); int main(int, char *[]) { auto *l = get_logger(); - l->info("HELLO {}", "GA"); - l->error("Some {}", "error"); + l->info("HE LO ", "GA"); + l->error("Some {} {} {}", "er or"); + l->error("Some {} {} {}", "er or"); } \ No newline at end of file diff --git a/include/spdlog/common.h b/include/spdlog/common.h index f76aedea..275ea23b 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -9,22 +9,16 @@ #include #include -#include #include #include #include #include -#include -#include -#include #if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) #include #include #endif -#include "spdlog/details/null_mutex.h" - #include "spdlog/fmt/fmt.h" #ifdef SPDLOG_HEADER_ONLY @@ -75,6 +69,17 @@ #define SPDLOG_FUNCTION __FUNCTION__ #endif +#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) +#define SPDLOG_FILENAME_T(s) L##s +SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) +{ + std::wstring_convert, wchar_t> c; + return c.to_bytes(filename); +} +#else +#define SPDLOG_FILENAME_T(s) s +#endif + namespace spdlog { class formatter; @@ -86,7 +91,6 @@ class sink; using log_clock = std::chrono::system_clock; using sink_ptr = std::shared_ptr; using sinks_init_list = std::initializer_list; -using log_err_handler = std::function; // string_view type - either std::string_view or fmt::string_view (pre c++17) #if defined(FMT_USE_STD_STRING_VIEW) diff --git a/include/spdlog/details/async_logger_impl.h b/include/spdlog/details/async_logger_impl.h index 88bd5e7c..d3676960 100644 --- a/include/spdlog/details/async_logger_impl.h +++ b/include/spdlog/details/async_logger_impl.h @@ -38,9 +38,6 @@ inline spdlog::async_logger::async_logger( // send the log message to the thread pool 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()) { pool_ptr->post_log(shared_from_this(), msg, overflow_policy_); @@ -119,6 +116,6 @@ inline std::shared_ptr spdlog::async_logger::clone(std::string n cloned->set_level(this->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); } diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 3c38e762..3388743d 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -4,26 +4,23 @@ // #pragma once -#include "spdlog/details/fmt_helper.h" +#include "spdlog/common.h" #include "spdlog/details/log_msg.h" #include "spdlog/details/os.h" #include "spdlog/fmt/fmt.h" #include "spdlog/formatter.h" -#include #include #include -#include #include -#include + #include -#include -#include #include namespace spdlog { namespace details { + // padding information. struct padding_info { @@ -49,64 +46,6 @@ struct padding_info const pad_side side_ = left; }; -class scoped_pad -{ -public: - scoped_pad(size_t wrapped_size, padding_info &padinfo, fmt::memory_buffer &dest) - : padinfo_(padinfo) - , dest_(dest) - { - - if (padinfo_.width_ <= wrapped_size) - { - total_pad_ = 0; - return; - } - - total_pad_ = padinfo.width_ - wrapped_size; - if (padinfo_.side_ == padding_info::left) - { - pad_it(total_pad_); - total_pad_ = 0; - } - else if (padinfo_.side_ == padding_info::center) - { - auto half_pad = total_pad_ / 2; - auto reminder = total_pad_ & 1; - pad_it(half_pad); - total_pad_ = half_pad + reminder; // for the right side - } - } - - scoped_pad(spdlog::string_view_t txt, padding_info &padinfo, fmt::memory_buffer &dest) - : scoped_pad(txt.size(), padinfo, dest) - { - } - - ~scoped_pad() - { - if (total_pad_) - { - pad_it(total_pad_); - } - } - -private: - void pad_it(size_t count) - { - // count = std::min(count, spaces_.size()); - assert(count <= spaces_.size()); - fmt_helper::append_string_view(string_view_t(spaces_.data(), count), dest_); - } - - const padding_info &padinfo_; - fmt::memory_buffer &dest_; - size_t total_pad_; - string_view_t spaces_{" " - " ", - 128}; -}; - class flag_formatter { public: @@ -122,944 +61,26 @@ protected: padding_info padinfo_; }; -/////////////////////////////////////////////////////////////////////// -// name & level pattern appender -/////////////////////////////////////////////////////////////////////// -class name_formatter : public flag_formatter -{ -public: - explicit name_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - if (padinfo_.enabled()) - { - scoped_pad p(*msg.logger_name, padinfo_, dest); - fmt_helper::append_string_view(*msg.logger_name, dest); - } - else - { - fmt_helper::append_string_view(*msg.logger_name, dest); - } - } -}; - -// log level appender -class level_formatter : public flag_formatter -{ -public: - explicit level_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - string_view_t &level_name = level::to_string_view(msg.level); - if (padinfo_.enabled()) - { - scoped_pad p(level_name, padinfo_, dest); - fmt_helper::append_string_view(level_name, dest); - } - else - { - fmt_helper::append_string_view(level_name, dest); - } - } -}; - -// short log level appender -class short_level_formatter : public flag_formatter -{ -public: - explicit short_level_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - string_view_t level_name{level::to_short_c_str(msg.level)}; - scoped_pad p(level_name, padinfo_, dest); - fmt_helper::append_string_view(level_name, dest); - } -}; - -/////////////////////////////////////////////////////////////////////// -// Date time pattern appenders -/////////////////////////////////////////////////////////////////////// - -static const char *ampm(const tm &t) -{ - return t.tm_hour >= 12 ? "PM" : "AM"; } -static int to12h(const tm &t) -{ - return t.tm_hour > 12 ? t.tm_hour - 12 : t.tm_hour; -} - -// Abbreviated weekday name -static const char *days[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; -class a_formatter : public flag_formatter -{ -public: - explicit a_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - string_view_t field_value{days[tm_time.tm_wday]}; - scoped_pad p(field_value, padinfo_, dest); - fmt_helper::append_string_view(field_value, dest); - } -}; - -// Full weekday name -static const char *full_days[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; -class A_formatter : public flag_formatter -{ -public: - explicit A_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - string_view_t field_value{full_days[tm_time.tm_wday]}; - scoped_pad p(field_value, padinfo_, dest); - fmt_helper::append_string_view(field_value, dest); - } -}; - -// Abbreviated month -static const char *months[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"}; -class b_formatter : public flag_formatter -{ -public: - explicit b_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - string_view_t field_value{months[tm_time.tm_mon]}; - scoped_pad p(field_value, padinfo_, dest); - fmt_helper::append_string_view(field_value, dest); - } -}; - -// Full month name -static const char *full_months[]{ - "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; -class B_formatter : public flag_formatter -{ -public: - explicit B_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - string_view_t field_value{full_months[tm_time.tm_mon]}; - scoped_pad p(field_value, padinfo_, dest); - fmt_helper::append_string_view(field_value, dest); - } -}; - -// Date and time representation (Thu Aug 23 15:35:46 2014) -class c_formatter final : public flag_formatter -{ -public: - explicit c_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 24; - scoped_pad p(field_size, padinfo_, dest); - - fmt_helper::append_string_view(days[tm_time.tm_wday], dest); - dest.push_back(' '); - fmt_helper::append_string_view(months[tm_time.tm_mon], dest); - dest.push_back(' '); - fmt_helper::append_int(tm_time.tm_mday, dest); - dest.push_back(' '); - // time - - fmt_helper::pad2(tm_time.tm_hour, dest); - dest.push_back(':'); - fmt_helper::pad2(tm_time.tm_min, dest); - dest.push_back(':'); - fmt_helper::pad2(tm_time.tm_sec, dest); - dest.push_back(' '); - fmt_helper::append_int(tm_time.tm_year + 1900, dest); - } -}; - -// year - 2 digit -class C_formatter final : public flag_formatter -{ -public: - explicit C_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 2; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad2(tm_time.tm_year % 100, dest); - } -}; - -// Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01 -class D_formatter final : public flag_formatter -{ -public: - explicit D_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 10; - scoped_pad p(field_size, padinfo_, dest); - - fmt_helper::pad2(tm_time.tm_mon + 1, dest); - dest.push_back('/'); - fmt_helper::pad2(tm_time.tm_mday, dest); - dest.push_back('/'); - fmt_helper::pad2(tm_time.tm_year % 100, dest); - } -}; - -// year - 4 digit -class Y_formatter final : public flag_formatter -{ -public: - explicit Y_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 4; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::append_int(tm_time.tm_year + 1900, dest); - } -}; - -// month 1-12 -class m_formatter final : public flag_formatter -{ -public: - explicit m_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 2; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad2(tm_time.tm_mon + 1, dest); - } -}; - -// day of month 1-31 -class d_formatter final : public flag_formatter -{ -public: - explicit d_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 2; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad2(tm_time.tm_mday, dest); - } -}; - -// hours in 24 format 0-23 -class H_formatter final : public flag_formatter -{ -public: - explicit H_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 2; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad2(tm_time.tm_hour, dest); - } -}; - -// hours in 12 format 1-12 -class I_formatter final : public flag_formatter -{ -public: - explicit I_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 2; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad2(to12h(tm_time), dest); - } -}; - -// minutes 0-59 -class M_formatter final : public flag_formatter -{ -public: - explicit M_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 2; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad2(tm_time.tm_min, dest); - } -}; - -// seconds 0-59 -class S_formatter final : public flag_formatter -{ -public: - explicit S_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 2; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad2(tm_time.tm_sec, dest); - } -}; - -// milliseconds -class e_formatter final : public flag_formatter -{ -public: - explicit e_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - auto millis = fmt_helper::time_fraction(msg.time); - if (padinfo_.enabled()) - { - const size_t field_size = 3; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad3(static_cast(millis.count()), dest); - } - else - { - fmt_helper::pad3(static_cast(millis.count()), dest); - } - } -}; - -// microseconds -class f_formatter final : public flag_formatter -{ -public: - explicit f_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - auto micros = fmt_helper::time_fraction(msg.time); - if (padinfo_.enabled()) - { - const size_t field_size = 6; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad6(static_cast(micros.count()), dest); - } - else - { - fmt_helper::pad6(static_cast(micros.count()), dest); - } - } -}; - -// nanoseconds -class F_formatter final : public flag_formatter -{ -public: - explicit F_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - auto ns = fmt_helper::time_fraction(msg.time); - if (padinfo_.enabled()) - { - const size_t field_size = 9; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad9(static_cast(ns.count()), dest); - } - else - { - fmt_helper::pad9(static_cast(ns.count()), dest); - } - } -}; - -// seconds since epoch -class E_formatter final : public flag_formatter -{ -public: - explicit E_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - const size_t field_size = 10; - scoped_pad p(field_size, padinfo_, dest); - auto duration = msg.time.time_since_epoch(); - auto seconds = std::chrono::duration_cast(duration).count(); - fmt_helper::append_int(seconds, dest); - } -}; - -// AM/PM -class p_formatter final : public flag_formatter -{ -public: - explicit p_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 2; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::append_string_view(ampm(tm_time), dest); - } -}; - -// 12 hour clock 02:55:02 pm -class r_formatter final : public flag_formatter -{ -public: - explicit r_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 11; - scoped_pad p(field_size, padinfo_, dest); - - fmt_helper::pad2(to12h(tm_time), dest); - dest.push_back(':'); - fmt_helper::pad2(tm_time.tm_min, dest); - dest.push_back(':'); - fmt_helper::pad2(tm_time.tm_sec, dest); - dest.push_back(' '); - fmt_helper::append_string_view(ampm(tm_time), dest); - } -}; - -// 24-hour HH:MM time, equivalent to %H:%M -class R_formatter final : public flag_formatter -{ -public: - explicit R_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 5; - scoped_pad p(field_size, padinfo_, dest); - - fmt_helper::pad2(tm_time.tm_hour, dest); - dest.push_back(':'); - fmt_helper::pad2(tm_time.tm_min, dest); - } -}; - -// ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S -class T_formatter final : public flag_formatter -{ -public: - explicit T_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 8; - scoped_pad p(field_size, padinfo_, dest); - - fmt_helper::pad2(tm_time.tm_hour, dest); - dest.push_back(':'); - fmt_helper::pad2(tm_time.tm_min, dest); - dest.push_back(':'); - fmt_helper::pad2(tm_time.tm_sec, dest); - } -}; - -// ISO 8601 offset from UTC in timezone (+-HH:MM) -class z_formatter final : public flag_formatter -{ -public: - explicit z_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - const std::chrono::seconds cache_refresh = std::chrono::seconds(5); - - z_formatter() = default; - z_formatter(const z_formatter &) = delete; - z_formatter &operator=(const z_formatter &) = delete; - - void format(const details::log_msg &msg, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - const size_t field_size = 6; - scoped_pad p(field_size, padinfo_, dest); - -#ifdef _WIN32 - int total_minutes = get_cached_offset(msg, tm_time); -#else - // No need to chache under gcc, - // it is very fast (already stored in tm.tm_gmtoff) - (void)(msg); - int total_minutes = os::utc_minutes_offset(tm_time); -#endif - bool is_negative = total_minutes < 0; - if (is_negative) - { - total_minutes = -total_minutes; - dest.push_back('-'); - } - else - { - dest.push_back('+'); - } - - fmt_helper::pad2(total_minutes / 60, dest); // hours - dest.push_back(':'); - fmt_helper::pad2(total_minutes % 60, dest); // minutes - } - -private: - log_clock::time_point last_update_{std::chrono::seconds(0)}; -#ifdef _WIN32 - int offset_minutes_{0}; - - int get_cached_offset(const log_msg &msg, const std::tm &tm_time) - { - if (msg.time - last_update_ >= cache_refresh) - { - offset_minutes_ = os::utc_minutes_offset(tm_time); - last_update_ = msg.time; - } - return offset_minutes_; - } -#endif -}; - -// Thread id -class t_formatter final : public flag_formatter -{ -public: - explicit t_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - if (padinfo_.enabled()) - { - const auto field_size = fmt_helper::count_digits(msg.thread_id); - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::append_int(msg.thread_id, dest); - } - else - { - fmt_helper::append_int(msg.thread_id, dest); - } - } -}; - -// Current pid -class pid_formatter final : public flag_formatter -{ -public: - explicit pid_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override - { - const auto pid = static_cast(details::os::pid()); - if (padinfo_.enabled()) - { - auto field_size = fmt_helper::count_digits(pid); - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::append_int(pid, dest); - } - else - { - fmt_helper::append_int(pid, dest); - } - } -}; - -// message counter formatter -class i_formatter final : public flag_formatter -{ -public: - explicit i_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - const size_t field_size = 6; - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad6(msg.msg_id, dest); - } -}; - -class v_formatter final : public flag_formatter -{ -public: - explicit v_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - if (padinfo_.enabled()) - { - scoped_pad p(msg.payload, padinfo_, dest); - fmt_helper::append_string_view(msg.payload, dest); - } - else - { - fmt_helper::append_string_view(msg.payload, dest); - } - } -}; - -class ch_formatter final : public flag_formatter -{ -public: - explicit ch_formatter(char ch) - : ch_(ch) - { - } - - void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override - { - const size_t field_size = 1; - scoped_pad p(field_size, padinfo_, dest); - dest.push_back(ch_); - } - -private: - char ch_; -}; - -// aggregate user chars to display as is -class aggregate_formatter final : public flag_formatter -{ -public: - aggregate_formatter() = default; - - void add_ch(char ch) - { - str_ += ch; - } - void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override - { - fmt_helper::append_string_view(str_, dest); - } - -private: - std::string str_; -}; - -// mark the color range. expect it to be in the form of "%^colored text%$" -class color_start_formatter final : public flag_formatter -{ -public: - explicit color_start_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - msg.color_range_start = dest.size(); - } -}; -class color_stop_formatter final : public flag_formatter -{ -public: - explicit color_stop_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - msg.color_range_end = dest.size(); - } -}; - -// print source location -class source_location_formatter final : public flag_formatter -{ -public: - explicit source_location_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - if (msg.source.empty()) - { - return; - } - if (padinfo_.enabled()) - { - const auto text_size = std::char_traits::length(msg.source.filename) + fmt_helper::count_digits(msg.source.line) + 1; - scoped_pad p(text_size, padinfo_, dest); - fmt_helper::append_string_view(msg.source.filename, dest); - dest.push_back(':'); - fmt_helper::append_int(msg.source.line, dest); - } - else - { - fmt_helper::append_string_view(msg.source.filename, dest); - dest.push_back(':'); - fmt_helper::append_int(msg.source.line, dest); - } - } -}; -// print source filename -class source_filename_formatter final : public flag_formatter -{ -public: - explicit source_filename_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - if (msg.source.empty()) - { - return; - } - scoped_pad p(msg.source.filename, padinfo_, dest); - fmt_helper::append_string_view(msg.source.filename, dest); - } -}; - -class source_linenum_formatter final : public flag_formatter -{ -public: - explicit source_linenum_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - if (msg.source.empty()) - { - return; - } - if (padinfo_.enabled()) - { - auto field_size = fmt_helper::count_digits(msg.source.line); - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::append_int(msg.source.line, dest); - } - else - { - fmt_helper::append_int(msg.source.line, dest); - } - } -}; -// print source funcname -class source_funcname_formatter final : public flag_formatter -{ -public: - explicit source_funcname_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; - - void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override - { - if (msg.source.empty()) - { - return; - } - scoped_pad p(msg.source.funcname, padinfo_, dest); - fmt_helper::append_string_view(msg.source.funcname, dest); - } -}; - -// Full info formatter -// pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v -class full_formatter final : public flag_formatter -{ -public: - explicit full_formatter(padding_info padinfo) - : flag_formatter(padinfo) - { - } - - void format(const details::log_msg &msg, const std::tm &tm_time, fmt::memory_buffer &dest) override - { - using std::chrono::duration_cast; - using std::chrono::milliseconds; - using std::chrono::seconds; - -#ifndef SPDLOG_NO_DATETIME - - // cache the date/time part for the next second. - auto duration = msg.time.time_since_epoch(); - auto secs = duration_cast(duration); - - if (cache_timestamp_ != secs || cached_datetime_.size() == 0) - { - cached_datetime_.clear(); - cached_datetime_.push_back('['); - fmt_helper::append_int(tm_time.tm_year + 1900, cached_datetime_); - cached_datetime_.push_back('-'); - - fmt_helper::pad2(tm_time.tm_mon + 1, cached_datetime_); - cached_datetime_.push_back('-'); - - fmt_helper::pad2(tm_time.tm_mday, cached_datetime_); - cached_datetime_.push_back(' '); - - fmt_helper::pad2(tm_time.tm_hour, cached_datetime_); - cached_datetime_.push_back(':'); - - fmt_helper::pad2(tm_time.tm_min, cached_datetime_); - cached_datetime_.push_back(':'); - - fmt_helper::pad2(tm_time.tm_sec, cached_datetime_); - cached_datetime_.push_back('.'); - - cache_timestamp_ = secs; - } - fmt_helper::append_buf(cached_datetime_, dest); - - auto millis = fmt_helper::time_fraction(msg.time); - fmt_helper::pad3(static_cast(millis.count()), dest); - dest.push_back(']'); - dest.push_back(' '); - -#else // no datetime needed - (void)tm_time; -#endif - -#ifndef SPDLOG_NO_NAME - if (!msg.logger_name->empty()) - { - dest.push_back('['); - // fmt_helper::append_str(*msg.logger_name, dest); - fmt_helper::append_string_view(*msg.logger_name, dest); - dest.push_back(']'); - dest.push_back(' '); - } -#endif - - dest.push_back('['); - // wrap the level name with color - msg.color_range_start = dest.size(); - // fmt_helper::append_string_view(level::to_c_str(msg.level), dest); - fmt_helper::append_string_view(level::to_string_view(msg.level), dest); - msg.color_range_end = dest.size(); - dest.push_back(']'); - dest.push_back(' '); - - // add source location if present - if (!msg.source.empty()) - { - dest.push_back('['); - fmt_helper::append_string_view(msg.source.filename, dest); - dest.push_back(':'); - fmt_helper::append_int(msg.source.line, dest); - dest.push_back(']'); - dest.push_back(' '); - } - // fmt_helper::append_string_view(msg.msg(), dest); - fmt_helper::append_string_view(msg.payload, dest); - } - -private: - std::chrono::seconds cache_timestamp_{0}; - fmt::basic_memory_buffer cached_datetime_; -}; - -} // namespace details - class pattern_formatter final : public formatter { public: explicit pattern_formatter( - std::string pattern, pattern_time_type time_type = pattern_time_type::local, std::string eol = spdlog::details::os::default_eol) - : pattern_(std::move(pattern)) - , eol_(std::move(eol)) - , pattern_time_type_(time_type) - , last_log_secs_(0) - { - std::memset(&cached_tm_, 0, sizeof(cached_tm_)); - compile_pattern_(pattern_); - } - - // use by default full formatter for if pattern is not given - explicit pattern_formatter(pattern_time_type time_type = pattern_time_type::local, std::string eol = spdlog::details::os::default_eol) - : pattern_("%+") - , eol_(std::move(eol)) - , pattern_time_type_(time_type) - , last_log_secs_(0) - { - std::memset(&cached_tm_, 0, sizeof(cached_tm_)); - formatters_.push_back(details::make_unique(details::padding_info{})); - } + std::string pattern, + pattern_time_type time_type = pattern_time_type::local, + std::string eol = spdlog::details::os::default_eol); + + // use default pattern is not given + explicit pattern_formatter( + pattern_time_type time_type = pattern_time_type::local, + std::string eol = spdlog::details::os::default_eol); pattern_formatter(const pattern_formatter &other) = delete; pattern_formatter &operator=(const pattern_formatter &other) = delete; - std::unique_ptr clone() const override - { - return details::make_unique(pattern_, pattern_time_type_, eol_); - } - - void format(const details::log_msg &msg, fmt::memory_buffer &dest) override - { -#ifndef SPDLOG_NO_DATETIME - auto secs = std::chrono::duration_cast(msg.time.time_since_epoch()); - if (secs != last_log_secs_) - { - cached_tm_ = get_time_(msg); - last_log_secs_ = secs; - } -#endif - for (auto &f : formatters_) - { - f->format(msg, cached_tm_, dest); - } - // write eol - details::fmt_helper::append_string_view(eol_, dest); - } + std::unique_ptr clone() const override; + void format(const details::log_msg &msg, fmt::memory_buffer &dest) override; private: std::string pattern_; @@ -1067,273 +88,20 @@ private: pattern_time_type pattern_time_type_; std::tm cached_tm_; std::chrono::seconds last_log_secs_; - std::vector> formatters_; + std::tm get_time_(const details::log_msg &msg); - std::tm get_time_(const details::log_msg &msg) - { - if (pattern_time_type_ == pattern_time_type::local) - { - return details::os::localtime(log_clock::to_time_t(msg.time)); - } - return details::os::gmtime(log_clock::to_time_t(msg.time)); - } - - void handle_flag_(char flag, details::padding_info padding) - { - switch (flag) - { - - case ('+'): // default formatter - formatters_.push_back(details::make_unique(padding)); - break; - - case 'n': // logger name - formatters_.push_back(details::make_unique(padding)); - break; - - case 'l': // level - formatters_.push_back(details::make_unique(padding)); - break; - - case 'L': // short level - formatters_.push_back(details::make_unique(padding)); - break; - - case ('t'): // thread id - formatters_.push_back(details::make_unique(padding)); - break; - - case ('v'): // the message text - formatters_.push_back(details::make_unique(padding)); - break; - - case ('a'): // weekday - formatters_.push_back(details::make_unique(padding)); - break; - - case ('A'): // short weekday - formatters_.push_back(details::make_unique(padding)); - break; - - case ('b'): - case ('h'): // month - formatters_.push_back(details::make_unique(padding)); - break; - - case ('B'): // short month - formatters_.push_back(details::make_unique(padding)); - break; - - case ('c'): // datetime - formatters_.push_back(details::make_unique(padding)); - break; - - case ('C'): // year 2 digits - formatters_.push_back(details::make_unique(padding)); - break; - - case ('Y'): // year 4 digits - formatters_.push_back(details::make_unique(padding)); - break; - - case ('D'): - case ('x'): // datetime MM/DD/YY - formatters_.push_back(details::make_unique(padding)); - break; - - case ('m'): // month 1-12 - formatters_.push_back(details::make_unique(padding)); - break; - - case ('d'): // day of month 1-31 - formatters_.push_back(details::make_unique(padding)); - break; - - case ('H'): // hours 24 - formatters_.push_back(details::make_unique(padding)); - break; - - case ('I'): // hours 12 - formatters_.push_back(details::make_unique(padding)); - break; - - case ('M'): // minutes - formatters_.push_back(details::make_unique(padding)); - break; - - case ('S'): // seconds - formatters_.push_back(details::make_unique(padding)); - break; - - case ('e'): // milliseconds - formatters_.push_back(details::make_unique(padding)); - break; - - case ('f'): // microseconds - formatters_.push_back(details::make_unique(padding)); - break; - - case ('F'): // nanoseconds - formatters_.push_back(details::make_unique(padding)); - break; - - case ('E'): // seconds since epoch - formatters_.push_back(details::make_unique(padding)); - break; - - case ('p'): // am/pm - formatters_.push_back(details::make_unique(padding)); - break; - - case ('r'): // 12 hour clock 02:55:02 pm - formatters_.push_back(details::make_unique(padding)); - break; - - case ('R'): // 24-hour HH:MM time - formatters_.push_back(details::make_unique(padding)); - break; - - case ('T'): - case ('X'): // ISO 8601 time format (HH:MM:SS) - formatters_.push_back(details::make_unique(padding)); - break; - - case ('z'): // timezone - formatters_.push_back(details::make_unique(padding)); - break; - - case ('P'): // pid - formatters_.push_back(details::make_unique(padding)); - break; - -#ifdef SPDLOG_ENABLE_MESSAGE_COUNTER - case ('i'): - formatters_.push_back(details::make_unique(padding)); - break; -#endif - case ('^'): // color range start - formatters_.push_back(details::make_unique(padding)); - break; - - case ('$'): // color range end - formatters_.push_back(details::make_unique(padding)); - break; - - case ('@'): // source location (filename:filenumber) - formatters_.push_back(details::make_unique(padding)); - break; - - case ('s'): // source filename - formatters_.push_back(details::make_unique(padding)); - break; - - case ('#'): // source line number - formatters_.push_back(details::make_unique(padding)); - break; - - case ('!'): // source funcname - formatters_.push_back(details::make_unique(padding)); - break; - - case ('%'): // % char - formatters_.push_back(details::make_unique('%')); - break; - - default: // Unknown flag appears as is - auto unknown_flag = details::make_unique(); - unknown_flag->add_ch('%'); - unknown_flag->add_ch(flag); - formatters_.push_back((std::move(unknown_flag))); - break; - } - } - + void handle_flag_(char flag, details::padding_info padding); + // Extract given pad spec (e.g. %8X) // Advance the given it pass the end of the padding spec found (if any) // Return padding. - details::padding_info handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end) - { - using details::padding_info; - using details::scoped_pad; - const size_t max_width = 128; - if (it == end) - { - return padding_info{}; - } - - padding_info::pad_side side; - switch (*it) - { - case '-': - side = padding_info::right; - ++it; - break; - case '=': - side = padding_info::center; - ++it; - break; - default: - side = details::padding_info::left; - break; - } - - if (it == end || !std::isdigit(static_cast(*it))) - { - return padding_info{0, side}; - } - - auto width = static_cast(*it - '0'); - for (++it; it != end && std::isdigit(static_cast(*it)); ++it) - { - auto digit = static_cast(*it - '0'); - width = width * 10 + digit; - } - return details::padding_info{std::min(width, max_width), side}; - } - - void compile_pattern_(const std::string &pattern) - { - auto end = pattern.end(); - std::unique_ptr user_chars; - formatters_.clear(); - for (auto it = pattern.begin(); it != end; ++it) - { - if (*it == '%') - { - if (user_chars) // append user chars found so far - { - formatters_.push_back(std::move(user_chars)); - } - - auto padding = handle_padspec_(++it, end); - - if (it != end) - { - handle_flag_(*it, padding); - } - else - { - break; - } - } - else // chars not following the % sign should be displayed as is - { - if (!user_chars) - { - user_chars = details::make_unique(); - } - user_chars->add_ch(*it); - } - } - if (user_chars) // append raw chars found so far - { - formatters_.push_back(std::move(user_chars)); - } - } + details::padding_info handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end); + + void compile_pattern_(const std::string &pattern); }; } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY -#include "../src/os.cpp" +#include "../src/pattern_formatter.cpp" #endif diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index ab4cf3f8..252f44df 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -154,7 +154,7 @@ public: periodic_flusher_ = details::make_unique(clbk, interval); } - void set_error_handler(log_err_handler handler) + void set_error_handler(void (*handler)(const std::string &msg)) { std::lock_guard lock(logger_map_mutex_); for (auto &l : loggers_) @@ -275,7 +275,7 @@ private: std::unique_ptr formatter_; level::level_enum level_ = spdlog::logger::default_level(); level::level_enum flush_level_ = level::off; - log_err_handler err_handler_; + void (*err_handler_)(const std::string &msg); std::shared_ptr tp_; std::unique_ptr periodic_flusher_; std::shared_ptr default_logger_; diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index f178281d..210f9af2 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -17,26 +17,21 @@ // The use of private formatter per sink provides the opportunity to cache some // formatted data, and support for different format per sink. - #include "spdlog/common.h" #include "spdlog/details/log_msg.h" -//#include "spdlog/formatter.h" -//#include "spdlog/sinks/sink.h" - #include #include #include -namespace spdlog +namespace spdlog { +class logger { - class logger - { - public: +public: template logger(std::string name, It begin, It end) : name_(std::move(name)) - , sinks_(begin, end) + , sinks_(begin, end) { } @@ -57,32 +52,32 @@ namespace spdlog template void log(source_loc loc, level::level_enum lvl, const char *fmt, const Args &... args) { - if (!should_log(lvl)) - { - return; - } + 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"); - } + 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 void log(level::level_enum lvl, const char *fmt, const Args &... args) { - log(source_loc{}, lvl, fmt, args...); + log(source_loc{}, lvl, fmt, args...); } void log(source_loc loc, level::level_enum lvl, const char *msg); void log(level::level_enum lvl, const char *msg); @@ -90,37 +85,37 @@ namespace spdlog template void trace(const char *fmt, const Args &... args) { - log(level::trace, fmt, args...); + log(level::trace, fmt, args...); } template void debug(const char *fmt, const Args &... args) { - log(level::debug, fmt, args...); + log(level::debug, fmt, args...); } template void info(const char *fmt, const Args &... args) { - log(level::info, fmt, args...); + log(level::info, fmt, args...); } template void warn(const char *fmt, const Args &... args) { - log(level::warn, fmt, args...); + log(level::warn, fmt, args...); } template void error(const char *fmt, const Args &... args) { - log(level::err, fmt, args...); + log(level::err, fmt, args...); } template void critical(const char *fmt, const Args &... args) { - log(level::critical, fmt, args...); + log(level::critical, fmt, args...); } #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT @@ -129,87 +124,87 @@ namespace spdlog #else inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target) { - int wbuf_size = static_cast(wbuf.size()); - if (wbuf_size == 0) - { - return; - } + int wbuf_size = static_cast(wbuf.size()); + if (wbuf_size == 0) + { + return; + } - auto result_size = ::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), wbuf_size, NULL, 0, NULL, NULL); + 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())); - } + 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 void log(source_loc source, level::level_enum lvl, const wchar_t *fmt, const Args &... args) { - if (!should_log(lvl)) - { - return; - } + 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 + 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 void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) { - log(source_loc{}, lvl, fmt, args...); + log(source_loc{}, lvl, fmt, args...); } template void trace(const wchar_t *fmt, const Args &... args) { - log(level::trace, fmt, args...); + log(level::trace, fmt, args...); } template void debug(const wchar_t *fmt, const Args &... args) { - log(level::debug, fmt, args...); + log(level::debug, fmt, args...); } template void info(const wchar_t *fmt, const Args &... args) { - log(level::info, fmt, args...); + log(level::info, fmt, args...); } template void warn(const wchar_t *fmt, const Args &... args) { - log(level::warn, fmt, args...); + log(level::warn, fmt, args...); } template void error(const wchar_t *fmt, const Args &... args) { - log(level::err, fmt, args...); + log(level::err, fmt, args...); } template void critical(const wchar_t *fmt, const Args &... args) { - log(level::critical, fmt, args...); + log(level::critical, fmt, args...); } #endif // _WIN32 #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT @@ -217,92 +212,92 @@ namespace spdlog template void log(level::level_enum lvl, const T &msg) { - log(source_loc{}, lvl, msg); + log(source_loc{}, lvl, msg); } // T can be statically converted to string_view template::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"); - } + 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::value, T>::type * = nullptr> void log(source_loc loc, 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(loc, &name_, lvl, to_string_view(buf)); - sink_it_(log_msg); - } - catch (const std::exception &ex) - { - err_handler_(ex.what()); - } - catch (...) - { - err_handler_("Unknown exception in logger"); - } + 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(loc, &name_, lvl, to_string_view(buf)); + sink_it_(log_msg); + } + catch (const std::exception &ex) + { + err_handler_(ex.what()); + } + catch (...) + { + err_handler_("Unknown exception in logger"); + } } template void trace(const T &msg) { - log(level::trace, msg); + log(level::trace, msg); } template void debug(const T &msg) { - log(level::debug, msg); + log(level::debug, msg); } template void info(const T &msg) { - log(level::info, msg); + log(level::info, msg); } template void warn(const T &msg) { - log(level::warn, msg); + log(level::warn, msg); } template void error(const T &msg) { - log(level::err, msg); + log(level::err, msg); } template void critical(const T &msg) { - log(level::critical, msg); + log(level::critical, msg); } bool should_log(level::level_enum msg_level) const; @@ -332,10 +327,8 @@ namespace spdlog std::vector &sinks(); // error handler - void set_error_handler(log_err_handler err_handler); - - log_err_handler error_handler() const; - + void set_error_handler(void (*handler)(const std::string& msg)); + // create new logger with same sinks and configuration. virtual std::shared_ptr clone(std::string logger_name); @@ -347,7 +340,7 @@ namespace spdlog // default error handler. // 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); @@ -356,10 +349,8 @@ namespace spdlog std::vector sinks_; spdlog::level_t level_{spdlog::logger::default_level()}; spdlog::level_t flush_level_{level::off}; - log_err_handler err_handler_{[this](const std::string &msg) { this->default_err_handler_(msg); }}; - std::atomic last_err_time_{0}; - std::atomic msg_counter_{1}; - }; + void (*custom_err_handler_)(const std::string &msg) {nullptr}; +}; } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index fd9a1d27..a70a7aa7 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -103,9 +103,9 @@ inline void flush_every(std::chrono::seconds interval) } // Set global error handler -inline void set_error_handler(log_err_handler handler) +inline void set_error_handler(void (*handler)(const std::string &msg)) { - details::registry::instance().set_error_handler(std::move(handler)); + details::registry::instance().set_error_handler(handler); } // Register the given logger with the given name diff --git a/include/spdlog/tweakme.h b/include/spdlog/tweakme.h index dfcb09d2..beae4f74 100644 --- a/include/spdlog/tweakme.h +++ b/include/spdlog/tweakme.h @@ -107,13 +107,6 @@ // #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") // diff --git a/src/logger.cpp b/src/logger.cpp index 88ff4d3b..cc28d883 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -113,14 +113,9 @@ SPDLOG_INLINE std::vector &spdlog::logger::sinks() } // error handler -SPDLOG_INLINE void spdlog::logger::set_error_handler(spdlog::log_err_handler err_handler) +SPDLOG_INLINE void spdlog::logger::set_error_handler(void (*handler)(const std::string &msg)) { - err_handler_ = std::move(err_handler); -} - -SPDLOG_INLINE spdlog::log_err_handler spdlog::logger::error_handler() const -{ - return err_handler_; + custom_err_handler_ = handler; } // create new logger with same sinks and configuration. @@ -129,16 +124,13 @@ SPDLOG_INLINE std::shared_ptr spdlog::logger::clone(std::string auto cloned = std::make_shared(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()); + cloned->set_error_handler(this->custom_err_handler_); return cloned; } // protected methods SPDLOG_INLINE void spdlog::logger::sink_it_(spdlog::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)) @@ -167,21 +159,17 @@ SPDLOG_INLINE bool spdlog::logger::should_flush_(const spdlog::details::log_msg return (msg.level >= flush_level) && (msg.level != level::off); } -SPDLOG_INLINE void spdlog::logger::default_err_handler_(const std::string &msg) -{ - auto now = time(nullptr); - if (now - last_err_time_ < 60) +void spdlog::logger::err_handler_(const std::string &msg) +{ + if (custom_err_handler_) + { + custom_err_handler_(msg); + } + else { - return; + auto tm_time = spdlog::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); } - 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); -} - -SPDLOG_INLINE void spdlog::logger::incr_msg_counter_(spdlog::details::log_msg &msg) -{ - msg.msg_id = msg_counter_.fetch_add(1, std::memory_order_relaxed); -} +} \ No newline at end of file diff --git a/src/os.cpp b/src/os.cpp index 4a8248f0..9df80e3b 100644 --- a/src/os.cpp +++ b/src/os.cpp @@ -344,14 +344,12 @@ SPDLOG_INLINE void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT // wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined) #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) -#define SPDLOG_FILENAME_T(s) L##s SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) { std::wstring_convert, wchar_t> c; return c.to_bytes(filename); } #else -#define SPDLOG_FILENAME_T(s) s SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) { return filename; diff --git a/src/pattern_formatter.cpp b/src/pattern_formatter.cpp new file mode 100644 index 00000000..b3037480 --- /dev/null +++ b/src/pattern_formatter.cpp @@ -0,0 +1,1266 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/details/pattern_formatter.h" +#endif // !SPDLOG_HEADER_ONLY + +#include "spdlog/details/fmt_helper.h" +#include "spdlog/details/log_msg.h" +#include "spdlog/details/os.h" +#include "spdlog/fmt/fmt.h" +#include "spdlog/formatter.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace spdlog { +namespace details { + +/////////////////////////////////////////////////////////////////////// +// name & level pattern appender +/////////////////////////////////////////////////////////////////////// + +class scoped_pad +{ +public: + scoped_pad(size_t wrapped_size, padding_info &padinfo, fmt::memory_buffer &dest) + : padinfo_(padinfo) + , dest_(dest) + { + + if (padinfo_.width_ <= wrapped_size) + { + total_pad_ = 0; + return; + } + + total_pad_ = padinfo.width_ - wrapped_size; + if (padinfo_.side_ == padding_info::left) + { + pad_it(total_pad_); + total_pad_ = 0; + } + else if (padinfo_.side_ == padding_info::center) + { + auto half_pad = total_pad_ / 2; + auto reminder = total_pad_ & 1; + pad_it(half_pad); + total_pad_ = half_pad + reminder; // for the right side + } + } + + scoped_pad(spdlog::string_view_t txt, padding_info &padinfo, fmt::memory_buffer &dest) + : scoped_pad(txt.size(), padinfo, dest) + { + } + + ~scoped_pad() + { + if (total_pad_) + { + pad_it(total_pad_); + } + } + +private: + void pad_it(size_t count) + { + // count = std::min(count, spaces_.size()); + assert(count <= spaces_.size()); + fmt_helper::append_string_view(string_view_t(spaces_.data(), count), dest_); + } + + const padding_info &padinfo_; + fmt::memory_buffer &dest_; + size_t total_pad_; + string_view_t spaces_{" " + " ", + 128}; +}; + +class name_formatter : public flag_formatter +{ +public: + explicit name_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + if (padinfo_.enabled()) + { + scoped_pad p(*msg.logger_name, padinfo_, dest); + fmt_helper::append_string_view(*msg.logger_name, dest); + } + else + { + fmt_helper::append_string_view(*msg.logger_name, dest); + } + } +}; + +// log level appender +class level_formatter : public flag_formatter +{ +public: + explicit level_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + string_view_t &level_name = level::to_string_view(msg.level); + if (padinfo_.enabled()) + { + scoped_pad p(level_name, padinfo_, dest); + fmt_helper::append_string_view(level_name, dest); + } + else + { + fmt_helper::append_string_view(level_name, dest); + } + } +}; + +// short log level appender +class short_level_formatter : public flag_formatter +{ +public: + explicit short_level_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + string_view_t level_name{level::to_short_c_str(msg.level)}; + scoped_pad p(level_name, padinfo_, dest); + fmt_helper::append_string_view(level_name, dest); + } +}; + +/////////////////////////////////////////////////////////////////////// +// Date time pattern appenders +/////////////////////////////////////////////////////////////////////// + +static const char *ampm(const tm &t) +{ + return t.tm_hour >= 12 ? "PM" : "AM"; +} + +static int to12h(const tm &t) +{ + return t.tm_hour > 12 ? t.tm_hour - 12 : t.tm_hour; +} + +// Abbreviated weekday name +static const char *days[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; +class a_formatter : public flag_formatter +{ +public: + explicit a_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + string_view_t field_value{days[tm_time.tm_wday]}; + scoped_pad p(field_value, padinfo_, dest); + fmt_helper::append_string_view(field_value, dest); + } +}; + +// Full weekday name +static const char *full_days[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; +class A_formatter : public flag_formatter +{ +public: + explicit A_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + string_view_t field_value{full_days[tm_time.tm_wday]}; + scoped_pad p(field_value, padinfo_, dest); + fmt_helper::append_string_view(field_value, dest); + } +}; + +// Abbreviated month +static const char *months[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"}; +class b_formatter : public flag_formatter +{ +public: + explicit b_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + string_view_t field_value{months[tm_time.tm_mon]}; + scoped_pad p(field_value, padinfo_, dest); + fmt_helper::append_string_view(field_value, dest); + } +}; + +// Full month name +static const char *full_months[]{ + "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; +class B_formatter : public flag_formatter +{ +public: + explicit B_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + string_view_t field_value{full_months[tm_time.tm_mon]}; + scoped_pad p(field_value, padinfo_, dest); + fmt_helper::append_string_view(field_value, dest); + } +}; + +// Date and time representation (Thu Aug 23 15:35:46 2014) +class c_formatter final : public flag_formatter +{ +public: + explicit c_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 24; + scoped_pad p(field_size, padinfo_, dest); + + fmt_helper::append_string_view(days[tm_time.tm_wday], dest); + dest.push_back(' '); + fmt_helper::append_string_view(months[tm_time.tm_mon], dest); + dest.push_back(' '); + fmt_helper::append_int(tm_time.tm_mday, dest); + dest.push_back(' '); + // time + + fmt_helper::pad2(tm_time.tm_hour, dest); + dest.push_back(':'); + fmt_helper::pad2(tm_time.tm_min, dest); + dest.push_back(':'); + fmt_helper::pad2(tm_time.tm_sec, dest); + dest.push_back(' '); + fmt_helper::append_int(tm_time.tm_year + 1900, dest); + } +}; + +// year - 2 digit +class C_formatter final : public flag_formatter +{ +public: + explicit C_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 2; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad2(tm_time.tm_year % 100, dest); + } +}; + +// Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01 +class D_formatter final : public flag_formatter +{ +public: + explicit D_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 10; + scoped_pad p(field_size, padinfo_, dest); + + fmt_helper::pad2(tm_time.tm_mon + 1, dest); + dest.push_back('/'); + fmt_helper::pad2(tm_time.tm_mday, dest); + dest.push_back('/'); + fmt_helper::pad2(tm_time.tm_year % 100, dest); + } +}; + +// year - 4 digit +class Y_formatter final : public flag_formatter +{ +public: + explicit Y_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 4; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::append_int(tm_time.tm_year + 1900, dest); + } +}; + +// month 1-12 +class m_formatter final : public flag_formatter +{ +public: + explicit m_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 2; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad2(tm_time.tm_mon + 1, dest); + } +}; + +// day of month 1-31 +class d_formatter final : public flag_formatter +{ +public: + explicit d_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 2; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad2(tm_time.tm_mday, dest); + } +}; + +// hours in 24 format 0-23 +class H_formatter final : public flag_formatter +{ +public: + explicit H_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 2; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad2(tm_time.tm_hour, dest); + } +}; + +// hours in 12 format 1-12 +class I_formatter final : public flag_formatter +{ +public: + explicit I_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 2; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad2(to12h(tm_time), dest); + } +}; + +// minutes 0-59 +class M_formatter final : public flag_formatter +{ +public: + explicit M_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 2; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad2(tm_time.tm_min, dest); + } +}; + +// seconds 0-59 +class S_formatter final : public flag_formatter +{ +public: + explicit S_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 2; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad2(tm_time.tm_sec, dest); + } +}; + +// milliseconds +class e_formatter final : public flag_formatter +{ +public: + explicit e_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + auto millis = fmt_helper::time_fraction(msg.time); + if (padinfo_.enabled()) + { + const size_t field_size = 3; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad3(static_cast(millis.count()), dest); + } + else + { + fmt_helper::pad3(static_cast(millis.count()), dest); + } + } +}; + +// microseconds +class f_formatter final : public flag_formatter +{ +public: + explicit f_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + auto micros = fmt_helper::time_fraction(msg.time); + if (padinfo_.enabled()) + { + const size_t field_size = 6; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad6(static_cast(micros.count()), dest); + } + else + { + fmt_helper::pad6(static_cast(micros.count()), dest); + } + } +}; + +// nanoseconds +class F_formatter final : public flag_formatter +{ +public: + explicit F_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + auto ns = fmt_helper::time_fraction(msg.time); + if (padinfo_.enabled()) + { + const size_t field_size = 9; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad9(static_cast(ns.count()), dest); + } + else + { + fmt_helper::pad9(static_cast(ns.count()), dest); + } + } +}; + +// seconds since epoch +class E_formatter final : public flag_formatter +{ +public: + explicit E_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + const size_t field_size = 10; + scoped_pad p(field_size, padinfo_, dest); + auto duration = msg.time.time_since_epoch(); + auto seconds = std::chrono::duration_cast(duration).count(); + fmt_helper::append_int(seconds, dest); + } +}; + +// AM/PM +class p_formatter final : public flag_formatter +{ +public: + explicit p_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 2; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::append_string_view(ampm(tm_time), dest); + } +}; + +// 12 hour clock 02:55:02 pm +class r_formatter final : public flag_formatter +{ +public: + explicit r_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 11; + scoped_pad p(field_size, padinfo_, dest); + + fmt_helper::pad2(to12h(tm_time), dest); + dest.push_back(':'); + fmt_helper::pad2(tm_time.tm_min, dest); + dest.push_back(':'); + fmt_helper::pad2(tm_time.tm_sec, dest); + dest.push_back(' '); + fmt_helper::append_string_view(ampm(tm_time), dest); + } +}; + +// 24-hour HH:MM time, equivalent to %H:%M +class R_formatter final : public flag_formatter +{ +public: + explicit R_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 5; + scoped_pad p(field_size, padinfo_, dest); + + fmt_helper::pad2(tm_time.tm_hour, dest); + dest.push_back(':'); + fmt_helper::pad2(tm_time.tm_min, dest); + } +}; + +// ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S +class T_formatter final : public flag_formatter +{ +public: + explicit T_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 8; + scoped_pad p(field_size, padinfo_, dest); + + fmt_helper::pad2(tm_time.tm_hour, dest); + dest.push_back(':'); + fmt_helper::pad2(tm_time.tm_min, dest); + dest.push_back(':'); + fmt_helper::pad2(tm_time.tm_sec, dest); + } +}; + +// ISO 8601 offset from UTC in timezone (+-HH:MM) +class z_formatter final : public flag_formatter +{ +public: + explicit z_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + const std::chrono::seconds cache_refresh = std::chrono::seconds(5); + + z_formatter() = default; + z_formatter(const z_formatter &) = delete; + z_formatter &operator=(const z_formatter &) = delete; + + void format(const details::log_msg &msg, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + const size_t field_size = 6; + scoped_pad p(field_size, padinfo_, dest); + +#ifdef _WIN32 + int total_minutes = get_cached_offset(msg, tm_time); +#else + // No need to chache under gcc, + // it is very fast (already stored in tm.tm_gmtoff) + (void)(msg); + int total_minutes = os::utc_minutes_offset(tm_time); +#endif + bool is_negative = total_minutes < 0; + if (is_negative) + { + total_minutes = -total_minutes; + dest.push_back('-'); + } + else + { + dest.push_back('+'); + } + + fmt_helper::pad2(total_minutes / 60, dest); // hours + dest.push_back(':'); + fmt_helper::pad2(total_minutes % 60, dest); // minutes + } + +private: + log_clock::time_point last_update_{std::chrono::seconds(0)}; +#ifdef _WIN32 + int offset_minutes_{0}; + + int get_cached_offset(const log_msg &msg, const std::tm &tm_time) + { + if (msg.time - last_update_ >= cache_refresh) + { + offset_minutes_ = os::utc_minutes_offset(tm_time); + last_update_ = msg.time; + } + return offset_minutes_; + } +#endif +}; + +// Thread id +class t_formatter final : public flag_formatter +{ +public: + explicit t_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + if (padinfo_.enabled()) + { + const auto field_size = fmt_helper::count_digits(msg.thread_id); + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::append_int(msg.thread_id, dest); + } + else + { + fmt_helper::append_int(msg.thread_id, dest); + } + } +}; + +// Current pid +class pid_formatter final : public flag_formatter +{ +public: + explicit pid_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override + { + const auto pid = static_cast(details::os::pid()); + if (padinfo_.enabled()) + { + auto field_size = fmt_helper::count_digits(pid); + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::append_int(pid, dest); + } + else + { + fmt_helper::append_int(pid, dest); + } + } +}; + +class v_formatter final : public flag_formatter +{ +public: + explicit v_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + if (padinfo_.enabled()) + { + scoped_pad p(msg.payload, padinfo_, dest); + fmt_helper::append_string_view(msg.payload, dest); + } + else + { + fmt_helper::append_string_view(msg.payload, dest); + } + } +}; + +class ch_formatter final : public flag_formatter +{ +public: + explicit ch_formatter(char ch) + : ch_(ch) + { + } + + void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override + { + const size_t field_size = 1; + scoped_pad p(field_size, padinfo_, dest); + dest.push_back(ch_); + } + +private: + char ch_; +}; + +// aggregate user chars to display as is +class aggregate_formatter final : public flag_formatter +{ +public: + aggregate_formatter() = default; + + void add_ch(char ch) + { + str_ += ch; + } + void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override + { + fmt_helper::append_string_view(str_, dest); + } + +private: + std::string str_; +}; + +// mark the color range. expect it to be in the form of "%^colored text%$" +class color_start_formatter final : public flag_formatter +{ +public: + explicit color_start_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + msg.color_range_start = dest.size(); + } +}; +class color_stop_formatter final : public flag_formatter +{ +public: + explicit color_stop_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + msg.color_range_end = dest.size(); + } +}; + +// print source location +class source_location_formatter final : public flag_formatter +{ +public: + explicit source_location_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + if (msg.source.empty()) + { + return; + } + if (padinfo_.enabled()) + { + const auto text_size = std::char_traits::length(msg.source.filename) + fmt_helper::count_digits(msg.source.line) + 1; + scoped_pad p(text_size, padinfo_, dest); + fmt_helper::append_string_view(msg.source.filename, dest); + dest.push_back(':'); + fmt_helper::append_int(msg.source.line, dest); + } + else + { + fmt_helper::append_string_view(msg.source.filename, dest); + dest.push_back(':'); + fmt_helper::append_int(msg.source.line, dest); + } + } +}; +// print source filename +class source_filename_formatter final : public flag_formatter +{ +public: + explicit source_filename_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + if (msg.source.empty()) + { + return; + } + scoped_pad p(msg.source.filename, padinfo_, dest); + fmt_helper::append_string_view(msg.source.filename, dest); + } +}; + +class source_linenum_formatter final : public flag_formatter +{ +public: + explicit source_linenum_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + if (msg.source.empty()) + { + return; + } + if (padinfo_.enabled()) + { + auto field_size = fmt_helper::count_digits(msg.source.line); + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::append_int(msg.source.line, dest); + } + else + { + fmt_helper::append_int(msg.source.line, dest); + } + } +}; +// print source funcname +class source_funcname_formatter final : public flag_formatter +{ +public: + explicit source_funcname_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + if (msg.source.empty()) + { + return; + } + scoped_pad p(msg.source.funcname, padinfo_, dest); + fmt_helper::append_string_view(msg.source.funcname, dest); + } +}; + +// Full info formatter +// pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v +class full_formatter final : public flag_formatter +{ +public: + explicit full_formatter(padding_info padinfo) + : flag_formatter(padinfo) + { + } + + void format(const details::log_msg &msg, const std::tm &tm_time, fmt::memory_buffer &dest) override + { + using std::chrono::duration_cast; + using std::chrono::milliseconds; + using std::chrono::seconds; + +#ifndef SPDLOG_NO_DATETIME + + // cache the date/time part for the next second. + auto duration = msg.time.time_since_epoch(); + auto secs = duration_cast(duration); + + if (cache_timestamp_ != secs || cached_datetime_.size() == 0) + { + cached_datetime_.clear(); + cached_datetime_.push_back('['); + fmt_helper::append_int(tm_time.tm_year + 1900, cached_datetime_); + cached_datetime_.push_back('-'); + + fmt_helper::pad2(tm_time.tm_mon + 1, cached_datetime_); + cached_datetime_.push_back('-'); + + fmt_helper::pad2(tm_time.tm_mday, cached_datetime_); + cached_datetime_.push_back(' '); + + fmt_helper::pad2(tm_time.tm_hour, cached_datetime_); + cached_datetime_.push_back(':'); + + fmt_helper::pad2(tm_time.tm_min, cached_datetime_); + cached_datetime_.push_back(':'); + + fmt_helper::pad2(tm_time.tm_sec, cached_datetime_); + cached_datetime_.push_back('.'); + + cache_timestamp_ = secs; + } + fmt_helper::append_buf(cached_datetime_, dest); + + auto millis = fmt_helper::time_fraction(msg.time); + fmt_helper::pad3(static_cast(millis.count()), dest); + dest.push_back(']'); + dest.push_back(' '); + +#else // no datetime needed + (void)tm_time; +#endif + +#ifndef SPDLOG_NO_NAME + if (!msg.logger_name->empty()) + { + dest.push_back('['); + // fmt_helper::append_str(*msg.logger_name, dest); + fmt_helper::append_string_view(*msg.logger_name, dest); + dest.push_back(']'); + dest.push_back(' '); + } +#endif + + dest.push_back('['); + // wrap the level name with color + msg.color_range_start = dest.size(); + // fmt_helper::append_string_view(level::to_c_str(msg.level), dest); + fmt_helper::append_string_view(level::to_string_view(msg.level), dest); + msg.color_range_end = dest.size(); + dest.push_back(']'); + dest.push_back(' '); + + // add source location if present + if (!msg.source.empty()) + { + dest.push_back('['); + fmt_helper::append_string_view(msg.source.filename, dest); + dest.push_back(':'); + fmt_helper::append_int(msg.source.line, dest); + dest.push_back(']'); + dest.push_back(' '); + } + // fmt_helper::append_string_view(msg.msg(), dest); + fmt_helper::append_string_view(msg.payload, dest); + } + +private: + std::chrono::seconds cache_timestamp_{0}; + fmt::basic_memory_buffer cached_datetime_; +}; + +} // namespace details + + + pattern_formatter::pattern_formatter( + std::string pattern, pattern_time_type time_type, std::string eol) + : pattern_(std::move(pattern)) + , eol_(std::move(eol)) + , pattern_time_type_(time_type) + , last_log_secs_(0) + { + std::memset(&cached_tm_, 0, sizeof(cached_tm_)); + compile_pattern_(pattern_); + } + + // use by default full formatter for if pattern is not given + pattern_formatter::pattern_formatter(pattern_time_type time_type, std::string eol) + : pattern_("%+") + , eol_(std::move(eol)) + , pattern_time_type_(time_type) + , last_log_secs_(0) + { + std::memset(&cached_tm_, 0, sizeof(cached_tm_)); + formatters_.push_back(details::make_unique(details::padding_info{})); + } + + + std::unique_ptr pattern_formatter::clone() const + { + return details::make_unique(pattern_, pattern_time_type_, eol_); + } + + void pattern_formatter::format(const details::log_msg &msg, fmt::memory_buffer &dest) + { +#ifndef SPDLOG_NO_DATETIME + auto secs = std::chrono::duration_cast(msg.time.time_since_epoch()); + if (secs != last_log_secs_) + { + cached_tm_ = get_time_(msg); + last_log_secs_ = secs; + } +#endif + for (auto &f : formatters_) + { + f->format(msg, cached_tm_, dest); + } + // write eol + details::fmt_helper::append_string_view(eol_, dest); + } + + std::tm pattern_formatter::get_time_(const details::log_msg &msg) + { + if (pattern_time_type_ == pattern_time_type::local) + { + return details::os::localtime(log_clock::to_time_t(msg.time)); + } + return details::os::gmtime(log_clock::to_time_t(msg.time)); + } + + void pattern_formatter::handle_flag_(char flag, details::padding_info padding) + { + switch (flag) + { + + case ('+'): // default formatter + formatters_.push_back(details::make_unique(padding)); + break; + + case 'n': // logger name + formatters_.push_back(details::make_unique(padding)); + break; + + case 'l': // level + formatters_.push_back(details::make_unique(padding)); + break; + + case 'L': // short level + formatters_.push_back(details::make_unique(padding)); + break; + + case ('t'): // thread id + formatters_.push_back(details::make_unique(padding)); + break; + + case ('v'): // the message text + formatters_.push_back(details::make_unique(padding)); + break; + + case ('a'): // weekday + formatters_.push_back(details::make_unique(padding)); + break; + + case ('A'): // short weekday + formatters_.push_back(details::make_unique(padding)); + break; + + case ('b'): + case ('h'): // month + formatters_.push_back(details::make_unique(padding)); + break; + + case ('B'): // short month + formatters_.push_back(details::make_unique(padding)); + break; + + case ('c'): // datetime + formatters_.push_back(details::make_unique(padding)); + break; + + case ('C'): // year 2 digits + formatters_.push_back(details::make_unique(padding)); + break; + + case ('Y'): // year 4 digits + formatters_.push_back(details::make_unique(padding)); + break; + + case ('D'): + case ('x'): // datetime MM/DD/YY + formatters_.push_back(details::make_unique(padding)); + break; + + case ('m'): // month 1-12 + formatters_.push_back(details::make_unique(padding)); + break; + + case ('d'): // day of month 1-31 + formatters_.push_back(details::make_unique(padding)); + break; + + case ('H'): // hours 24 + formatters_.push_back(details::make_unique(padding)); + break; + + case ('I'): // hours 12 + formatters_.push_back(details::make_unique(padding)); + break; + + case ('M'): // minutes + formatters_.push_back(details::make_unique(padding)); + break; + + case ('S'): // seconds + formatters_.push_back(details::make_unique(padding)); + break; + + case ('e'): // milliseconds + formatters_.push_back(details::make_unique(padding)); + break; + + case ('f'): // microseconds + formatters_.push_back(details::make_unique(padding)); + break; + + case ('F'): // nanoseconds + formatters_.push_back(details::make_unique(padding)); + break; + + case ('E'): // seconds since epoch + formatters_.push_back(details::make_unique(padding)); + break; + + case ('p'): // am/pm + formatters_.push_back(details::make_unique(padding)); + break; + + case ('r'): // 12 hour clock 02:55:02 pm + formatters_.push_back(details::make_unique(padding)); + break; + + case ('R'): // 24-hour HH:MM time + formatters_.push_back(details::make_unique(padding)); + break; + + case ('T'): + case ('X'): // ISO 8601 time format (HH:MM:SS) + formatters_.push_back(details::make_unique(padding)); + break; + + case ('z'): // timezone + formatters_.push_back(details::make_unique(padding)); + break; + + case ('P'): // pid + formatters_.push_back(details::make_unique(padding)); + break; + + case ('^'): // color range start + formatters_.push_back(details::make_unique(padding)); + break; + + case ('$'): // color range end + formatters_.push_back(details::make_unique(padding)); + break; + + case ('@'): // source location (filename:filenumber) + formatters_.push_back(details::make_unique(padding)); + break; + + case ('s'): // source filename + formatters_.push_back(details::make_unique(padding)); + break; + + case ('#'): // source line number + formatters_.push_back(details::make_unique(padding)); + break; + + case ('!'): // source funcname + formatters_.push_back(details::make_unique(padding)); + break; + + case ('%'): // % char + formatters_.push_back(details::make_unique('%')); + break; + + default: // Unknown flag appears as is + auto unknown_flag = details::make_unique(); + unknown_flag->add_ch('%'); + unknown_flag->add_ch(flag); + formatters_.push_back((std::move(unknown_flag))); + break; + } + } + + // Extract given pad spec (e.g. %8X) + // Advance the given it pass the end of the padding spec found (if any) + // Return padding. + details::padding_info pattern_formatter::handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end) + { + using details::padding_info; + using details::scoped_pad; + const size_t max_width = 128; + if (it == end) + { + return padding_info{}; + } + + padding_info::pad_side side; + switch (*it) + { + case '-': + side = padding_info::right; + ++it; + break; + case '=': + side = padding_info::center; + ++it; + break; + default: + side = details::padding_info::left; + break; + } + + if (it == end || !std::isdigit(static_cast(*it))) + { + return padding_info{0, side}; + } + + auto width = static_cast(*it - '0'); + for (++it; it != end && std::isdigit(static_cast(*it)); ++it) + { + auto digit = static_cast(*it - '0'); + width = width * 10 + digit; + } + return details::padding_info{std::min(width, max_width), side}; + } + + void pattern_formatter::compile_pattern_(const std::string &pattern) + { + auto end = pattern.end(); + std::unique_ptr user_chars; + formatters_.clear(); + for (auto it = pattern.begin(); it != end; ++it) + { + if (*it == '%') + { + if (user_chars) // append user chars found so far + { + formatters_.push_back(std::move(user_chars)); + } + + auto padding = handle_padspec_(++it, end); + + if (it != end) + { + handle_flag_(*it, padding); + } + else + { + break; + } + } + else // chars not following the % sign should be displayed as is + { + if (!user_chars) + { + user_chars = details::make_unique(); + } + user_chars->add_ch(*it); + } + } + if (user_chars) // append raw chars found so far + { + formatters_.push_back(std::move(user_chars)); + } + } +} // namespace spdlog + diff --git a/tests/includes.h b/tests/includes.h index 54601602..26517922 100644 --- a/tests/includes.h +++ b/tests/includes.h @@ -11,7 +11,6 @@ #include #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_DEBUG -#define SPDLOG_ENABLE_MESSAGE_COUNTER #include "spdlog/spdlog.h" #include "spdlog/async.h" diff --git a/tests/test_errors.cpp b/tests/test_errors.cpp index 24075634..e675cfd3 100644 --- a/tests/test_errors.cpp +++ b/tests/test_errors.cpp @@ -41,13 +41,18 @@ TEST_CASE("default_error_handler", "[errors]]") struct custom_ex { }; + +static void custom_handler(const std::string &msg) +{ + throw custom_ex(); +} TEST_CASE("custom_error_handler", "[errors]]") { prepare_logdir(); std::string filename = "logs/simple_log.txt"; auto logger = spdlog::create("logger", filename, true); logger->flush_on(spdlog::level::info); - logger->set_error_handler([=](const std::string &) { throw custom_ex(); }); + logger->set_error_handler(custom_handler); logger->info("Good message #1"); REQUIRE_THROWS_AS(logger->info("Bad format msg {} {}", "xxx"), custom_ex); @@ -59,7 +64,7 @@ TEST_CASE("default_error_handler2", "[errors]]") { spdlog::drop_all(); auto logger = spdlog::create("failed_logger"); - logger->set_error_handler([=](const std::string &) { throw custom_ex(); }); + logger->set_error_handler(custom_handler); REQUIRE_THROWS_AS(logger->info("Some message"), custom_ex); } @@ -67,26 +72,26 @@ TEST_CASE("flush_error_handler", "[errors]]") { spdlog::drop_all(); auto logger = spdlog::create("failed_logger"); - logger->set_error_handler([=](const std::string &) { throw custom_ex(); }); + logger->set_error_handler(custom_handler); REQUIRE_THROWS_AS(logger->flush(), custom_ex); } TEST_CASE("async_error_handler", "[errors]]") { prepare_logdir(); - std::string err_msg("log failed with some msg"); + std::string filename = "logs/simple_async_log.txt"; { spdlog::init_thread_pool(128, 1); auto logger = spdlog::create_async("logger", filename, true); - logger->set_error_handler([=](const std::string &) { + logger->set_error_handler([](const std::string &) { std::ofstream ofs("logs/custom_err.txt"); if (!ofs) { throw std::runtime_error("Failed open logs/custom_err.txt"); } - ofs << err_msg; + ofs << "log failed with some msg"; }); logger->info("Good message #1"); logger->info("Bad format msg {} {}", "xxx"); @@ -95,27 +100,26 @@ TEST_CASE("async_error_handler", "[errors]]") } spdlog::init_thread_pool(128, 1); REQUIRE(count_lines(filename) == 2); - REQUIRE(file_contents("logs/custom_err.txt") == err_msg); + REQUIRE(file_contents("logs/custom_err.txt") == "log failed with some msg"); } // Make sure async error handler is executed TEST_CASE("async_error_handler2", "[errors]]") { - prepare_logdir(); - std::string err_msg("This is async handler error message"); + prepare_logdir(); { spdlog::init_thread_pool(128, 1); auto logger = spdlog::create_async("failed_logger"); - logger->set_error_handler([=](const std::string &) { + logger->set_error_handler([](const std::string &) { std::ofstream ofs("logs/custom_err2.txt"); if (!ofs) throw std::runtime_error("Failed open logs/custom_err2.txt"); - ofs << err_msg; + ofs << "handler error message"; }); logger->info("Hello failure"); spdlog::drop("failed_logger"); // force logger to drain the queue and shutdown } spdlog::init_thread_pool(128, 1); - REQUIRE(file_contents("logs/custom_err2.txt") == err_msg); + REQUIRE(file_contents("logs/custom_err2.txt") == "handler error message"); } diff --git a/tests/test_misc.cpp b/tests/test_misc.cpp index 1b880835..5f4c094c 100644 --- a/tests/test_misc.cpp +++ b/tests/test_misc.cpp @@ -107,8 +107,7 @@ TEST_CASE("clone-logger", "[clone]") cloned->info("Some message 2"); auto test_sink = std::static_pointer_cast(cloned->sinks()[0]); - REQUIRE(test_sink->msg_counter() == 2); - + spdlog::drop_all(); } @@ -129,8 +128,7 @@ TEST_CASE("clone async", "[clone]") spdlog::details::os::sleep_for_millis(10); - auto test_sink = std::static_pointer_cast(cloned->sinks()[0]); - REQUIRE(test_sink->msg_counter() == 2); + auto test_sink = std::static_pointer_cast(cloned->sinks()[0]); 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))); } -TEST_CASE("message_counter", "[message_counter]") -{ - std::ostringstream oss; - auto oss_sink = std::make_shared(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]") { std::ostringstream oss; From e9f34fbd26d7f50d0be644b02f55193a0c3ba12b Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 5 Apr 2019 23:10:12 +0300 Subject: [PATCH 058/157] wip --- example/example.cpp | 6 +----- src/os.cpp | 4 +--- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 918d19b1..217faa4e 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -14,9 +14,5 @@ spdlog::logger *get_logger(); int main(int, char *[]) { auto *l = get_logger(); - l->info("HE LO ", "GA"); - l->error("Some {} {} {}", "er or"); - l->error("Some {} {} {}", "er or"); - - + l->info("HE LO ", "GA"); } \ No newline at end of file diff --git a/src/os.cpp b/src/os.cpp index 9df80e3b..6d6cad72 100644 --- a/src/os.cpp +++ b/src/os.cpp @@ -6,7 +6,6 @@ #ifndef SPDLOG_HEADER_ONLY #include "spdlog/details/os.h" -#include "spdlog/common.h" #endif #include @@ -15,11 +14,10 @@ #include #include #include -#include #include +#include #include #include -#include #ifdef _WIN32 From 2aceb13f3ed81ebdc7da6c5db77cc1437563a2d0 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 5 Apr 2019 23:34:55 +0300 Subject: [PATCH 059/157] fix support for utf8 logging under win32 --- example/example.cpp | 2 +- include/spdlog/details/os.h | 5 + include/spdlog/logger.h | 313 ++++++++++++++++++------------------ src/logger.cpp | 2 +- src/os.cpp | 24 +++ 5 files changed, 184 insertions(+), 162 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 217faa4e..4b416cd7 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -14,5 +14,5 @@ spdlog::logger *get_logger(); int main(int, char *[]) { auto *l = get_logger(); - l->info("HE LO ", "GA"); + l->info(L"HEllo {}", L"HGFS"); } \ No newline at end of file diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index d923b30f..9dd94ebe 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -79,6 +79,11 @@ bool is_color_terminal() SPDLOG_NOEXCEPT; // Detrmine if the terminal attached // Source: https://github.com/agauniyal/rang/ bool in_terminal(FILE *file) SPDLOG_NOEXCEPT; + +#if defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) && defined(_WIN32) +void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target); +#endif + } // namespace os } // namespace details } // namespace spdlog diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 210f9af2..c27ddcfe 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -20,6 +20,10 @@ #include "spdlog/common.h" #include "spdlog/details/log_msg.h" +#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT +#include "spdlog/details/os.h" +#endif + #include #include #include @@ -52,254 +56,241 @@ public: template void log(source_loc loc, level::level_enum lvl, const char *fmt, const Args &... args) { - if (!should_log(lvl)) - { - return; - } + 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"); - } + 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 void log(level::level_enum lvl, const char *fmt, const Args &... args) { - log(source_loc{}, lvl, fmt, args...); + log(source_loc{}, lvl, fmt, args...); } + void log(source_loc loc, level::level_enum lvl, const char *msg); void log(level::level_enum lvl, const char *msg); template void trace(const char *fmt, const Args &... args) { - log(level::trace, fmt, args...); + log(level::trace, fmt, args...); } template void debug(const char *fmt, const Args &... args) { - log(level::debug, fmt, args...); + log(level::debug, fmt, args...); } template void info(const char *fmt, const Args &... args) { - log(level::info, fmt, args...); + log(level::info, fmt, args...); } template void warn(const char *fmt, const Args &... args) { - log(level::warn, fmt, args...); + log(level::warn, fmt, args...); } template void error(const char *fmt, const Args &... args) { - log(level::err, fmt, args...); + log(level::err, fmt, args...); } template void critical(const char *fmt, const Args &... args) { - log(level::critical, fmt, args...); + log(level::critical, fmt, args...); } -#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT -#ifndef _WIN32 -#error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows -#else - inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target) - { - int wbuf_size = static_cast(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 - 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 - 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 - void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) - { - log(source_loc{}, lvl, fmt, args...); - } - - template - void trace(const wchar_t *fmt, const Args &... args) - { - log(level::trace, fmt, args...); - } - - template - void debug(const wchar_t *fmt, const Args &... args) - { - log(level::debug, fmt, args...); - } - - template - void info(const wchar_t *fmt, const Args &... args) - { - log(level::info, fmt, args...); - } - - template - void warn(const wchar_t *fmt, const Args &... args) - { - log(level::warn, fmt, args...); - } - - template - void error(const wchar_t *fmt, const Args &... args) - { - log(level::err, fmt, args...); - } - - template - void critical(const wchar_t *fmt, const Args &... args) - { - log(level::critical, fmt, args...); - } -#endif // _WIN32 -#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT template void log(level::level_enum lvl, const T &msg) { - log(source_loc{}, lvl, msg); + log(source_loc{}, lvl, msg); } // T can be statically converted to string_view template::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"); - } + 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::value, T>::type * = nullptr> void log(source_loc loc, 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(loc, &name_, lvl, to_string_view(buf)); - sink_it_(log_msg); - } - catch (const std::exception &ex) - { - err_handler_(ex.what()); - } - catch (...) - { - err_handler_("Unknown exception in logger"); - } + 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(loc, &name_, lvl, to_string_view(buf)); + sink_it_(log_msg); + } + catch (const std::exception &ex) + { + err_handler_(ex.what()); + } + catch (...) + { + err_handler_("Unknown exception in logger"); + } } template void trace(const T &msg) { - log(level::trace, msg); + log(level::trace, msg); } template void debug(const T &msg) { - log(level::debug, msg); + log(level::debug, msg); } template void info(const T &msg) { - log(level::info, msg); + log(level::info, msg); } template void warn(const T &msg) { - log(level::warn, msg); + log(level::warn, msg); } template void error(const T &msg) { - log(level::err, msg); + log(level::err, msg); } template void critical(const T &msg) { - log(level::critical, msg); + log(level::critical, msg); } +#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT +#ifndef _WIN32 +#error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows +#else + template + 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 + void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) + { + log(source_loc{}, lvl, fmt, args...); + } + + template + void trace(const wchar_t *fmt, const Args &... args) + { + log(level::trace, fmt, args...); + } + + template + void debug(const wchar_t *fmt, const Args &... args) + { + log(level::debug, fmt, args...); + } + + template + void info(const wchar_t *fmt, const Args &... args) + { + log(level::info, fmt, args...); + } + + template + void warn(const wchar_t *fmt, const Args &... args) + { + log(level::warn, fmt, args...); + } + + template + void error(const wchar_t *fmt, const Args &... args) + { + log(level::err, fmt, args...); + } + + template + void critical(const wchar_t *fmt, const Args &... args) + { + log(level::critical, fmt, args...); + } +#endif // _WIN32 +#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT + bool should_log(level::level_enum msg_level) const; void set_level(level::level_enum log_level); @@ -350,6 +341,8 @@ public: spdlog::level_t level_{spdlog::logger::default_level()}; spdlog::level_t flush_level_{level::off}; void (*custom_err_handler_)(const std::string &msg) {nullptr}; + + }; } // namespace spdlog diff --git a/src/logger.cpp b/src/logger.cpp index cc28d883..32396524 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -172,4 +172,4 @@ void spdlog::logger::err_handler_(const std::string &msg) 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); } -} \ No newline at end of file +} diff --git a/src/os.cpp b/src/os.cpp index 6d6cad72..93738cb0 100644 --- a/src/os.cpp +++ b/src/os.cpp @@ -397,6 +397,30 @@ SPDLOG_INLINE bool in_terminal(FILE *file) SPDLOG_NOEXCEPT 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(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 From bfbb4e40500344c7945c4a70ef45deed255d6f63 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 5 Apr 2019 23:40:27 +0300 Subject: [PATCH 060/157] some err handler cleanup --- include/spdlog/logger.h | 5 +++-- src/logger.cpp | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index c27ddcfe..6b6c736b 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -32,6 +32,7 @@ namespace spdlog { class logger { public: + using err_handler = void (*)(const std::string &msg); template logger(std::string name, It begin, It end) : name_(std::move(name)) @@ -318,7 +319,7 @@ public: std::vector &sinks(); // error handler - void set_error_handler(void (*handler)(const std::string& msg)); + void set_error_handler(err_handler); // create new logger with same sinks and configuration. virtual std::shared_ptr clone(std::string logger_name); @@ -340,7 +341,7 @@ public: std::vector sinks_; spdlog::level_t level_{spdlog::logger::default_level()}; spdlog::level_t flush_level_{level::off}; - void (*custom_err_handler_)(const std::string &msg) {nullptr}; + err_handler custom_err_handler_{nullptr}; }; diff --git a/src/logger.cpp b/src/logger.cpp index 32396524..4ef4cc88 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -113,7 +113,7 @@ SPDLOG_INLINE std::vector &spdlog::logger::sinks() } // error handler -SPDLOG_INLINE void spdlog::logger::set_error_handler(void (*handler)(const std::string &msg)) +SPDLOG_INLINE void spdlog::logger::set_error_handler(err_handler handler) { custom_err_handler_ = handler; } From c69c49047b64931a16273321ad13af7ade345ab7 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 6 Apr 2019 00:15:14 +0300 Subject: [PATCH 061/157] wip static lib --- example/example.cpp | 3 +- include/spdlog/details/registry.h | 271 ++++++------------------------ include/spdlog/spdlog.h | 1 + src/registry.cpp | 259 ++++++++++++++++++++++++++++ 4 files changed, 309 insertions(+), 225 deletions(-) create mode 100644 src/registry.cpp diff --git a/example/example.cpp b/example/example.cpp index 4b416cd7..01227247 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -7,6 +7,7 @@ // // +#include "spdlog/spdlog.h" #include "spdlog/logger.h" spdlog::logger *get_logger(); @@ -14,5 +15,5 @@ spdlog::logger *get_logger(); int main(int, char *[]) { auto *l = get_logger(); - l->info(L"HEllo {}", L"HGFS"); + l->info("HEllo {}", "HG FS"); } \ No newline at end of file diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 252f44df..7a1ad1f2 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -11,28 +11,20 @@ // This class is thread safe #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 #include #include #include #include +#include namespace spdlog { +class logger; + namespace details { class thread_pool; +class periodic_worker; class registry { @@ -40,240 +32,67 @@ public: registry(const registry &) = delete; registry &operator=(const registry &) = delete; - void register_logger(std::shared_ptr new_logger) - { - std::lock_guard lock(logger_map_mutex_); - register_logger_(std::move(new_logger)); - } - - void initialize_logger(std::shared_ptr new_logger) - { - std::lock_guard 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 get(const std::string &logger_name) - { - std::lock_guard lock(logger_map_mutex_); - auto found = loggers_.find(logger_name); - return found == loggers_.end() ? nullptr : found->second; - } - - std::shared_ptr default_logger() - { - std::lock_guard lock(logger_map_mutex_); - return default_logger_; - } + void register_logger(std::shared_ptr new_logger); + void initialize_logger(std::shared_ptr new_logger); + std::shared_ptr get(const std::string &logger_name); + + std::shared_ptr default_logger(); + // Return raw ptr to the default logger. // To be used directly by the spdlog default api (e.g. spdlog::info) // This make the default API faster, but cannot be used concurrently with set_default_logger(). // e.g do not call set_default_logger() from one thread while calling spdlog::info() from another. - logger *get_default_raw() - { - return default_logger_.get(); - } + logger *get_default_raw(); + // set default logger. // default logger is stored in default_logger_ (for faster retrieval) and in the loggers_ map. - void set_default_logger(std::shared_ptr new_default_logger) - { - std::lock_guard 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 tp) - { - std::lock_guard lock(tp_mutex_); - tp_ = std::move(tp); - } - - std::shared_ptr get_tp() - { - std::lock_guard lock(tp_mutex_); - return tp_; - } + void set_default_logger(std::shared_ptr new_default_logger); + void set_tp(std::shared_ptr tp); + + std::shared_ptr get_tp(); + // Set global formatter. Each sink in each logger will get a clone of this object - void set_formatter(std::unique_ptr formatter) - { - std::lock_guard lock(logger_map_mutex_); - formatter_ = std::move(formatter); - for (auto &l : loggers_) - { - l.second->set_formatter(formatter_->clone()); - } - } + void set_formatter(std::unique_ptr formatter); - void set_level(level::level_enum log_level) - { - std::lock_guard 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) - { - std::lock_guard 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) - { - std::lock_guard lock(flusher_mutex_); - std::function clbk = std::bind(®istry::flush_all, this); - periodic_flusher_ = details::make_unique(clbk, interval); - } - - void set_error_handler(void (*handler)(const std::string &msg)) - { - std::lock_guard lock(logger_map_mutex_); - for (auto &l : loggers_) - { - l.second->set_error_handler(handler); - } - err_handler_ = handler; - } - - void apply_all(const std::function)> &fun) - { - std::lock_guard lock(logger_map_mutex_); - for (auto &l : loggers_) - { - fun(l.second); - } - } - - void flush_all() - { - std::lock_guard lock(logger_map_mutex_); - for (auto &l : loggers_) - { - l.second->flush(); - } - } - - void drop(const std::string &logger_name) - { - std::lock_guard lock(logger_map_mutex_); - loggers_.erase(logger_name); - if (default_logger_ && default_logger_->name() == logger_name) - { - default_logger_.reset(); - } - } - - void drop_all() - { - std::lock_guard lock(logger_map_mutex_); - loggers_.clear(); - default_logger_.reset(); - } + void set_level(level::level_enum log_level); + + void flush_on(level::level_enum log_level); + + void flush_every(std::chrono::seconds interval); + + void set_error_handler(void (*handler)(const std::string &msg)); + + void apply_all(const std::function)> &fun); + + void flush_all(); + + void drop(const std::string &logger_name); + + void drop_all(); // clean all resources and threads started by the registry - void shutdown() - { - { - std::lock_guard lock(flusher_mutex_); - periodic_flusher_.reset(); - } + void shutdown(); - drop_all(); - - { - std::lock_guard lock(tp_mutex_); - tp_.reset(); - } - } - - std::recursive_mutex &tp_mutex() - { - return tp_mutex_; - } - - void set_automatic_registration(bool automatic_regsistration) - { - std::lock_guard lock(logger_map_mutex_); - automatic_registration_ = automatic_regsistration; - } - - static registry &instance() - { - static registry s_instance; - return s_instance; - } + std::recursive_mutex &tp_mutex(); + + void set_automatic_registration(bool automatic_regsistration); + + static registry &instance(); private: - 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(); -#else - auto color_sink = std::make_shared(); -#endif - - const char *default_logger_name = ""; - default_logger_ = std::make_shared(default_logger_name, std::move(color_sink)); - loggers_[default_logger_name] = default_logger_; - -#endif // SPDLOG_DISABLE_DEFAULT_LOGGER - } - + registry(); ~registry() = default; - void throw_if_exists_(const std::string &logger_name) - { - if (loggers_.find(logger_name) != loggers_.end()) - { - throw spdlog_ex("logger with name '" + logger_name + "' already exists"); - } - } - - void register_logger_(std::shared_ptr new_logger) - { - auto logger_name = new_logger->name(); - throw_if_exists_(logger_name); - loggers_[logger_name] = std::move(new_logger); - } - + void throw_if_exists_(const std::string &logger_name); + void register_logger_(std::shared_ptr new_logger); std::mutex logger_map_mutex_, flusher_mutex_; std::recursive_mutex tp_mutex_; std::unordered_map> loggers_; std::unique_ptr formatter_; - level::level_enum level_ = spdlog::logger::default_level(); + level::level_enum level_ = level::info; level::level_enum flush_level_ = level::off; void (*err_handler_)(const std::string &msg); std::shared_ptr tp_; @@ -284,3 +103,7 @@ private: } // namespace details } // namespace spdlog + +#ifdef SPDLOG_HEADER_ONLY +#include "../src/registry.cpp" +#endif // SPDLOG_HEADER_ONLY diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index a70a7aa7..cc4c8a47 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -11,6 +11,7 @@ #include "spdlog/common.h" #include "spdlog/details/registry.h" +#include "spdlog/details/pattern_formatter.h" #include "spdlog/logger.h" #include "spdlog/version.h" diff --git a/src/registry.cpp b/src/registry.cpp new file mode 100644 index 00000000..51f184ed --- /dev/null +++ b/src/registry.cpp @@ -0,0 +1,259 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// +#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 +#include +#include +#include +#include + +namespace spdlog { +namespace details { + +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(); +#else + auto color_sink = std::make_shared(); +#endif + + const char *default_logger_name = ""; + default_logger_ = std::make_shared(default_logger_name, std::move(color_sink)); + loggers_[default_logger_name] = default_logger_; + +#endif // SPDLOG_DISABLE_DEFAULT_LOGGER +} +void registry::register_logger(std::shared_ptr new_logger) +{ + std::lock_guard lock(logger_map_mutex_); + register_logger_(std::move(new_logger)); +} + +void registry::initialize_logger(std::shared_ptr new_logger) +{ + std::lock_guard 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 registry::get(const std::string &logger_name) +{ + std::lock_guard lock(logger_map_mutex_); + auto found = loggers_.find(logger_name); + return found == loggers_.end() ? nullptr : found->second; +} + +std::shared_ptr registry::default_logger() +{ + std::lock_guard 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. +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. +void registry::set_default_logger(std::shared_ptr new_default_logger) +{ + std::lock_guard 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 registry::set_tp(std::shared_ptr tp) +{ + std::lock_guard lock(tp_mutex_); + tp_ = std::move(tp); +} + +std::shared_ptr registry::get_tp() +{ + std::lock_guard lock(tp_mutex_); + return tp_; +} + +// Set global formatter. Each sink in each logger will get a clone of this object +void registry::set_formatter(std::unique_ptr formatter) +{ + std::lock_guard lock(logger_map_mutex_); + formatter_ = std::move(formatter); + for (auto &l : loggers_) + { + l.second->set_formatter(formatter_->clone()); + } +} + +void registry::set_level(level::level_enum log_level) +{ + std::lock_guard lock(logger_map_mutex_); + for (auto &l : loggers_) + { + l.second->set_level(log_level); + } + level_ = log_level; +} + +void registry::flush_on(level::level_enum log_level) +{ + std::lock_guard lock(logger_map_mutex_); + for (auto &l : loggers_) + { + l.second->flush_on(log_level); + } + flush_level_ = log_level; +} + +void registry::flush_every(std::chrono::seconds interval) +{ + std::lock_guard lock(flusher_mutex_); + std::function clbk = std::bind(®istry::flush_all, this); + periodic_flusher_ = details::make_unique(clbk, interval); +} + +void registry::set_error_handler(void (*handler)(const std::string &msg)) +{ + std::lock_guard lock(logger_map_mutex_); + for (auto &l : loggers_) + { + l.second->set_error_handler(handler); + } + err_handler_ = handler; +} + +void registry::apply_all(const std::function)> &fun) +{ + std::lock_guard lock(logger_map_mutex_); + for (auto &l : loggers_) + { + fun(l.second); + } +} + +void registry::flush_all() +{ + std::lock_guard lock(logger_map_mutex_); + for (auto &l : loggers_) + { + l.second->flush(); + } +} + +void registry::drop(const std::string &logger_name) +{ + std::lock_guard lock(logger_map_mutex_); + loggers_.erase(logger_name); + if (default_logger_ && default_logger_->name() == logger_name) + { + default_logger_.reset(); + } +} + +void registry::drop_all() +{ + std::lock_guard lock(logger_map_mutex_); + loggers_.clear(); + default_logger_.reset(); +} + +// clean all resources and threads started by the registry +void registry::shutdown() +{ + { + std::lock_guard lock(flusher_mutex_); + periodic_flusher_.reset(); + } + + drop_all(); + + { + std::lock_guard lock(tp_mutex_); + tp_.reset(); + } +} + +std::recursive_mutex ®istry::tp_mutex() +{ + return tp_mutex_; +} + +void registry::set_automatic_registration(bool automatic_regsistration) +{ + std::lock_guard lock(logger_map_mutex_); + automatic_registration_ = automatic_regsistration; +} + +registry ®istry::instance() +{ + static registry s_instance; + return s_instance; +} + +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"); + } +} + +void registry::register_logger_(std::shared_ptr new_logger) +{ + auto logger_name = new_logger->name(); + throw_if_exists_(logger_name); + loggers_[logger_name] = std::move(new_logger); +} +} // namespace details +} // namespace spdlog From 4dd1a24d0b8894df6f832345fc703f95d4fd4dd4 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 6 Apr 2019 01:25:33 +0300 Subject: [PATCH 062/157] wip static lib --- example/example.cpp | 7 +++++-- include/spdlog/details/registry.h | 5 +---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 01227247..68228ff3 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -14,6 +14,9 @@ spdlog::logger *get_logger(); int main(int, char *[]) { - auto *l = get_logger(); - l->info("HEllo {}", "HG FS"); + int x = 4; + spdlog::info("HELLO {}", "st at ic"); + spdlog::warn("HELLO {}*{} = {}", x, x, x*x); + /*auto *l = get_logger(); + l->info("HEllo {}", "HG FS");*/ } \ No newline at end of file diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 7a1ad1f2..24e72e2f 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -34,18 +34,15 @@ public: void register_logger(std::shared_ptr new_logger); void initialize_logger(std::shared_ptr new_logger); - std::shared_ptr get(const std::string &logger_name); - + std::shared_ptr get(const std::string &logger_name); std::shared_ptr default_logger(); - // Return raw ptr to the default logger. // To be used directly by the spdlog default api (e.g. spdlog::info) // This make the default API faster, but cannot be used concurrently with set_default_logger(). // e.g do not call set_default_logger() from one thread while calling spdlog::info() from another. logger *get_default_raw(); - // set default logger. // default logger is stored in default_logger_ (for faster retrieval) and in the loggers_ map. void set_default_logger(std::shared_ptr new_default_logger); From 9716ff69c4037bd758dedf6755590d2212599c4d Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 6 Apr 2019 01:31:10 +0300 Subject: [PATCH 063/157] added inline statemetns --- src/pattern_formatter.cpp | 16 ++++++------- src/registry.cpp | 48 +++++++++++++++++++-------------------- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/src/pattern_formatter.cpp b/src/pattern_formatter.cpp index b3037480..810d8a23 100644 --- a/src/pattern_formatter.cpp +++ b/src/pattern_formatter.cpp @@ -960,7 +960,7 @@ private: } // namespace details - pattern_formatter::pattern_formatter( + SPDLOG_INLINE pattern_formatter::pattern_formatter( std::string pattern, pattern_time_type time_type, std::string eol) : pattern_(std::move(pattern)) , eol_(std::move(eol)) @@ -972,7 +972,7 @@ private: } // use by default full formatter for if pattern is not given - pattern_formatter::pattern_formatter(pattern_time_type time_type, std::string eol) + SPDLOG_INLINE pattern_formatter::pattern_formatter(pattern_time_type time_type, std::string eol) : pattern_("%+") , eol_(std::move(eol)) , pattern_time_type_(time_type) @@ -983,12 +983,12 @@ private: } - std::unique_ptr pattern_formatter::clone() const + SPDLOG_INLINE std::unique_ptr pattern_formatter::clone() const { return details::make_unique(pattern_, pattern_time_type_, eol_); } - void pattern_formatter::format(const details::log_msg &msg, fmt::memory_buffer &dest) + SPDLOG_INLINE void pattern_formatter::format(const details::log_msg &msg, fmt::memory_buffer &dest) { #ifndef SPDLOG_NO_DATETIME auto secs = std::chrono::duration_cast(msg.time.time_since_epoch()); @@ -1006,7 +1006,7 @@ private: details::fmt_helper::append_string_view(eol_, dest); } - std::tm pattern_formatter::get_time_(const details::log_msg &msg) + SPDLOG_INLINE std::tm pattern_formatter::get_time_(const details::log_msg &msg) { if (pattern_time_type_ == pattern_time_type::local) { @@ -1015,7 +1015,7 @@ private: return details::os::gmtime(log_clock::to_time_t(msg.time)); } - void pattern_formatter::handle_flag_(char flag, details::padding_info padding) + SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_info padding) { switch (flag) { @@ -1183,7 +1183,7 @@ private: // Extract given pad spec (e.g. %8X) // Advance the given it pass the end of the padding spec found (if any) // Return padding. - details::padding_info pattern_formatter::handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end) + SPDLOG_INLINE details::padding_info pattern_formatter::handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end) { using details::padding_info; using details::scoped_pad; @@ -1223,7 +1223,7 @@ private: return details::padding_info{std::min(width, max_width), side}; } - void pattern_formatter::compile_pattern_(const std::string &pattern) + SPDLOG_INLINE void pattern_formatter::compile_pattern_(const std::string &pattern) { auto end = pattern.end(); std::unique_ptr user_chars; diff --git a/src/registry.cpp b/src/registry.cpp index 51f184ed..b4487b4a 100644 --- a/src/registry.cpp +++ b/src/registry.cpp @@ -30,7 +30,7 @@ namespace spdlog { namespace details { -registry::registry() +SPDLOG_INLINE registry::registry() : formatter_(new pattern_formatter()) , level_(spdlog::logger::default_level()) { @@ -49,13 +49,13 @@ registry::registry() #endif // SPDLOG_DISABLE_DEFAULT_LOGGER } -void registry::register_logger(std::shared_ptr new_logger) +SPDLOG_INLINE void registry::register_logger(std::shared_ptr new_logger) { std::lock_guard lock(logger_map_mutex_); register_logger_(std::move(new_logger)); } -void registry::initialize_logger(std::shared_ptr new_logger) +SPDLOG_INLINE void registry::initialize_logger(std::shared_ptr new_logger) { std::lock_guard lock(logger_map_mutex_); new_logger->set_formatter(formatter_->clone()); @@ -74,14 +74,14 @@ void registry::initialize_logger(std::shared_ptr new_logger) } } -std::shared_ptr registry::get(const std::string &logger_name) +SPDLOG_INLINE std::shared_ptr registry::get(const std::string &logger_name) { std::lock_guard lock(logger_map_mutex_); auto found = loggers_.find(logger_name); return found == loggers_.end() ? nullptr : found->second; } -std::shared_ptr registry::default_logger() +SPDLOG_INLINE std::shared_ptr registry::default_logger() { std::lock_guard lock(logger_map_mutex_); return default_logger_; @@ -91,14 +91,14 @@ std::shared_ptr registry::default_logger() // To be used directly by the spdlog default api (e.g. spdlog::info) // This make the default API faster, but cannot be used concurrently with set_default_logger(). // e.g do not call set_default_logger() from one thread while calling spdlog::info() from another. -logger *registry::get_default_raw() +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. -void registry::set_default_logger(std::shared_ptr new_default_logger) +SPDLOG_INLINE void registry::set_default_logger(std::shared_ptr new_default_logger) { std::lock_guard lock(logger_map_mutex_); // remove previous default logger from the map @@ -113,20 +113,20 @@ void registry::set_default_logger(std::shared_ptr new_default_logger) default_logger_ = std::move(new_default_logger); } -void registry::set_tp(std::shared_ptr tp) +SPDLOG_INLINE void registry::set_tp(std::shared_ptr tp) { std::lock_guard lock(tp_mutex_); tp_ = std::move(tp); } -std::shared_ptr registry::get_tp() +SPDLOG_INLINE std::shared_ptr registry::get_tp() { std::lock_guard lock(tp_mutex_); return tp_; } // Set global formatter. Each sink in each logger will get a clone of this object -void registry::set_formatter(std::unique_ptr formatter) +SPDLOG_INLINE void registry::set_formatter(std::unique_ptr formatter) { std::lock_guard lock(logger_map_mutex_); formatter_ = std::move(formatter); @@ -136,7 +136,7 @@ void registry::set_formatter(std::unique_ptr formatter) } } -void registry::set_level(level::level_enum log_level) +SPDLOG_INLINE void registry::set_level(level::level_enum log_level) { std::lock_guard lock(logger_map_mutex_); for (auto &l : loggers_) @@ -146,7 +146,7 @@ void registry::set_level(level::level_enum log_level) level_ = log_level; } -void registry::flush_on(level::level_enum log_level) +SPDLOG_INLINE void registry::flush_on(level::level_enum log_level) { std::lock_guard lock(logger_map_mutex_); for (auto &l : loggers_) @@ -156,14 +156,14 @@ void registry::flush_on(level::level_enum log_level) flush_level_ = log_level; } -void registry::flush_every(std::chrono::seconds interval) +SPDLOG_INLINE void registry::flush_every(std::chrono::seconds interval) { std::lock_guard lock(flusher_mutex_); std::function clbk = std::bind(®istry::flush_all, this); periodic_flusher_ = details::make_unique(clbk, interval); } -void registry::set_error_handler(void (*handler)(const std::string &msg)) +SPDLOG_INLINE void registry::set_error_handler(void (*handler)(const std::string &msg)) { std::lock_guard lock(logger_map_mutex_); for (auto &l : loggers_) @@ -173,7 +173,7 @@ void registry::set_error_handler(void (*handler)(const std::string &msg)) err_handler_ = handler; } -void registry::apply_all(const std::function)> &fun) +SPDLOG_INLINE void registry::apply_all(const std::function)> &fun) { std::lock_guard lock(logger_map_mutex_); for (auto &l : loggers_) @@ -182,7 +182,7 @@ void registry::apply_all(const std::function) } } -void registry::flush_all() +SPDLOG_INLINE void registry::flush_all() { std::lock_guard lock(logger_map_mutex_); for (auto &l : loggers_) @@ -191,7 +191,7 @@ void registry::flush_all() } } -void registry::drop(const std::string &logger_name) +SPDLOG_INLINE void registry::drop(const std::string &logger_name) { std::lock_guard lock(logger_map_mutex_); loggers_.erase(logger_name); @@ -201,7 +201,7 @@ void registry::drop(const std::string &logger_name) } } -void registry::drop_all() +SPDLOG_INLINE void registry::drop_all() { std::lock_guard lock(logger_map_mutex_); loggers_.clear(); @@ -209,7 +209,7 @@ void registry::drop_all() } // clean all resources and threads started by the registry -void registry::shutdown() +SPDLOG_INLINE void registry::shutdown() { { std::lock_guard lock(flusher_mutex_); @@ -224,24 +224,24 @@ void registry::shutdown() } } -std::recursive_mutex ®istry::tp_mutex() +SPDLOG_INLINE std::recursive_mutex ®istry::tp_mutex() { return tp_mutex_; } -void registry::set_automatic_registration(bool automatic_regsistration) +SPDLOG_INLINE void registry::set_automatic_registration(bool automatic_regsistration) { std::lock_guard lock(logger_map_mutex_); automatic_registration_ = automatic_regsistration; } -registry ®istry::instance() +SPDLOG_INLINE registry ®istry::instance() { static registry s_instance; return s_instance; } -void registry::throw_if_exists_(const std::string &logger_name) +SPDLOG_INLINE void registry::throw_if_exists_(const std::string &logger_name) { if (loggers_.find(logger_name) != loggers_.end()) { @@ -249,7 +249,7 @@ void registry::throw_if_exists_(const std::string &logger_name) } } -void registry::register_logger_(std::shared_ptr new_logger) +SPDLOG_INLINE void registry::register_logger_(std::shared_ptr new_logger) { auto logger_name = new_logger->name(); throw_if_exists_(logger_name); From d12a858897f35776960103f4c730440d46a6153e Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 6 Apr 2019 01:37:27 +0300 Subject: [PATCH 064/157] some cleanup --- include/spdlog/common.h | 11 +++-------- src/sink.cpp | 2 -- 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 275ea23b..933589af 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -70,6 +70,7 @@ #endif #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) +using filename_t = std::wstring; #define SPDLOG_FILENAME_T(s) L##s SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) { @@ -77,6 +78,7 @@ SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) return c.to_bytes(filename); } #else +using filename_t = std::string; #define SPDLOG_FILENAME_T(s) s #endif @@ -210,14 +212,7 @@ private: 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 { diff --git a/src/sink.cpp b/src/sink.cpp index 0d308748..7f9e84e5 100644 --- a/src/sink.cpp +++ b/src/sink.cpp @@ -27,5 +27,3 @@ SPDLOG_INLINE spdlog::level::level_enum spdlog::sinks::sink::level() const { return static_cast(level_.load(std::memory_order_relaxed)); } - - From b7ecec0c238be4868f0ad678174eb9a5808d7be2 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 6 Apr 2019 01:37:51 +0300 Subject: [PATCH 065/157] some cleanup --- include/spdlog/common.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 933589af..105415dd 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -212,8 +212,6 @@ private: std::string msg_; }; - - struct source_loc { SPDLOG_CONSTEXPR source_loc() From 7ab6fd9db63d0328054bd5aaf3bc712ed3bf3867 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 6 Apr 2019 01:37:51 +0300 Subject: [PATCH 066/157] source_loc change line to int --- include/spdlog/common.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 933589af..105415dd 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -212,8 +212,6 @@ private: std::string msg_; }; - - struct source_loc { SPDLOG_CONSTEXPR source_loc() From 97f9cc4bc079f7c1ee581f6e4757e0a778208dd0 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 6 Apr 2019 01:44:03 +0300 Subject: [PATCH 067/157] some cleanup --- example/example.cpp | 3 ++- include/spdlog/common.h | 17 ++++++----------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 68228ff3..03d1a0a9 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -16,7 +16,8 @@ int main(int, char *[]) { int x = 4; spdlog::info("HELLO {}", "st at ic"); - spdlog::warn("HELLO {}*{} = {}", x, x, x*x); + spdlog::warn("HELLO {} *{} = {}", x, x, x*x); + /*auto *l = get_logger(); l->info("HEllo {}", "HG FS");*/ } \ No newline at end of file diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 105415dd..a44dc00c 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -13,6 +13,7 @@ #include #include #include +#include #if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) #include @@ -27,7 +28,6 @@ #define SPDLOG_INLINE #endif - // visual studio upto 2013 does not support noexcept nor constexpr #if defined(_MSC_VER) && (_MSC_VER < 1900) #define SPDLOG_NOEXCEPT throw() @@ -214,15 +214,10 @@ private: struct source_loc { - SPDLOG_CONSTEXPR source_loc() - : filename{""} - , line{0} - , funcname{""} - { - } + SPDLOG_CONSTEXPR source_loc() = default; SPDLOG_CONSTEXPR source_loc(const char *filename_in, int line_in, const char *funcname_in) : filename{filename_in} - , line{static_cast(line_in)} + , line{line_in} , funcname{funcname_in} { } @@ -231,9 +226,9 @@ struct source_loc { return line == 0; } - const char *filename; - uint32_t line; - const char *funcname; + const char *filename{nullptr}; + int line{0}; + const char *funcname{nullptr}; }; namespace details { From 6bec53dcd2fd49edcf159661701fbe71f226e924 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sat, 6 Apr 2019 02:14:08 +0300 Subject: [PATCH 068/157] Update logger.h --- include/spdlog/logger.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 6b6c736b..228c857c 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -164,10 +164,9 @@ public: } try { - using details::fmt_helper::to_string_view; fmt::memory_buffer buf; fmt::format_to(buf, "{}", msg); - details::log_msg log_msg(loc, &name_, lvl, to_string_view(buf)); + details::log_msg log_msg(loc, &name_, lvl, lvl, string_view_t(buf.data(), buf.size())); sink_it_(log_msg); } catch (const std::exception &ex) From 7e29c483798283668836f9592c90135b2e820525 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 6 Apr 2019 12:57:09 +0300 Subject: [PATCH 069/157] removed spdlite --- CMakeLists.txt | 5 - example/example.cpp | 8 +- spdlite/CMakeLists.txt | 14 -- spdlite/example/CMakeLists.txt | 11 -- spdlite/example/create_logger.cpp | 16 -- spdlite/example/example.cpp | 12 -- spdlite/include/spdlite/default_api.h | 95 ---------- spdlite/include/spdlite/spdlite.h | 218 ----------------------- spdlite/include/spdlite/spdlite_macros.h | 75 -------- spdlite/src/spdlite.cpp | 155 ---------------- spdlite/src/spdlite_default_api.cpp | 63 ------- 11 files changed, 3 insertions(+), 669 deletions(-) delete mode 100644 spdlite/CMakeLists.txt delete mode 100644 spdlite/example/CMakeLists.txt delete mode 100644 spdlite/example/create_logger.cpp delete mode 100644 spdlite/example/example.cpp delete mode 100644 spdlite/include/spdlite/default_api.h delete mode 100644 spdlite/include/spdlite/spdlite.h delete mode 100644 spdlite/include/spdlite/spdlite_macros.h delete mode 100644 spdlite/src/spdlite.cpp delete mode 100644 spdlite/src/spdlite_default_api.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9aa992cf..843a522f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,7 +54,6 @@ option(SPDLOG_BUILD_BENCH "Build benchmarks (Requires https://github.com/google/ option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) -option(SPDLOG_BUILD_LITE "Build spdlog lite" ${SPDLOG_MASTER_PROJECT}) if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) @@ -88,10 +87,6 @@ if(SPDLOG_BUILD_BENCH) add_subdirectory(bench) endif() -if(SPDLOG_BUILD_LITE) - add_subdirectory(spdlite) -endif() - #--------------------------------------------------------------------------------------- # Install/export targets and files #--------------------------------------------------------------------------------------- diff --git a/example/example.cpp b/example/example.cpp index 03d1a0a9..e740afb6 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -15,9 +15,7 @@ spdlog::logger *get_logger(); int main(int, char *[]) { int x = 4; - spdlog::info("HELLO {}", "st at ic"); - spdlog::warn("HELLO {} *{} = {}", x, x, x*x); - - /*auto *l = get_logger(); - l->info("HEllo {}", "HG FS");*/ + + auto *l = get_logger(); + l->info("HEllo { }", "HG FS"); } \ No newline at end of file diff --git a/spdlite/CMakeLists.txt b/spdlite/CMakeLists.txt deleted file mode 100644 index e2b58148..00000000 --- a/spdlite/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -cmake_minimum_required(VERSION 3.1) -project(spdlite) - -include_directories(${PROJECT_SOURCE_DIR}/include) -file(GLOB SRC_FILES ${PROJECT_SOURCE_DIR}/src/*.cpp) -file(GLOB HEADER_FILES ${PROJECT_SOURCE_DIR}/include/*.h) - -add_library(spdlite ${SRC_FILES} ${HEADER_FILES}) - -target_link_libraries(spdlite spdlog::spdlog) - -add_subdirectory(example) - - diff --git a/spdlite/example/CMakeLists.txt b/spdlite/example/CMakeLists.txt deleted file mode 100644 index bb0e8244..00000000 --- a/spdlite/example/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -project(spdlite-example CXX) - -set(LITE_SOURCES example.cpp create_logger.cpp) - -add_executable(${PROJECT_NAME} ${LITE_SOURCES}) - -find_package(Threads) -target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) -target_link_libraries(${PROJECT_NAME} PRIVATE spdlite) - - diff --git a/spdlite/example/create_logger.cpp b/spdlite/example/create_logger.cpp deleted file mode 100644 index b1ab0bf3..00000000 --- a/spdlite/example/create_logger.cpp +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright(c) 2015-present Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) - -#include "spdlite/spdlite.h" -#include "spdlog/spdlog.h" -#include "spdlog/sinks/basic_file_sink.h" - - -#define UNUSED(x) (void)(x) - -// example of creating lite logger with console and file sink -spdlite::logger create_logger(void *ctx) -{ - UNUSED(ctx); - return spdlite::logger(spdlog::basic_logger_mt("logger-name", "log.txt", true)); -} diff --git a/spdlite/example/example.cpp b/spdlite/example/example.cpp deleted file mode 100644 index 47fdf06e..00000000 --- a/spdlite/example/example.cpp +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright(c) 2015-present Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) - -#include "spdlite/spdlite.h" -#include "spdlite/default_api.h" - -#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_TRACE -#include "spdlite/spdlite_macros.h" -int main() -{ - SPDLITE_TRACE("SOME INFO {}", 123); -} \ No newline at end of file diff --git a/spdlite/include/spdlite/default_api.h b/spdlite/include/spdlite/default_api.h deleted file mode 100644 index 64e44137..00000000 --- a/spdlite/include/spdlite/default_api.h +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright(c) 2015-present Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) - -#pragma once - -#include "spdlite.h" -namespace spdlite -{ -// -// spdlite namespace functions - forward the calls to the default_logger. -// -spdlite::logger &default_logger(); - -template -inline void trace(const char *fmt, const Args &... args) -{ - default_logger().trace(fmt, args...); -} - -template -inline void debug(const char *fmt, const Args &... args) -{ - default_logger().debug(fmt, args...); -} - -template -inline void info(const char *fmt, const Args &... args) -{ - default_logger().info(fmt, args...); -} - -template -inline void warn(const char *fmt, const Args &... args) -{ - default_logger().warn(fmt, args...); -} - -template -inline void error(const char *fmt, const Args &... args) -{ - default_logger().error(fmt, args...); -} - -template -inline void critical(const char *fmt, const Args &... args) -{ - default_logger().critical(fmt, args...); -} - -// string view convertable -template -inline void trace(const T &msg) -{ - default_logger().trace(msg); -} - -template -inline void debug(const T &msg) -{ - default_logger().debug(msg); -} - -template -inline void info(const T &msg) -{ - default_logger().info(msg); -} - -template -inline void warn(const T &msg) -{ - default_logger().warn(msg); -} - -template -inline void error(const T &msg) -{ - default_logger().error(msg); -} - -template -inline void critical(const T &msg) -{ - default_logger().critical(msg); -} - -void log_printf(spdlite::level lvl, const char *format, va_list args); -void trace_printf(const char *format, ...); -void debug_printf(const char *format, ...); -void info_printf(const char *format, ...); -void warn_printf(const char *format, ...); -void error_printf(const char *format, ...); -void critical_printf(const char *format, ...); - -} diff --git a/spdlite/include/spdlite/spdlite.h b/spdlite/include/spdlite/spdlite.h deleted file mode 100644 index 762c0b41..00000000 --- a/spdlite/include/spdlite/spdlite.h +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright(c) 2015-present Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) - -#pragma once - -// lite logger - a pimpl around spdlog::logger shared_ptr: -// much faster compile times. -// can be used as lib or separate compilation unit. -// very cheap copy and move. -// supports printf format for even faster compile (by avoiding variadic templates). -// -// see lite-example/ for usage. - -#include -#include -#include "spdlog/fmt/fmt.h" - -namespace spdlog { -class logger; -} -namespace spdlite { - -// string_view type - either std::string_view or fmt::string_view (pre c++17) -#if defined(FMT_USE_STD_STRING_VIEW) -using string_view_t = std::string_view; -#else -using string_view_t = fmt::string_view; -#endif - -enum class level -{ - trace, - debug, - info, - warn, - err, - critical, - off -}; - -class logger -{ -public: - explicit logger(std::shared_ptr impl); - // logger() = default; //logger with nullptr impl - logger(const logger &) = default; - logger(logger &&) = default; - logger &operator=(const logger &) = default; - - ~logger() = default; - - void set_impl(std::shared_ptr impl); - bool should_log(spdlite::level lvl) const noexcept; - - template - void log(spdlite::level lvl, const char *fmt, const Args &... args) - { - if (!should_log(lvl)) - { - return; - } - fmt::memory_buffer formatted_buf; - fmt::format_to(formatted_buf, fmt, args...); - log_formatted_(lvl, formatted_buf); - } - - // log string view - void log(spdlite::level lvl, const string_view_t &sv); - - // - // trace - // - - void trace(const char *msg) - { - log(spdlite::level::trace, string_view_t(msg)); - } - - template - void trace(const T &msg) - { - log(spdlite::level::trace, string_view_t(msg)); - } - - template - void trace(const char *fmt, const Args &... args) - { - log(spdlite::level::trace, fmt, args...); - } - - // - // debug - // - void debug(const char *msg) - { - log(spdlite::level::debug, string_view_t(msg)); - } - - template - void debug(const T &msg) - { - log(spdlite::level::debug, string_view_t(msg)); - } - - template - void debug(const char *fmt, const Args &... args) - { - log(spdlite::level::debug, fmt, args...); - } - - // info - void info(const char *msg) - { - log(spdlite::level::info, string_view_t(msg)); - } - - template - void info(const T &msg) - { - log(spdlite::level::info, string_view_t(msg)); - } - - template - void info(const char *fmt, const Args &... args) - { - log(spdlite::level::info, fmt, args...); - } - - // warn - void warn(const char *msg) - { - log(spdlite::level::warn, string_view_t(msg)); - } - - template - void warn(const T &msg) - { - log(spdlite::level::warn, string_view_t(msg)); - } - - template - void warn(const char *fmt, const Args &... args) - { - log(spdlite::level::warn, fmt, args...); - } - - // error - void error(const char *msg) - { - log(spdlite::level::err, string_view_t(msg)); - } - - template - void error(const T &msg) - { - log(spdlite::level::err, string_view_t(msg)); - } - - template - void error(const char *fmt, const Args &... args) - { - log(spdlite::level::err, fmt, args...); - } - - // critical - void critical(const char *msg) - { - log(spdlite::level::critical, string_view_t(msg)); - } - - template - void critical(const T &msg) - { - log(spdlite::level::critical, string_view_t(msg)); - } - - template - void critical(const char *fmt, const Args &... args) - { - log(spdlite::level::critical, fmt, args...); - } - - // printf formatting - void log_printf(spdlite::level lvl, const char *format, va_list args); - void trace_printf(const char *format, ...); - void debug_printf(const char *format, ...); - void info_printf(const char *format, ...); - void warn_printf(const char *format, ...); - void error_printf(const char *format, ...); - void critical_printf(const char *format, ...); - - // setters/getters - void set_level(spdlite::level level) noexcept; - void set_pattern(std::string pattern) noexcept; - spdlite::level level() const noexcept; - std::string name() const noexcept; - spdlite::level flush_level() const noexcept; - - // flush - void flush(); - void flush_on(spdlite::level log_level); - - // clone with new name - spdlite::logger clone(std::string logger_name); - - static spdlite::logger &default_logger(); - -protected: - std::shared_ptr impl_; - void log_formatted_(spdlite::level lvl, const fmt::memory_buffer &formatted); -}; - - -} // namespace spdlite - -// user implemented factory to create lite logger -// implement it in a seperated and dedicated compilation unit for fast compiles. -spdlite::logger create_logger(void *ctx = nullptr); diff --git a/spdlite/include/spdlite/spdlite_macros.h b/spdlite/include/spdlite/spdlite_macros.h deleted file mode 100644 index 58c4066d..00000000 --- a/spdlite/include/spdlite/spdlite_macros.h +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright(c) 2015-present Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) - -#pragma once -// -// enable/disable log calls at compile time according to global level. -// -// define SPDLITE_ACTIVE_LEVEL to one of those (before including lite.h): - - -#define SPDLITE_LEVEL_TRACE 0 -#define SPDLITE_LEVEL_DEBUG 1 -#define SPDLITE_LEVEL_INFO 2 -#define SPDLITE_LEVEL_WARN 3 -#define SPDLITE_LEVEL_ERROR 4 -#define SPDLITE_LEVEL_CRITICAL 5 -#define SPDLITE_LEVEL_OFF 6 - -#define SPDLITE_LOGGER_CALL(logger, level, ...) logger.log(level, __VA_ARGS__) - -// default level is info -#ifndef SPDLITE_ACTIVE_LEVEL -#define SPDLITE_ACTIVE_LEVEL SPDLITE_LEVEL_INFO -#endif - -static_assert(SPDLITE_ACTIVE_LEVEL >= SPDLITE_LEVEL_TRACE && SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_OFF, "SPDLITE_ACTIVE_LEVEL"); - - -#if SPDLITE_ACTIVE_LEVEL == SPDLITE_LEVEL_TRACE -#define SPDLITE_LOGGER_TRACE(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::trace, __VA_ARGS__) -#define SPDLITE_TRACE(...) SPDLITE_LOGGER_TRACE(spdlite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_TRACE(logger, ...) (void)0 -#define SPDLITE_TRACE(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_DEBUG -#define SPDLITE_LOGGER_DEBUG(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::debug, __VA_ARGS__) -#define SPDLITE_DEBUG(...) SPDLITE_LOGGER_DEBUG(spdlite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_DEBUG(logger, ...) (void)0 -#define SPDLITE_DEBUG(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_INFO -#define SPDLITE_LOGGER_INFO(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::info, __VA_ARGS__) -#define SPDLITE_INFO(...) SPDLITE_LOGGER_INFO(spdlite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_INFO(logger, ...) (void)0 -#define SPDLITE_INFO(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_WARN -#define SPDLITE_LOGGER_WARN(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::warn, __VA_ARGS__) -#define SPDLITE_WARN(...) SPDLITE_LOGGER_WARN(spdlite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_WARN(logger, ...) (void)0 -#define SPDLITE_WARN(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_ERROR -#define SPDLITE_LOGGER_ERROR(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::err, __VA_ARGS__) -#define SPDLITE_ERROR(...) SPDLITE_LOGGER_ERROR(spdlite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_ERROR(logger, ...) (void)0 -#define SPDLITE_ERROR(...) (void)0 -#endif - -#if SPDLITE_ACTIVE_LEVEL <= SPDLITE_LEVEL_CRITICAL -#define SPDLITE_LOGGER_CRITICAL(logger, ...) SPDLITE_LOGGER_CALL(logger, spdlite::level::critical, __VA_ARGS__) -#define SPDLITE_CRITICAL(...) SPDLITE_LOGGER_CRITICAL(spdlite::default_logger(), __VA_ARGS__) -#else -#define SPDLITE_LOGGER_CRITICAL(logger, ...) (void)0 -#define SPDLITE_CRITICAL(...) (void)0 -#endif diff --git a/spdlite/src/spdlite.cpp b/spdlite/src/spdlite.cpp deleted file mode 100644 index 1cc96101..00000000 --- a/spdlite/src/spdlite.cpp +++ /dev/null @@ -1,155 +0,0 @@ -// -// Copyright(c) 2019-present spdlog -// Distributed under the MIT License (http://opensource.org/licenses/MIT) -// - -#include "spdlite/spdlite.h" -#include "spdlog/spdlog.h" - -static spdlog::level::level_enum to_spdlog_level(spdlite::level level) -{ - return static_cast(level); -} - -static spdlite::level to_lite_level(spdlog::level::level_enum level) -{ - return static_cast(level); -} - -spdlite::logger::logger(std::shared_ptr impl) -{ - impl_ = std::move(impl); -} - -void spdlite::logger::set_impl(std::shared_ptr impl) -{ - impl_ = std::move(impl); -} - -bool spdlite::logger::should_log(spdlite::level level) const SPDLOG_NOEXCEPT -{ - auto spd_level = to_spdlog_level(level); - return impl_->should_log(spd_level); // TODO avoid the call using local level member? -} - -void spdlite::logger::log(spdlite::level lvl, const string_view_t &sv) -{ - auto spd_level = to_spdlog_level(lvl); - impl_->log(spd_level, sv); -} - -void spdlite::logger::log_printf(spdlite::level lvl, const char *format, va_list args) -{ - char buffer[256]; - auto size = vsnprintf(buffer, sizeof(buffer), format, args); - if (size < 0) - { - size = snprintf(buffer, sizeof(buffer), "invalid format (%s)", format); - } - log(lvl, string_view_t{buffer, static_cast(size)}); -} - -void spdlite::logger::trace_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::trace, format, args); - va_end(args); -} - -void spdlite::logger::debug_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::debug, format, args); - va_end(args); -} - -void spdlite::logger::info_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::info, format, args); - va_end(args); -} - -void spdlite::logger::warn_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::warn, format, args); - va_end(args); -} - -void spdlite::logger::error_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::err, format, args); - va_end(args); -} - -void spdlite::logger::critical_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(spdlite::level::critical, format, args); - va_end(args); -} - -void spdlite::logger::set_level(spdlite::level level) noexcept -{ - auto spd_level = to_spdlog_level(level); - impl_->set_level(spd_level); -} - -spdlite::level spdlite::logger::level() const noexcept -{ - return to_lite_level(impl_->level()); -} - -std::string spdlite::logger::name() const noexcept -{ - return impl_->name(); -} - -void spdlite::logger::flush() -{ - impl_->flush(); -} - -void spdlite::logger::flush_on(spdlite::level level) -{ - auto spd_level = to_spdlog_level(level); - impl_->flush_on(spd_level); -} - -spdlite::level spdlite::logger::flush_level() const noexcept -{ - return to_lite_level(impl_->flush_level()); -} - -// pattern -void spdlite::logger::set_pattern(std::string pattern) noexcept -{ - impl_->set_pattern(std::move(pattern)); -} - -spdlite::logger spdlite::logger::clone(std::string logger_name) -{ - return spdlite::logger(impl_->clone(std::move(logger_name))); -} - -void spdlite::logger::log_formatted_(spdlite::level lvl, const fmt::memory_buffer &formatted) -{ - auto spd_level = to_spdlog_level(lvl); - impl_->log(spd_level, spdlog::details::fmt_helper::to_string_view(formatted)); -} - -spdlite::logger &spdlite::logger::default_logger() -{ - static spdlite::logger default_inst_ = spdlite::logger(spdlog::default_logger()); - return default_inst_; -} - - diff --git a/spdlite/src/spdlite_default_api.cpp b/spdlite/src/spdlite_default_api.cpp deleted file mode 100644 index 73a0704d..00000000 --- a/spdlite/src/spdlite_default_api.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright(c) 2015-present Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) - -#include "spdlite/default_api.h" - -spdlite::logger &spdlite::default_logger() -{ - return spdlite::logger::default_logger(); -} - -// printf -void spdlite::log_printf(spdlite::level lvl, const char *format, va_list args) -{ - default_logger().log_printf(lvl, format, args); -} - -void spdlite::trace_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::trace, format, args); - va_end(args); -} - -void spdlite::debug_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::debug, format, args); - va_end(args); -} - -void spdlite::info_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::info, format, args); - va_end(args); -} - -void spdlite::warn_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::warn, format, args); - va_end(args); -} - -void spdlite::error_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::err, format, args); - va_end(args); -} - -void spdlite::critical_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - log_printf(level::critical, format, args); - va_end(args); -} \ No newline at end of file From 215b6aea95a0fd15d1b8c8a1c672918b7a75a7ab Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 6 Apr 2019 13:45:33 +0300 Subject: [PATCH 070/157] file_helper.cpp and filename_t fix --- include/spdlog/common.h | 17 ++-- include/spdlog/details/file_helper.h | 130 ++++---------------------- src/file_helper.cpp | 132 +++++++++++++++++++++++++++ 3 files changed, 161 insertions(+), 118 deletions(-) create mode 100644 src/file_helper.cpp diff --git a/include/spdlog/common.h b/include/spdlog/common.h index c7e20c2f..bb5ec94e 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -69,6 +69,15 @@ #define SPDLOG_FUNCTION __FUNCTION__ #endif + +namespace spdlog { + +class formatter; + +namespace sinks { +class sink; +} + #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) using filename_t = std::wstring; #define SPDLOG_FILENAME_T(s) L##s @@ -82,14 +91,6 @@ using filename_t = std::string; #define SPDLOG_FILENAME_T(s) s #endif -namespace spdlog { - -class formatter; - -namespace sinks { -class sink; -} - using log_clock = std::chrono::system_clock; using sink_ptr = std::shared_ptr; using sinks_init_list = std::initializer_list; diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index 8c1132d9..1a352c6f 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -5,110 +5,36 @@ #pragma once -// Helper class for file sinks. -// When failing to open a file, retry several times(5) with a delay interval(10 ms). -// Throw spdlog_ex exception on errors. - -#include "spdlog/details/log_msg.h" -#include "spdlog/details/os.h" - -#include -#include -#include -#include -#include +#include "spdlog/common.h" #include namespace spdlog { 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 { - public: const int open_tries = 5; const int open_interval = 10; - explicit file_helper() = default; file_helper(const file_helper &) = delete; file_helper &operator=(const file_helper &) = delete; + ~file_helper(); - ~file_helper() - { - close(); - } - - void open(const filename_t &fname, bool truncate = false) - { - close(); - auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab"); - _filename = fname; - for (int tries = 0; tries < open_tries; ++tries) - { - if (!os::fopen_s(&fd_, fname, mode)) - { - return; - } - - 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); - } - + void open(const filename_t &fname, bool truncate = false); + void reopen(bool truncate); + void flush(); + void close(); + void write(const fmt::memory_buffer &buf); + size_t size() const; + const filename_t &filename() const; + static bool file_exists(const filename_t &fname); + // // return file path and its extension: // @@ -122,27 +48,7 @@ public: // ".mylog" => (".mylog". "") // "my_folder/.mylog" => ("my_folder/.mylog", "") // "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt") - static std::tuple split_by_extension(const spdlog::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)); - } + static std::tuple split_by_extension(const filename_t &fname); private: std::FILE *fd_{nullptr}; @@ -150,3 +56,7 @@ private: }; } // namespace details } // namespace spdlog + +#ifdef SPDLOG_HEADER_ONLY +#include "../../../src/file_helper.cpp" +#endif // ! SPDLOG_HEADER_ONLY diff --git a/src/file_helper.cpp b/src/file_helper.cpp new file mode 100644 index 00000000..781931b0 --- /dev/null +++ b/src/file_helper.cpp @@ -0,0 +1,132 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/details/file_helper.h" + +#endif +#include "spdlog/details/os.h" + +#include +#include +#include +#include +#include +#include + +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 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 From c1c6e6265c58fb99f7a2cb4b1d5c2a7e111e59b5 Mon Sep 17 00:00:00 2001 From: gabime Date: Tue, 9 Apr 2019 16:42:44 +0300 Subject: [PATCH 071/157] Fixed header only build --- include/spdlog/details/log_msg.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 5d6f7ad1..86918fd4 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -32,3 +32,7 @@ struct log_msg }; } // namespace details } // namespace spdlog + +#ifdef SPDLOG_HEADER_ONLY +#include "../../../src/log_msg.cpp" +#endif // SPDLOG_HEADER_ONLY From 13db9d945232bcc16b86e9acd226d1bd5a70033e Mon Sep 17 00:00:00 2001 From: gabime Date: Tue, 9 Apr 2019 16:46:17 +0300 Subject: [PATCH 072/157] Fix build --- include/spdlog/logger.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 228c857c..58ae20e6 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -166,7 +166,7 @@ public: { fmt::memory_buffer buf; fmt::format_to(buf, "{}", msg); - details::log_msg log_msg(loc, &name_, lvl, lvl, string_view_t(buf.data(), buf.size())); + details::log_msg log_msg(loc, &name_, lvl, string_view_t(buf.data(), buf.size())); sink_it_(log_msg); } catch (const std::exception &ex) From 3e378f009d992dab6cec928f08a3e990860f54dd Mon Sep 17 00:00:00 2001 From: gabime Date: Tue, 9 Apr 2019 16:49:19 +0300 Subject: [PATCH 073/157] Fixed build --- src/logger.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/logger.cpp b/src/logger.cpp index 4ef4cc88..d3200537 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -159,7 +159,7 @@ SPDLOG_INLINE bool spdlog::logger::should_flush_(const spdlog::details::log_msg return (msg.level >= flush_level) && (msg.level != level::off); } -void spdlog::logger::err_handler_(const std::string &msg) +SPDLOG_INLINE void spdlog::logger::err_handler_(const std::string &msg) { if (custom_err_handler_) { From baefe0b3f6c3ad5db3b77991e5354298626c053b Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 26 Apr 2019 15:11:01 +0300 Subject: [PATCH 074/157] wip --- CMakeLists.txt | 92 ++++--------------------- example/example.cpp | 19 +++--- include/spdlog/async_logger.h | 12 ++-- src/async_logger.cpp | 123 ++++++++++++++++++++++++++++++++++ src/os.cpp | 2 - tests/test_errors.cpp | 2 +- 6 files changed, 154 insertions(+), 96 deletions(-) create mode 100644 src/async_logger.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 843a522f..20669a00 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,3 +1,4 @@ + # # Copyright(c) 2015 Ruslan Baratov. # Distributed under the MIT License (http://opensource.org/licenses/MIT) @@ -6,7 +7,6 @@ cmake_minimum_required(VERSION 3.1) project(spdlog VERSION 1.3.1 LANGUAGES CXX) include(CMakeDependentOption) -include(GNUInstallDirs) #--------------------------------------------------------------------------------------- # set default build to release @@ -40,8 +40,6 @@ include(cmake/sanitizers.cmake) #--------------------------------------------------------------------------------------- # spdlog target #--------------------------------------------------------------------------------------- -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) @@ -49,12 +47,24 @@ if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) set(SPDLOG_MASTER_PROJECT ON) endif() +option(SPDLOG_HEADER_ONLY "Header only version. Turn OFF to build as static lib" OFF) 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_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) +if(SPDLOG_HEADER_ONLY) + add_definitions(-DSPDLOG_HEADER_ONLY) + add_library(spdlog INTERFACE) + add_library(spdlog::spdlog ALIAS spdlog) + +else() + remove_definitions(-DSPDLOG_HEADER_ONLY) + file(GLOB SRC_FILES ${PROJECT_SOURCE_DIR}/src/*.cpp) + add_library(spdlog ${SRC_FILES} ) + add_library(spdlog::spdlog ALIAS spdlog) +endif() if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) find_package(fmt REQUIRED CONFIG) @@ -62,9 +72,8 @@ endif() target_include_directories( spdlog - INTERFACE + PUBLIC "$" - "$" ) if(SPDLOG_FMT_EXTERNAL) @@ -86,76 +95,3 @@ endif() if(SPDLOG_BUILD_BENCH) add_subdirectory(bench) endif() - -#--------------------------------------------------------------------------------------- -# Install/export targets and files -#--------------------------------------------------------------------------------------- -if(SPDLOG_INSTALL) - # set files and directories - set(config_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") - set(include_install_dir "${CMAKE_INSTALL_INCLUDEDIR}") - set(pkgconfig_install_dir "${CMAKE_INSTALL_LIBDIR}/pkgconfig") - set(version_config "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.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") - set(targets_export_name "${PROJECT_NAME}Targets") - set(namespace "${PROJECT_NAME}::") - - # generate package version file - include(CMakePackageConfigHelpers) - write_basic_package_version_file( - "${version_config}" COMPATIBILITY SameMajorVersion - ) - - # configure pkg config file - configure_file("cmake/spdlog.pc.in" "${pkg_config}" @ONLY) - # configure spdlogConfig.cmake file - configure_file("cmake/Config.cmake.in" "${project_config}" @ONLY) - - # install targets - 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}) diff --git a/example/example.cpp b/example/example.cpp index e740afb6..616a4d20 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -7,15 +7,16 @@ // // -#include "spdlog/spdlog.h" -#include "spdlog/logger.h" -spdlog::logger *get_logger(); +#include "spdlog/spdlog.h" +#include "spdlog/async.h" +#include "spdlog/sinks/stdout_color_sinks.h" + int main(int, char *[]) -{ - int x = 4; - - auto *l = get_logger(); - l->info("HEllo { }", "HG FS"); -} \ No newline at end of file +{ + using spdlog::sinks::stderr_color_sink_mt; + auto logger = spdlog::create_async("async"); + logger->info("HEllo xsdsdfs {}", 123); + //spdlog::error("HEllo err {}", "HG FS"); +} diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index a7ecb787..3d1c9578 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -19,12 +19,8 @@ // Upon destruction, logs all remaining messages in the queue before // destructing.. -#include "spdlog/common.h" -#include "spdlog/logger.h" -#include -#include -#include +#include "spdlog/logger.h" namespace spdlog { @@ -70,4 +66,8 @@ private: }; } // namespace spdlog -#include "details/async_logger_impl.h" +#ifdef SPDLOG_HEADER_ONLY +#include "../src/async_logger.cpp" +#endif // SPDLOG_HEADER_ONLY + + diff --git a/src/async_logger.cpp b/src/async_logger.cpp new file mode 100644 index 00000000..94e8e546 --- /dev/null +++ b/src/async_logger.cpp @@ -0,0 +1,123 @@ +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/async_logger.h" +#endif + + +// async logger implementation +// uses a thread pool to perform the actual logging + +#include "spdlog/sinks/sink.h" +#include "spdlog/details/thread_pool.h" + +#include +#include +#include + +template +SPDLOG_INLINE spdlog::async_logger::async_logger( + std::string logger_name, It begin, It end, std::weak_ptr tp, async_overflow_policy overflow_policy) + : logger(std::move(logger_name), begin, end) + , thread_pool_(std::move(tp)) + , overflow_policy_(overflow_policy) +{ +} + +SPDLOG_INLINE spdlog::async_logger::async_logger( + std::string logger_name, sinks_init_list sinks_list, std::weak_ptr tp, async_overflow_policy overflow_policy) + : async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), std::move(tp), overflow_policy) +{ +} + +SPDLOG_INLINE spdlog::async_logger::async_logger( + std::string logger_name, sink_ptr single_sink, std::weak_ptr tp, async_overflow_policy overflow_policy) + : async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy) +{ +} + +// send the log message to the thread pool +SPDLOG_INLINE void spdlog::async_logger::sink_it_(details::log_msg &msg) +{ + if (auto pool_ptr = thread_pool_.lock()) + { + pool_ptr->post_log(shared_from_this(), msg, overflow_policy_); + } + else + { + throw spdlog_ex("async log: thread pool doesn't exist anymore"); + } +} + +// send flush request to the thread pool +SPDLOG_INLINE void spdlog::async_logger::flush_() +{ + if (auto pool_ptr = thread_pool_.lock()) + { + pool_ptr->post_flush(shared_from_this(), overflow_policy_); + } + else + { + throw spdlog_ex("async flush: thread pool doesn't exist anymore"); + } +} + +// +// backend functions - called from the thread pool to do the actual job +// +SPDLOG_INLINE void spdlog::async_logger::backend_log_(const details::log_msg &incoming_log_msg) +{ + try + { + for (auto &s : sinks_) + { + if (s->should_log(incoming_log_msg.level)) + { + s->log(incoming_log_msg); + } + } + } + catch (const std::exception &ex) + { + err_handler_(ex.what()); + } + catch (...) + { + err_handler_("Unknown exception in logger"); + } + + if (should_flush_(incoming_log_msg)) + { + backend_flush_(); + } +} + +SPDLOG_INLINE void spdlog::async_logger::backend_flush_() +{ + try + { + for (auto &sink : sinks_) + { + sink->flush(); + } + } + catch (const std::exception &ex) + { + err_handler_(ex.what()); + } + catch (...) + { + err_handler_("Unknown exception in logger"); + } +} + +SPDLOG_INLINE std::shared_ptr spdlog::async_logger::clone(std::string new_name) +{ + auto cloned = std::make_shared(std::move(new_name), sinks_.begin(), sinks_.end(), thread_pool_, overflow_policy_); + + cloned->set_level(this->level()); + cloned->flush_on(this->flush_level()); + cloned->set_error_handler(this->custom_err_handler_); + return std::move(cloned); +} + + + diff --git a/src/os.cpp b/src/os.cpp index 93738cb0..ecd5a611 100644 --- a/src/os.cpp +++ b/src/os.cpp @@ -2,8 +2,6 @@ // Copyright(c) 2015 Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#pragma once - #ifndef SPDLOG_HEADER_ONLY #include "spdlog/details/os.h" #endif diff --git a/tests/test_errors.cpp b/tests/test_errors.cpp index e675cfd3..f2d69777 100644 --- a/tests/test_errors.cpp +++ b/tests/test_errors.cpp @@ -42,7 +42,7 @@ struct custom_ex { }; -static void custom_handler(const std::string &msg) +static void custom_handler(const std::string &) { throw custom_ex(); } From ccfa3f03b0629ac57df8a99939ba5c2ad80ea01c Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 26 Apr 2019 17:39:58 +0300 Subject: [PATCH 075/157] Fixed clang tidy --- clang_tidy.sh | 1 - 1 file changed, 1 deletion(-) diff --git a/clang_tidy.sh b/clang_tidy.sh index 4fb8644b..c09054c5 100755 --- a/clang_tidy.sh +++ b/clang_tidy.sh @@ -1,3 +1,2 @@ #!/bin/bash clang-tidy example/example.cpp -- -I ./include -clang-tidy lite-example/example.cpp -- -I./include -I./lite From e8d99cee70e8d80edef5984ab698be19233ea3b2 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 26 Apr 2019 17:52:47 +0300 Subject: [PATCH 076/157] fix formatter bench --- bench/formatter-bench.cpp | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/bench/formatter-bench.cpp b/bench/formatter-bench.cpp index 857f4c78..a4ddaa7b 100644 --- a/bench/formatter-bench.cpp +++ b/bench/formatter-bench.cpp @@ -8,19 +8,6 @@ #include "spdlog/spdlog.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) { auto formatter = spdlog::details::make_unique(pattern); From ff89f1476df4ac01f7b5f85c474093978d4a1090 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 26 Apr 2019 18:14:59 +0300 Subject: [PATCH 077/157] Restored error_handler as std::function --- CMakeLists.txt | 2 +- example/example.cpp | 1 - include/spdlog/details/async_logger_impl.h | 121 --------------------- include/spdlog/logger.h | 8 +- tests/test_errors.cpp | 28 ++--- 5 files changed, 16 insertions(+), 144 deletions(-) delete mode 100644 include/spdlog/details/async_logger_impl.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 20669a00..5137907d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,7 +49,7 @@ endif() option(SPDLOG_HEADER_ONLY "Header only version. Turn OFF to build as static lib" OFF) 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_BENCH "Build benchmarks (Requires https://github.com/google/benchmark.git to be installed)" ON) option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) diff --git a/example/example.cpp b/example/example.cpp index 616a4d20..132494fd 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -12,7 +12,6 @@ #include "spdlog/async.h" #include "spdlog/sinks/stdout_color_sinks.h" - int main(int, char *[]) { using spdlog::sinks::stderr_color_sink_mt; diff --git a/include/spdlog/details/async_logger_impl.h b/include/spdlog/details/async_logger_impl.h deleted file mode 100644 index d3676960..00000000 --- a/include/spdlog/details/async_logger_impl.h +++ /dev/null @@ -1,121 +0,0 @@ -// -// Copyright(c) 2015 Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) -// - -#pragma once - -// async logger implementation -// uses a thread pool to perform the actual logging - -#include "spdlog/details/thread_pool.h" - -#include -#include -#include - -template -inline spdlog::async_logger::async_logger( - std::string logger_name, It begin, It end, std::weak_ptr tp, async_overflow_policy overflow_policy) - : logger(std::move(logger_name), begin, end) - , thread_pool_(std::move(tp)) - , overflow_policy_(overflow_policy) -{ -} - -inline spdlog::async_logger::async_logger( - std::string logger_name, sinks_init_list sinks_list, std::weak_ptr tp, async_overflow_policy 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( - std::string logger_name, sink_ptr single_sink, std::weak_ptr tp, async_overflow_policy overflow_policy) - : async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy) -{ -} - -// send the log message to the thread pool -inline void spdlog::async_logger::sink_it_(details::log_msg &msg) -{ - if (auto pool_ptr = thread_pool_.lock()) - { - pool_ptr->post_log(shared_from_this(), msg, overflow_policy_); - } - else - { - throw spdlog_ex("async log: thread pool doesn't exist anymore"); - } -} - -// send flush request to the thread pool -inline void spdlog::async_logger::flush_() -{ - if (auto pool_ptr = thread_pool_.lock()) - { - pool_ptr->post_flush(shared_from_this(), overflow_policy_); - } - else - { - throw spdlog_ex("async flush: thread pool doesn't exist anymore"); - } -} - -// -// 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) -{ - try - { - for (auto &s : sinks_) - { - if (s->should_log(incoming_log_msg.level)) - { - s->log(incoming_log_msg); - } - } - } - catch (const std::exception &ex) - { - err_handler_(ex.what()); - } - catch (...) - { - err_handler_("Unknown exception in logger"); - } - - if (should_flush_(incoming_log_msg)) - { - backend_flush_(); - } -} - -inline void spdlog::async_logger::backend_flush_() -{ - try - { - for (auto &sink : sinks_) - { - sink->flush(); - } - } - catch (const std::exception &ex) - { - err_handler_(ex.what()); - } - catch (...) - { - err_handler_("Unknown exception in logger"); - } -} - -inline std::shared_ptr spdlog::async_logger::clone(std::string new_name) -{ - auto cloned = std::make_shared(std::move(new_name), sinks_.begin(), sinks_.end(), thread_pool_, overflow_policy_); - - cloned->set_level(this->level()); - cloned->flush_on(this->flush_level()); - cloned->set_error_handler(this->custom_err_handler_); - return std::move(cloned); -} diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 58ae20e6..fdba2a11 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -27,12 +27,13 @@ #include #include #include +#include namespace spdlog { class logger { public: - using err_handler = void (*)(const std::string &msg); + using err_handler = std::function; template logger(std::string name, It begin, It end) : name_(std::move(name)) @@ -332,10 +333,7 @@ public: // default error handler. // print the error to stderr with the max rate of 1 message/minute. 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_; std::vector sinks_; spdlog::level_t level_{spdlog::logger::default_level()}; diff --git a/tests/test_errors.cpp b/tests/test_errors.cpp index f2d69777..24075634 100644 --- a/tests/test_errors.cpp +++ b/tests/test_errors.cpp @@ -41,18 +41,13 @@ TEST_CASE("default_error_handler", "[errors]]") struct custom_ex { }; - -static void custom_handler(const std::string &) -{ - throw custom_ex(); -} TEST_CASE("custom_error_handler", "[errors]]") { prepare_logdir(); std::string filename = "logs/simple_log.txt"; auto logger = spdlog::create("logger", filename, true); logger->flush_on(spdlog::level::info); - logger->set_error_handler(custom_handler); + logger->set_error_handler([=](const std::string &) { throw custom_ex(); }); logger->info("Good message #1"); REQUIRE_THROWS_AS(logger->info("Bad format msg {} {}", "xxx"), custom_ex); @@ -64,7 +59,7 @@ TEST_CASE("default_error_handler2", "[errors]]") { spdlog::drop_all(); auto logger = spdlog::create("failed_logger"); - logger->set_error_handler(custom_handler); + logger->set_error_handler([=](const std::string &) { throw custom_ex(); }); REQUIRE_THROWS_AS(logger->info("Some message"), custom_ex); } @@ -72,26 +67,26 @@ TEST_CASE("flush_error_handler", "[errors]]") { spdlog::drop_all(); auto logger = spdlog::create("failed_logger"); - logger->set_error_handler(custom_handler); + logger->set_error_handler([=](const std::string &) { throw custom_ex(); }); REQUIRE_THROWS_AS(logger->flush(), custom_ex); } TEST_CASE("async_error_handler", "[errors]]") { prepare_logdir(); - + std::string err_msg("log failed with some msg"); std::string filename = "logs/simple_async_log.txt"; { spdlog::init_thread_pool(128, 1); auto logger = spdlog::create_async("logger", filename, true); - logger->set_error_handler([](const std::string &) { + logger->set_error_handler([=](const std::string &) { std::ofstream ofs("logs/custom_err.txt"); if (!ofs) { throw std::runtime_error("Failed open logs/custom_err.txt"); } - ofs << "log failed with some msg"; + ofs << err_msg; }); logger->info("Good message #1"); logger->info("Bad format msg {} {}", "xxx"); @@ -100,26 +95,27 @@ TEST_CASE("async_error_handler", "[errors]]") } spdlog::init_thread_pool(128, 1); REQUIRE(count_lines(filename) == 2); - REQUIRE(file_contents("logs/custom_err.txt") == "log failed with some msg"); + REQUIRE(file_contents("logs/custom_err.txt") == err_msg); } // Make sure async error handler is executed TEST_CASE("async_error_handler2", "[errors]]") { - prepare_logdir(); + prepare_logdir(); + std::string err_msg("This is async handler error message"); { spdlog::init_thread_pool(128, 1); auto logger = spdlog::create_async("failed_logger"); - logger->set_error_handler([](const std::string &) { + logger->set_error_handler([=](const std::string &) { std::ofstream ofs("logs/custom_err2.txt"); if (!ofs) throw std::runtime_error("Failed open logs/custom_err2.txt"); - ofs << "handler error message"; + ofs << err_msg; }); logger->info("Hello failure"); spdlog::drop("failed_logger"); // force logger to drain the queue and shutdown } spdlog::init_thread_pool(128, 1); - REQUIRE(file_contents("logs/custom_err2.txt") == "handler error message"); + REQUIRE(file_contents("logs/custom_err2.txt") == err_msg); } From c1c2ff2d07d3420038aa5579940efb9472808e6e Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 27 Apr 2019 02:33:33 +0300 Subject: [PATCH 078/157] wip --- CMakeLists.txt | 39 ++- example/example.cpp | 226 +++++++++++++++++- include/spdlog/.spdlog.h.kate-swp | Bin 0 -> 223 bytes include/spdlog/async_logger.h | 2 +- include/spdlog/common.h | 2 + include/spdlog/details/file_helper.h | 2 +- include/spdlog/details/log_msg.h | 2 +- include/spdlog/details/os.h | 2 +- include/spdlog/details/pattern_formatter.h | 2 +- include/spdlog/details/registry.h | 2 +- {src => include/spdlog/impl}/async_logger.cpp | 0 {src => include/spdlog/impl}/file_helper.cpp | 0 {src => include/spdlog/impl}/log_msg.cpp | 0 {src => include/spdlog/impl}/logger.cpp | 0 {src => include/spdlog/impl}/os.cpp | 0 .../spdlog/impl}/pattern_formatter.cpp | 0 {src => include/spdlog/impl}/registry.cpp | 0 {src => include/spdlog/impl}/sink.cpp | 0 include/spdlog/logger.h | 3 +- include/spdlog/sinks/sink.h | 2 +- 20 files changed, 260 insertions(+), 24 deletions(-) create mode 100644 include/spdlog/.spdlog.h.kate-swp rename {src => include/spdlog/impl}/async_logger.cpp (100%) rename {src => include/spdlog/impl}/file_helper.cpp (100%) rename {src => include/spdlog/impl}/log_msg.cpp (100%) rename {src => include/spdlog/impl}/logger.cpp (100%) rename {src => include/spdlog/impl}/os.cpp (100%) rename {src => include/spdlog/impl}/pattern_formatter.cpp (100%) rename {src => include/spdlog/impl}/registry.cpp (100%) rename {src => include/spdlog/impl}/sink.cpp (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5137907d..8bb9460d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -47,41 +47,47 @@ if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) set(SPDLOG_MASTER_PROJECT ON) endif() -option(SPDLOG_HEADER_ONLY "Header only version. Turn OFF to build as static lib" OFF) +option(SPDLOG_HEADER_ONLY "Header only version. Turn OFF to build as static lib" ON) 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)" ON) option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) +set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include") + if(SPDLOG_HEADER_ONLY) add_definitions(-DSPDLOG_HEADER_ONLY) add_library(spdlog INTERFACE) add_library(spdlog::spdlog ALIAS spdlog) + target_include_directories( + spdlog + INTERFACE + "$" + ) else() remove_definitions(-DSPDLOG_HEADER_ONLY) - file(GLOB SRC_FILES ${PROJECT_SOURCE_DIR}/src/*.cpp) - add_library(spdlog ${SRC_FILES} ) + file(GLOB SRC_FILES ${HEADER_BASE}/spdlog/impl/*.cpp) + add_library(spdlog STATIC ${SRC_FILES}) add_library(spdlog::spdlog ALIAS spdlog) + target_include_directories( + spdlog + PUBLIC + "$" + ) endif() if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) find_package(fmt REQUIRED CONFIG) endif() -target_include_directories( - spdlog - PUBLIC - "$" -) if(SPDLOG_FMT_EXTERNAL) target_compile_definitions(spdlog INTERFACE SPDLOG_FMT_EXTERNAL) target_link_libraries(spdlog INTERFACE fmt::fmt) endif() -set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include") if(SPDLOG_BUILD_EXAMPLES) add_subdirectory(example) @@ -95,3 +101,18 @@ endif() if(SPDLOG_BUILD_BENCH) add_subdirectory(bench) endif() + +#--------------------------------------------------------------------------------------- +# install +#--------------------------------------------------------------------------------------- +install(DIRECTORY ${HEADER_BASE}/spdlog DESTINATION include) + +if(!SPDLOG_HEADER_ONLY) + install(TARGETS spdlog ARCHIVE DESTINATION lib) +endif() + +#--------------------------------------------------------------------------------------- +# register project in CMake user registry +#--------------------------------------------------------------------------------------- +export(PACKAGE ${PROJECT_NAME}) + diff --git a/example/example.cpp b/example/example.cpp index 132494fd..345f8bd1 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -7,15 +7,229 @@ // // +#include + +void stdout_logger_example(); +void basic_example(); +void rotating_example(); +void daily_example(); +void async_example(); +void binary_example(); +void trace_example(); +void multi_sink_example(); +void user_defined_example(); +void err_handler_example(); +void syslog_example(); +void clone_example(); #include "spdlog/spdlog.h" -#include "spdlog/async.h" -#include "spdlog/sinks/stdout_color_sinks.h" int main(int, char *[]) { - using spdlog::sinks::stderr_color_sink_mt; - auto logger = spdlog::create_async("async"); - logger->info("HEllo xsdsdfs {}", 123); - //spdlog::error("HEllo err {}", "HG FS"); + 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::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); + spdlog::info("Support for floats {:03.2f}", 1.23456); + spdlog::info("Positional args are {1} {0}..", "too", "supported"); + spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left"); + + // Runtime log levels + spdlog::set_level(spdlog::level::info); // Set global log level to info + spdlog::debug("This message should not be displayed!"); + spdlog::set_level(spdlog::level::trace); // Set specific logger's log level + spdlog::debug("This message should be displayed.."); + + // Customize msg format for all loggers + spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v"); + spdlog::info("This an info message with custom format"); + spdlog::set_pattern("%+"); // back to default format + + try + { + stdout_logger_example(); + basic_example(); + rotating_example(); + daily_example(); + clone_example(); + async_example(); + binary_example(); + multi_sink_example(); + user_defined_example(); + err_handler_example(); + trace_example(); + + // Flush all *registered* loggers using a worker thread every 3 seconds. + // note: registered loggers *must* be thread safe for this to work correctly! + spdlog::flush_every(std::chrono::seconds(3)); + + // Apply some function on all registered loggers + spdlog::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); + + // Release all spdlog resources, and drop all loggers in the registry. + // This is optional (only mandatory if using windows + async log). + spdlog::shutdown(); + } + + // Exceptions will only be thrown upon failed logger or sink construction (not during logging). + catch (const spdlog::spdlog_ex &ex) + { + std::printf("Log initialization failed: %s\n", ex.what()); + return 1; + } } + +#include "spdlog/sinks/stdout_color_sinks.h" +// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed. +void stdout_logger_example() +{ + // Create color multi threaded logger. + auto console = spdlog::stdout_color_mt("console"); + // or for stderr: + // auto console = spdlog::stderr_color_mt("error-logger"); +} + +#include "spdlog/sinks/basic_file_sink.h" +void basic_example() +{ + // Create basic file logger (not rotated). + auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt"); +} + +#include "spdlog/sinks/rotating_file_sink.h" +void rotating_example() +{ + // Create a file rotating logger with 5mb size max and 3 rotated files. + auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); +} + +#include "spdlog/sinks/daily_file_sink.h" +void daily_example() +{ + // Create a daily logger - a new file is created every day on 2:30am. + auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); +} + +// Clone a logger and give it new name. +// Useful for creating component/subsystem loggers from some "root" logger. +void clone_example() +{ + auto network_logger = spdlog::default_logger()->clone("network"); + network_logger->info("Logging network stuff.."); +} + +#include "spdlog/async.h" +void async_example() +{ + // Default thread pool settings can be modified *before* creating the async logger: + // spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread. + auto async_file = spdlog::basic_logger_mt("async_file_logger", "logs/async_log.txt"); + // alternatively: + // auto async_file = spdlog::create_async("async_file_logger", "logs/async_log.txt"); + + for (int i = 1; i < 101; ++i) + { + async_file->info("Async message #{}", i); + } +} + +// Log binary data as hex. +// Many types of std::container types can be used. +// Iterator ranges are supported too. +// Format flags: +// {:X} - print in uppercase. +// {:s} - don't separate each byte with space. +// {:p} - don't print the position on each line start. +// {:n} - don't split the output to lines. + +#include "spdlog/fmt/bin_to_hex.h" +void binary_example() +{ + std::vector buf; + for (int i = 0; i < 80; i++) + { + buf.push_back(static_cast(i & 0xff)); + } + spdlog::info("Binary example: {}", spdlog::to_hex(buf)); + spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10)); + // more examples: + // logger->info("uppercase: {:X}", spdlog::to_hex(buf)); + // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf)); + // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf)); +} + +// Compile time log levels. +// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE) +void trace_example() +{ + // trace from default logger + SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23); + // debug from default logger + SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23); + + // trace from logger object + auto logger = spdlog::get("file_logger"); + SPDLOG_LOGGER_TRACE(logger, "another trace message"); +} + +// A logger with multiple sinks (stdout and file) - each with a different format and log level. +void multi_sink_example() +{ + auto console_sink = std::make_shared(); + console_sink->set_level(spdlog::level::warn); + console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v"); + + auto file_sink = std::make_shared("logs/multisink.txt", true); + file_sink->set_level(spdlog::level::trace); + + spdlog::logger logger("multi_sink", {console_sink, file_sink}); + logger.set_level(spdlog::level::debug); + logger.warn("this should appear in both console and file"); + logger.info("this message should not appear in the console, only in the file"); +} + +// User defined types logging by implementing operator<< +#include "spdlog/fmt/ostr.h" // must be included +struct my_type +{ + int i; + template + friend OStream &operator<<(OStream &os, const my_type &c) + { + return os << "[my_type i=" << c.i << "]"; + } +}; + +void user_defined_example() +{ + spdlog::info("user defined type: {}", my_type{14}); +} + +// Custom error handler. Will be triggered on log failure. +void err_handler_example() +{ + // can be set globally or per logger(logger->set_error_handler(..)) + spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); }); +} + +// syslog example (linux/osx/freebsd) +#ifndef _WIN32 +#include "spdlog/sinks/syslog_sink.h" +void syslog_example() +{ + std::string ident = "spdlog-example"; + auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID); + syslog_logger->warn("This is warning that will end up in syslog."); +} +#endif + +// Android example. +#if defined(__ANDROID__) +#include "spdlog/sinks/android_sink.h" +void android_example() +{ + std::string tag = "spdlog-android"; + auto android_logger = spdlog::android_logger_mt("android", tag); + android_logger->critical("Use \"adb shell logcat\" to view this message."); +} + +#endif diff --git a/include/spdlog/.spdlog.h.kate-swp b/include/spdlog/.spdlog.h.kate-swp new file mode 100644 index 0000000000000000000000000000000000000000..546ce39c13ff21174480c7ca37b4bbaa0f150501 GIT binary patch literal 223 zcmZQzU=Z?7EJ;-eE>A2_aLdd|RWQ;sU|?VnacVxPmHPaMuS>XK#qA{v7f2m=-xBNz zlraKgS0HA(zT6cq;06?6R7ddL(fA(78uUPt=mJbIfgm6Qrh*w_q7qPu6^I#K5PUWe UKiD-Gq#Ps<;TAmwbX0OBhn$^ZZW literal 0 HcmV?d00001 diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index 3d1c9578..94a1edbd 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -67,7 +67,7 @@ private: } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY -#include "../src/async_logger.cpp" +#include "spdlog/impl/async_logger.cpp" #endif // SPDLOG_HEADER_ONLY diff --git a/include/spdlog/common.h b/include/spdlog/common.h index bb5ec94e..a4c3407c 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -14,6 +14,7 @@ #include #include #include +#include #if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) #include @@ -94,6 +95,7 @@ using filename_t = std::string; using log_clock = std::chrono::system_clock; using sink_ptr = std::shared_ptr; using sinks_init_list = std::initializer_list; +using err_handler = std::function; // string_view type - either std::string_view or fmt::string_view (pre c++17) #if defined(FMT_USE_STD_STRING_VIEW) diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index 1a352c6f..62cd2ee3 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -58,5 +58,5 @@ private: } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY -#include "../../../src/file_helper.cpp" +#include "spdlog/impl/file_helper.cpp" #endif // ! SPDLOG_HEADER_ONLY diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 86918fd4..3ac381be 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -34,5 +34,5 @@ struct log_msg } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY -#include "../../../src/log_msg.cpp" +#include "spdlog/impl/log_msg.cpp" #endif // SPDLOG_HEADER_ONLY diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 9dd94ebe..5f87f5fd 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -89,5 +89,5 @@ void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY -#include "../src/os.cpp" +#include "spdlog/impl/os.cpp" #endif diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 3388743d..64686017 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -103,5 +103,5 @@ private: } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY -#include "../src/pattern_formatter.cpp" +#include "spdlog/impl/pattern_formatter.cpp" #endif diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 24e72e2f..5afff601 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -102,5 +102,5 @@ private: } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY -#include "../src/registry.cpp" +#include "spdlog/impl/registry.cpp" #endif // SPDLOG_HEADER_ONLY diff --git a/src/async_logger.cpp b/include/spdlog/impl/async_logger.cpp similarity index 100% rename from src/async_logger.cpp rename to include/spdlog/impl/async_logger.cpp diff --git a/src/file_helper.cpp b/include/spdlog/impl/file_helper.cpp similarity index 100% rename from src/file_helper.cpp rename to include/spdlog/impl/file_helper.cpp diff --git a/src/log_msg.cpp b/include/spdlog/impl/log_msg.cpp similarity index 100% rename from src/log_msg.cpp rename to include/spdlog/impl/log_msg.cpp diff --git a/src/logger.cpp b/include/spdlog/impl/logger.cpp similarity index 100% rename from src/logger.cpp rename to include/spdlog/impl/logger.cpp diff --git a/src/os.cpp b/include/spdlog/impl/os.cpp similarity index 100% rename from src/os.cpp rename to include/spdlog/impl/os.cpp diff --git a/src/pattern_formatter.cpp b/include/spdlog/impl/pattern_formatter.cpp similarity index 100% rename from src/pattern_formatter.cpp rename to include/spdlog/impl/pattern_formatter.cpp diff --git a/src/registry.cpp b/include/spdlog/impl/registry.cpp similarity index 100% rename from src/registry.cpp rename to include/spdlog/impl/registry.cpp diff --git a/src/sink.cpp b/include/spdlog/impl/sink.cpp similarity index 100% rename from src/sink.cpp rename to include/spdlog/impl/sink.cpp diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index fdba2a11..070e9875 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -33,7 +33,6 @@ namespace spdlog { class logger { public: - using err_handler = std::function; template logger(std::string name, It begin, It end) : name_(std::move(name)) @@ -345,5 +344,5 @@ public: } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY -#include "../src/logger.cpp" +#include "spdlog/impl/logger.cpp" #endif // SPDLOG_HEADER_ONLY diff --git a/include/spdlog/sinks/sink.h b/include/spdlog/sinks/sink.h index 11c54fb6..8515b041 100644 --- a/include/spdlog/sinks/sink.h +++ b/include/spdlog/sinks/sink.h @@ -42,5 +42,5 @@ protected: } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY -#include "../src/sink.cpp" +#include "spdlog/impl/sink.cpp" #endif // SPDLOG_HEADER_ONLY From 2de924a187d6cfcec0f87723e3790b07d4bfb01a Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 27 Apr 2019 02:34:50 +0300 Subject: [PATCH 079/157] clang-format --- include/spdlog/async_logger.h | 3 - include/spdlog/common.h | 1 - include/spdlog/details/file_helper.h | 16 +- include/spdlog/details/log_msg.h | 4 +- include/spdlog/details/pattern_formatter.h | 21 +- include/spdlog/details/registry.h | 48 +- include/spdlog/impl/async_logger.cpp | 20 +- include/spdlog/impl/file_helper.cpp | 169 ++++--- include/spdlog/impl/log_msg.cpp | 12 +- include/spdlog/impl/logger.cpp | 10 +- include/spdlog/impl/pattern_formatter.cpp | 552 ++++++++++----------- include/spdlog/impl/registry.cpp | 1 - include/spdlog/impl/sink.cpp | 60 +-- include/spdlog/logger.h | 479 +++++++++--------- include/spdlog/sinks/sink.h | 6 +- include/spdlog/spdlog.h | 3 +- tests/test_misc.cpp | 4 +- 17 files changed, 694 insertions(+), 715 deletions(-) diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index 94a1edbd..b0b644a4 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -19,7 +19,6 @@ // Upon destruction, logs all remaining messages in the queue before // destructing.. - #include "spdlog/logger.h" namespace spdlog { @@ -69,5 +68,3 @@ private: #ifdef SPDLOG_HEADER_ONLY #include "spdlog/impl/async_logger.cpp" #endif // SPDLOG_HEADER_ONLY - - diff --git a/include/spdlog/common.h b/include/spdlog/common.h index a4c3407c..add4000b 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -70,7 +70,6 @@ #define SPDLOG_FUNCTION __FUNCTION__ #endif - namespace spdlog { class formatter; diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index 62cd2ee3..9f7fceaa 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -24,17 +24,17 @@ public: file_helper(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); - void flush(); - void close(); + void open(const filename_t &fname, bool truncate = false); + void reopen(bool truncate); + void flush(); + void close(); void write(const fmt::memory_buffer &buf); - size_t size() const; + size_t size() const; const filename_t &filename() const; static bool file_exists(const filename_t &fname); - + // // return file path and its extension: // @@ -57,6 +57,6 @@ private: } // namespace details } // namespace spdlog -#ifdef SPDLOG_HEADER_ONLY +#ifdef SPDLOG_HEADER_ONLY #include "spdlog/impl/file_helper.cpp" #endif // ! SPDLOG_HEADER_ONLY diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 3ac381be..e9cacbb7 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -13,7 +13,7 @@ namespace details { struct log_msg { 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); log_msg(const log_msg &other) = default; @@ -33,6 +33,6 @@ struct log_msg } // namespace details } // namespace spdlog -#ifdef SPDLOG_HEADER_ONLY +#ifdef SPDLOG_HEADER_ONLY #include "spdlog/impl/log_msg.cpp" #endif // SPDLOG_HEADER_ONLY diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 64686017..210efd23 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -20,7 +20,6 @@ namespace spdlog { namespace details { - // padding information. struct padding_info { @@ -61,26 +60,22 @@ protected: padding_info padinfo_; }; -} +} // namespace details class pattern_formatter final : public formatter { public: explicit pattern_formatter( - std::string pattern, - pattern_time_type time_type = pattern_time_type::local, - std::string eol = spdlog::details::os::default_eol); - + std::string pattern, pattern_time_type time_type = pattern_time_type::local, std::string eol = spdlog::details::os::default_eol); + // use default pattern is not given - explicit pattern_formatter( - pattern_time_type time_type = pattern_time_type::local, - std::string eol = spdlog::details::os::default_eol); + explicit pattern_formatter(pattern_time_type time_type = pattern_time_type::local, std::string eol = spdlog::details::os::default_eol); pattern_formatter(const pattern_formatter &other) = delete; pattern_formatter &operator=(const pattern_formatter &other) = delete; std::unique_ptr clone() const override; - void format(const details::log_msg &msg, fmt::memory_buffer &dest) override; + void format(const details::log_msg &msg, fmt::memory_buffer &dest) override; private: std::string pattern_; @@ -89,15 +84,15 @@ private: std::tm cached_tm_; std::chrono::seconds last_log_secs_; std::vector> formatters_; - std::tm get_time_(const details::log_msg &msg); + std::tm get_time_(const details::log_msg &msg); void handle_flag_(char flag, details::padding_info padding); - + // Extract given pad spec (e.g. %8X) // Advance the given it pass the end of the padding spec found (if any) // Return padding. details::padding_info handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end); - + void compile_pattern_(const std::string &pattern); }; } // namespace spdlog diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 5afff601..93d35e87 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -32,59 +32,59 @@ public: registry(const registry &) = delete; registry &operator=(const registry &) = delete; - void register_logger(std::shared_ptr new_logger); - void initialize_logger(std::shared_ptr new_logger); - std::shared_ptr get(const std::string &logger_name); + void register_logger(std::shared_ptr new_logger); + void initialize_logger(std::shared_ptr new_logger); + std::shared_ptr get(const std::string &logger_name); std::shared_ptr default_logger(); - + // Return raw ptr to the default logger. // To be used directly by the spdlog default api (e.g. spdlog::info) // This make the default API faster, but cannot be used concurrently with set_default_logger(). // e.g do not call set_default_logger() from one thread while calling spdlog::info() from another. logger *get_default_raw(); - + // set default logger. // default logger is stored in default_logger_ (for faster retrieval) and in the loggers_ map. void set_default_logger(std::shared_ptr new_default_logger); void set_tp(std::shared_ptr tp); - + std::shared_ptr get_tp(); - + // Set global formatter. Each sink in each logger will get a clone of this object - void set_formatter(std::unique_ptr formatter); + void set_formatter(std::unique_ptr formatter); void set_level(level::level_enum log_level); - + void flush_on(level::level_enum log_level); - + void flush_every(std::chrono::seconds interval); - + void set_error_handler(void (*handler)(const std::string &msg)); - + void apply_all(const std::function)> &fun); - + void flush_all(); - + void drop(const std::string &logger_name); - - void drop_all(); + + void drop_all(); // clean all resources and threads started by the registry - void shutdown(); + void shutdown(); + + std::recursive_mutex &tp_mutex(); - std::recursive_mutex &tp_mutex(); - void set_automatic_registration(bool automatic_regsistration); - - static registry &instance(); + + static registry &instance(); private: - registry(); + registry(); ~registry() = default; - void throw_if_exists_(const std::string &logger_name); - void register_logger_(std::shared_ptr new_logger); + void throw_if_exists_(const std::string &logger_name); + void register_logger_(std::shared_ptr new_logger); std::mutex logger_map_mutex_, flusher_mutex_; std::recursive_mutex tp_mutex_; std::unordered_map> loggers_; diff --git a/include/spdlog/impl/async_logger.cpp b/include/spdlog/impl/async_logger.cpp index 94e8e546..e915042e 100644 --- a/include/spdlog/impl/async_logger.cpp +++ b/include/spdlog/impl/async_logger.cpp @@ -2,7 +2,6 @@ #include "spdlog/async_logger.h" #endif - // async logger implementation // uses a thread pool to perform the actual logging @@ -15,22 +14,22 @@ template SPDLOG_INLINE spdlog::async_logger::async_logger( - std::string logger_name, It begin, It end, std::weak_ptr tp, async_overflow_policy overflow_policy) - : logger(std::move(logger_name), begin, end) - , thread_pool_(std::move(tp)) - , overflow_policy_(overflow_policy) + std::string logger_name, It begin, It end, std::weak_ptr tp, async_overflow_policy overflow_policy) + : logger(std::move(logger_name), begin, end) + , thread_pool_(std::move(tp)) + , overflow_policy_(overflow_policy) { } SPDLOG_INLINE spdlog::async_logger::async_logger( - std::string logger_name, sinks_init_list sinks_list, std::weak_ptr tp, async_overflow_policy overflow_policy) - : async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), std::move(tp), overflow_policy) + std::string logger_name, sinks_init_list sinks_list, std::weak_ptr tp, async_overflow_policy overflow_policy) + : async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), std::move(tp), overflow_policy) { } SPDLOG_INLINE spdlog::async_logger::async_logger( - std::string logger_name, sink_ptr single_sink, std::weak_ptr tp, async_overflow_policy overflow_policy) - : async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy) + std::string logger_name, sink_ptr single_sink, std::weak_ptr tp, async_overflow_policy overflow_policy) + : async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy) { } @@ -118,6 +117,3 @@ SPDLOG_INLINE std::shared_ptr spdlog::async_logger::clone(std::s cloned->set_error_handler(this->custom_err_handler_); return std::move(cloned); } - - - diff --git a/include/spdlog/impl/file_helper.cpp b/include/spdlog/impl/file_helper.cpp index 781931b0..70a86eb8 100644 --- a/include/spdlog/impl/file_helper.cpp +++ b/include/spdlog/impl/file_helper.cpp @@ -17,116 +17,115 @@ #include namespace spdlog { -namespace details +namespace details { +SPDLOG_INLINE file_helper::~file_helper() { - SPDLOG_INLINE file_helper::~file_helper() - { - close(); - } + close(); +} - SPDLOG_INLINE void file_helper::open(const filename_t &fname, bool truncate) +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) { - 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)) { - if (!os::fopen_s(&fd_, fname, mode)) - { - return; - } - - details::os::sleep_for_millis(open_interval); + return; } - throw spdlog_ex("Failed opening file " + os::filename_to_str(_filename) + " for writing", errno); + details::os::sleep_for_millis(open_interval); } - SPDLOG_INLINE void file_helper::reopen(bool truncate) + 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()) { - if (_filename.empty()) - { - throw spdlog_ex("Failed re opening file - was not opened before"); - } - open(_filename, truncate); + throw spdlog_ex("Failed re opening file - was not opened before"); } + open(_filename, truncate); +} - SPDLOG_INLINE void file_helper::flush() +SPDLOG_INLINE void file_helper::flush() +{ + std::fflush(fd_); +} + +SPDLOG_INLINE void file_helper::close() +{ + if (fd_ != nullptr) { - std::fflush(fd_); + std::fclose(fd_); + fd_ = nullptr; } +} - SPDLOG_INLINE void file_helper::close() +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) { - if (fd_ != nullptr) - { - std::fclose(fd_); - fd_ = nullptr; - } + throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno); } +} - SPDLOG_INLINE void file_helper::write(const fmt::memory_buffer &buf) +SPDLOG_INLINE size_t file_helper::size() const +{ + if (fd_ == nullptr) { - 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); - } + throw spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(_filename)); } + return os::filesize(fd_); +} - SPDLOG_INLINE size_t file_helper::size() const +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 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) { - if (fd_ == nullptr) - { - throw spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(_filename)); - } - return os::filesize(fd_); + return std::make_tuple(fname, filename_t()); } - SPDLOG_INLINE const filename_t &file_helper::filename() const + // 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 _filename; + return std::make_tuple(fname, filename_t()); } - 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 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)); - } + // 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 diff --git a/include/spdlog/impl/log_msg.cpp b/include/spdlog/impl/log_msg.cpp index 241bcf5d..ec4f8642 100644 --- a/include/spdlog/impl/log_msg.cpp +++ b/include/spdlog/impl/log_msg.cpp @@ -1,12 +1,10 @@ #include "spdlog/details/os.h" #include "spdlog/sinks/sink.h" - -#ifndef SPDLOG_HEADER_ONLY -#include "spdlog/details/log_msg.h" -#endif - - - + +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/details/log_msg.h" +#endif + SPDLOG_INLINE spdlog::details::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) diff --git a/include/spdlog/impl/logger.cpp b/include/spdlog/impl/logger.cpp index d3200537..7dcfc973 100644 --- a/include/spdlog/impl/logger.cpp +++ b/include/spdlog/impl/logger.cpp @@ -160,11 +160,11 @@ SPDLOG_INLINE bool spdlog::logger::should_flush_(const spdlog::details::log_msg } SPDLOG_INLINE void spdlog::logger::err_handler_(const std::string &msg) -{ - if (custom_err_handler_) - { - custom_err_handler_(msg); - } +{ + if (custom_err_handler_) + { + custom_err_handler_(msg); + } else { auto tm_time = spdlog::details::os::localtime(); diff --git a/include/spdlog/impl/pattern_formatter.cpp b/include/spdlog/impl/pattern_formatter.cpp index 810d8a23..f1d43cf8 100644 --- a/include/spdlog/impl/pattern_formatter.cpp +++ b/include/spdlog/impl/pattern_formatter.cpp @@ -959,308 +959,304 @@ private: } // namespace details +SPDLOG_INLINE pattern_formatter::pattern_formatter(std::string pattern, pattern_time_type time_type, std::string eol) + : pattern_(std::move(pattern)) + , eol_(std::move(eol)) + , pattern_time_type_(time_type) + , last_log_secs_(0) +{ + std::memset(&cached_tm_, 0, sizeof(cached_tm_)); + compile_pattern_(pattern_); +} - SPDLOG_INLINE pattern_formatter::pattern_formatter( - std::string pattern, pattern_time_type time_type, std::string eol) - : pattern_(std::move(pattern)) - , eol_(std::move(eol)) - , pattern_time_type_(time_type) - , last_log_secs_(0) - { - std::memset(&cached_tm_, 0, sizeof(cached_tm_)); - compile_pattern_(pattern_); - } +// use by default full formatter for if pattern is not given +SPDLOG_INLINE pattern_formatter::pattern_formatter(pattern_time_type time_type, std::string eol) + : pattern_("%+") + , eol_(std::move(eol)) + , pattern_time_type_(time_type) + , last_log_secs_(0) +{ + std::memset(&cached_tm_, 0, sizeof(cached_tm_)); + formatters_.push_back(details::make_unique(details::padding_info{})); +} - // use by default full formatter for if pattern is not given - SPDLOG_INLINE pattern_formatter::pattern_formatter(pattern_time_type time_type, std::string eol) - : pattern_("%+") - , eol_(std::move(eol)) - , pattern_time_type_(time_type) - , last_log_secs_(0) - { - std::memset(&cached_tm_, 0, sizeof(cached_tm_)); - formatters_.push_back(details::make_unique(details::padding_info{})); - } +SPDLOG_INLINE std::unique_ptr pattern_formatter::clone() const +{ + return details::make_unique(pattern_, pattern_time_type_, eol_); +} - - SPDLOG_INLINE std::unique_ptr pattern_formatter::clone() const - { - return details::make_unique(pattern_, pattern_time_type_, eol_); - } - - SPDLOG_INLINE void pattern_formatter::format(const details::log_msg &msg, fmt::memory_buffer &dest) - { +SPDLOG_INLINE void pattern_formatter::format(const details::log_msg &msg, fmt::memory_buffer &dest) +{ #ifndef SPDLOG_NO_DATETIME - auto secs = std::chrono::duration_cast(msg.time.time_since_epoch()); - if (secs != last_log_secs_) - { - cached_tm_ = get_time_(msg); - last_log_secs_ = secs; - } + auto secs = std::chrono::duration_cast(msg.time.time_since_epoch()); + if (secs != last_log_secs_) + { + cached_tm_ = get_time_(msg); + last_log_secs_ = secs; + } #endif - for (auto &f : formatters_) - { - f->format(msg, cached_tm_, dest); - } - // write eol - details::fmt_helper::append_string_view(eol_, dest); + for (auto &f : formatters_) + { + f->format(msg, cached_tm_, dest); + } + // write eol + details::fmt_helper::append_string_view(eol_, dest); +} + +SPDLOG_INLINE std::tm pattern_formatter::get_time_(const details::log_msg &msg) +{ + if (pattern_time_type_ == pattern_time_type::local) + { + return details::os::localtime(log_clock::to_time_t(msg.time)); + } + return details::os::gmtime(log_clock::to_time_t(msg.time)); +} + +SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_info padding) +{ + switch (flag) + { + + case ('+'): // default formatter + formatters_.push_back(details::make_unique(padding)); + break; + + case 'n': // logger name + formatters_.push_back(details::make_unique(padding)); + break; + + case 'l': // level + formatters_.push_back(details::make_unique(padding)); + break; + + case 'L': // short level + formatters_.push_back(details::make_unique(padding)); + break; + + case ('t'): // thread id + formatters_.push_back(details::make_unique(padding)); + break; + + case ('v'): // the message text + formatters_.push_back(details::make_unique(padding)); + break; + + case ('a'): // weekday + formatters_.push_back(details::make_unique(padding)); + break; + + case ('A'): // short weekday + formatters_.push_back(details::make_unique(padding)); + break; + + case ('b'): + case ('h'): // month + formatters_.push_back(details::make_unique(padding)); + break; + + case ('B'): // short month + formatters_.push_back(details::make_unique(padding)); + break; + + case ('c'): // datetime + formatters_.push_back(details::make_unique(padding)); + break; + + case ('C'): // year 2 digits + formatters_.push_back(details::make_unique(padding)); + break; + + case ('Y'): // year 4 digits + formatters_.push_back(details::make_unique(padding)); + break; + + case ('D'): + case ('x'): // datetime MM/DD/YY + formatters_.push_back(details::make_unique(padding)); + break; + + case ('m'): // month 1-12 + formatters_.push_back(details::make_unique(padding)); + break; + + case ('d'): // day of month 1-31 + formatters_.push_back(details::make_unique(padding)); + break; + + case ('H'): // hours 24 + formatters_.push_back(details::make_unique(padding)); + break; + + case ('I'): // hours 12 + formatters_.push_back(details::make_unique(padding)); + break; + + case ('M'): // minutes + formatters_.push_back(details::make_unique(padding)); + break; + + case ('S'): // seconds + formatters_.push_back(details::make_unique(padding)); + break; + + case ('e'): // milliseconds + formatters_.push_back(details::make_unique(padding)); + break; + + case ('f'): // microseconds + formatters_.push_back(details::make_unique(padding)); + break; + + case ('F'): // nanoseconds + formatters_.push_back(details::make_unique(padding)); + break; + + case ('E'): // seconds since epoch + formatters_.push_back(details::make_unique(padding)); + break; + + case ('p'): // am/pm + formatters_.push_back(details::make_unique(padding)); + break; + + case ('r'): // 12 hour clock 02:55:02 pm + formatters_.push_back(details::make_unique(padding)); + break; + + case ('R'): // 24-hour HH:MM time + formatters_.push_back(details::make_unique(padding)); + break; + + case ('T'): + case ('X'): // ISO 8601 time format (HH:MM:SS) + formatters_.push_back(details::make_unique(padding)); + break; + + case ('z'): // timezone + formatters_.push_back(details::make_unique(padding)); + break; + + case ('P'): // pid + formatters_.push_back(details::make_unique(padding)); + break; + + case ('^'): // color range start + formatters_.push_back(details::make_unique(padding)); + break; + + case ('$'): // color range end + formatters_.push_back(details::make_unique(padding)); + break; + + case ('@'): // source location (filename:filenumber) + formatters_.push_back(details::make_unique(padding)); + break; + + case ('s'): // source filename + formatters_.push_back(details::make_unique(padding)); + break; + + case ('#'): // source line number + formatters_.push_back(details::make_unique(padding)); + break; + + case ('!'): // source funcname + formatters_.push_back(details::make_unique(padding)); + break; + + case ('%'): // % char + formatters_.push_back(details::make_unique('%')); + break; + + default: // Unknown flag appears as is + auto unknown_flag = details::make_unique(); + unknown_flag->add_ch('%'); + unknown_flag->add_ch(flag); + formatters_.push_back((std::move(unknown_flag))); + break; + } +} + +// Extract given pad spec (e.g. %8X) +// Advance the given it pass the end of the padding spec found (if any) +// Return padding. +SPDLOG_INLINE details::padding_info pattern_formatter::handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end) +{ + using details::padding_info; + using details::scoped_pad; + const size_t max_width = 128; + if (it == end) + { + return padding_info{}; } - SPDLOG_INLINE std::tm pattern_formatter::get_time_(const details::log_msg &msg) + padding_info::pad_side side; + switch (*it) { - if (pattern_time_type_ == pattern_time_type::local) - { - return details::os::localtime(log_clock::to_time_t(msg.time)); - } - return details::os::gmtime(log_clock::to_time_t(msg.time)); + case '-': + side = padding_info::right; + ++it; + break; + case '=': + side = padding_info::center; + ++it; + break; + default: + side = details::padding_info::left; + break; } - SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_info padding) + if (it == end || !std::isdigit(static_cast(*it))) { - switch (flag) - { - - case ('+'): // default formatter - formatters_.push_back(details::make_unique(padding)); - break; - - case 'n': // logger name - formatters_.push_back(details::make_unique(padding)); - break; - - case 'l': // level - formatters_.push_back(details::make_unique(padding)); - break; - - case 'L': // short level - formatters_.push_back(details::make_unique(padding)); - break; - - case ('t'): // thread id - formatters_.push_back(details::make_unique(padding)); - break; - - case ('v'): // the message text - formatters_.push_back(details::make_unique(padding)); - break; - - case ('a'): // weekday - formatters_.push_back(details::make_unique(padding)); - break; - - case ('A'): // short weekday - formatters_.push_back(details::make_unique(padding)); - break; - - case ('b'): - case ('h'): // month - formatters_.push_back(details::make_unique(padding)); - break; - - case ('B'): // short month - formatters_.push_back(details::make_unique(padding)); - break; - - case ('c'): // datetime - formatters_.push_back(details::make_unique(padding)); - break; - - case ('C'): // year 2 digits - formatters_.push_back(details::make_unique(padding)); - break; - - case ('Y'): // year 4 digits - formatters_.push_back(details::make_unique(padding)); - break; - - case ('D'): - case ('x'): // datetime MM/DD/YY - formatters_.push_back(details::make_unique(padding)); - break; - - case ('m'): // month 1-12 - formatters_.push_back(details::make_unique(padding)); - break; - - case ('d'): // day of month 1-31 - formatters_.push_back(details::make_unique(padding)); - break; - - case ('H'): // hours 24 - formatters_.push_back(details::make_unique(padding)); - break; - - case ('I'): // hours 12 - formatters_.push_back(details::make_unique(padding)); - break; - - case ('M'): // minutes - formatters_.push_back(details::make_unique(padding)); - break; - - case ('S'): // seconds - formatters_.push_back(details::make_unique(padding)); - break; - - case ('e'): // milliseconds - formatters_.push_back(details::make_unique(padding)); - break; - - case ('f'): // microseconds - formatters_.push_back(details::make_unique(padding)); - break; - - case ('F'): // nanoseconds - formatters_.push_back(details::make_unique(padding)); - break; - - case ('E'): // seconds since epoch - formatters_.push_back(details::make_unique(padding)); - break; - - case ('p'): // am/pm - formatters_.push_back(details::make_unique(padding)); - break; - - case ('r'): // 12 hour clock 02:55:02 pm - formatters_.push_back(details::make_unique(padding)); - break; - - case ('R'): // 24-hour HH:MM time - formatters_.push_back(details::make_unique(padding)); - break; - - case ('T'): - case ('X'): // ISO 8601 time format (HH:MM:SS) - formatters_.push_back(details::make_unique(padding)); - break; - - case ('z'): // timezone - formatters_.push_back(details::make_unique(padding)); - break; - - case ('P'): // pid - formatters_.push_back(details::make_unique(padding)); - break; - - case ('^'): // color range start - formatters_.push_back(details::make_unique(padding)); - break; - - case ('$'): // color range end - formatters_.push_back(details::make_unique(padding)); - break; - - case ('@'): // source location (filename:filenumber) - formatters_.push_back(details::make_unique(padding)); - break; - - case ('s'): // source filename - formatters_.push_back(details::make_unique(padding)); - break; - - case ('#'): // source line number - formatters_.push_back(details::make_unique(padding)); - break; - - case ('!'): // source funcname - formatters_.push_back(details::make_unique(padding)); - break; - - case ('%'): // % char - formatters_.push_back(details::make_unique('%')); - break; - - default: // Unknown flag appears as is - auto unknown_flag = details::make_unique(); - unknown_flag->add_ch('%'); - unknown_flag->add_ch(flag); - formatters_.push_back((std::move(unknown_flag))); - break; - } + return padding_info{0, side}; } - // Extract given pad spec (e.g. %8X) - // Advance the given it pass the end of the padding spec found (if any) - // Return padding. - SPDLOG_INLINE details::padding_info pattern_formatter::handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end) + auto width = static_cast(*it - '0'); + for (++it; it != end && std::isdigit(static_cast(*it)); ++it) { - using details::padding_info; - using details::scoped_pad; - const size_t max_width = 128; - if (it == end) - { - return padding_info{}; - } - - padding_info::pad_side side; - switch (*it) - { - case '-': - side = padding_info::right; - ++it; - break; - case '=': - side = padding_info::center; - ++it; - break; - default: - side = details::padding_info::left; - break; - } - - if (it == end || !std::isdigit(static_cast(*it))) - { - return padding_info{0, side}; - } - - auto width = static_cast(*it - '0'); - for (++it; it != end && std::isdigit(static_cast(*it)); ++it) - { - auto digit = static_cast(*it - '0'); - width = width * 10 + digit; - } - return details::padding_info{std::min(width, max_width), side}; + auto digit = static_cast(*it - '0'); + width = width * 10 + digit; } + return details::padding_info{std::min(width, max_width), side}; +} - SPDLOG_INLINE void pattern_formatter::compile_pattern_(const std::string &pattern) +SPDLOG_INLINE void pattern_formatter::compile_pattern_(const std::string &pattern) +{ + auto end = pattern.end(); + std::unique_ptr user_chars; + formatters_.clear(); + for (auto it = pattern.begin(); it != end; ++it) { - auto end = pattern.end(); - std::unique_ptr user_chars; - formatters_.clear(); - for (auto it = pattern.begin(); it != end; ++it) + if (*it == '%') { - if (*it == '%') + if (user_chars) // append user chars found so far { - if (user_chars) // append user chars found so far - { - formatters_.push_back(std::move(user_chars)); - } - - auto padding = handle_padspec_(++it, end); - - if (it != end) - { - handle_flag_(*it, padding); - } - else - { - break; - } + formatters_.push_back(std::move(user_chars)); } - else // chars not following the % sign should be displayed as is + + auto padding = handle_padspec_(++it, end); + + if (it != end) { - if (!user_chars) - { - user_chars = details::make_unique(); - } - user_chars->add_ch(*it); + handle_flag_(*it, padding); + } + else + { + break; } } - if (user_chars) // append raw chars found so far + else // chars not following the % sign should be displayed as is { - formatters_.push_back(std::move(user_chars)); + if (!user_chars) + { + user_chars = details::make_unique(); + } + user_chars->add_ch(*it); } } + if (user_chars) // append raw chars found so far + { + formatters_.push_back(std::move(user_chars)); + } +} } // namespace spdlog - diff --git a/include/spdlog/impl/registry.cpp b/include/spdlog/impl/registry.cpp index b4487b4a..ca0247eb 100644 --- a/include/spdlog/impl/registry.cpp +++ b/include/spdlog/impl/registry.cpp @@ -6,7 +6,6 @@ #include "spdlog/details/registry.h" #endif - #include "spdlog/common.h" #include "spdlog/details/periodic_worker.h" #include "spdlog/logger.h" diff --git a/include/spdlog/impl/sink.cpp b/include/spdlog/impl/sink.cpp index 7f9e84e5..04adb9be 100644 --- a/include/spdlog/impl/sink.cpp +++ b/include/spdlog/impl/sink.cpp @@ -1,29 +1,31 @@ -#include "spdlog/common.h" -#include "spdlog/details/pattern_formatter.h" - -#ifndef SPDLOG_HEADER_ONLY -#include "spdlog/sinks/sink.h" -#endif - -SPDLOG_INLINE spdlog::sinks::sink::sink() - : formatter_{details::make_unique()} -{} - -SPDLOG_INLINE spdlog::sinks::sink::sink(std::unique_ptr 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(level_.load(std::memory_order_relaxed)); -} +#include "spdlog/common.h" +#include "spdlog/details/pattern_formatter.h" + +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/sinks/sink.h" +#endif + +SPDLOG_INLINE spdlog::sinks::sink::sink() + : formatter_{details::make_unique()} +{ +} + +SPDLOG_INLINE spdlog::sinks::sink::sink(std::unique_ptr 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(level_.load(std::memory_order_relaxed)); +} diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 070e9875..91371320 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -33,313 +33,310 @@ namespace spdlog { class logger { public: - template - logger(std::string name, It begin, It end) - : name_(std::move(name)) - , sinks_(begin, end) + template + logger(std::string name, It begin, It end) + : name_(std::move(name)) + , sinks_(begin, end) + { + } + + 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 &operator=(const logger &) = delete; + + template + void log(source_loc loc, level::level_enum lvl, const char *fmt, const Args &... args) + { + if (!should_log(lvl)) { + return; } - logger(std::string name, sink_ptr single_sink) - : logger(std::move(name), {std::move(single_sink)}) + 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); } - logger(std::string name, sinks_init_list sinks) - : logger(std::move(name), sinks.begin(), sinks.end()) + catch (const std::exception &ex) { + err_handler_(ex.what()); } - - virtual ~logger() = default; - - logger(const logger &) = delete; - logger &operator=(const logger &) = delete; - - template - void log(source_loc loc, level::level_enum lvl, const char *fmt, const Args &... args) + catch (...) { - 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"); - } + err_handler_("Unknown exception in logger"); } + } - template - void log(level::level_enum lvl, const char *fmt, const Args &... args) + template + void log(level::level_enum lvl, const char *fmt, const Args &... args) + { + log(source_loc{}, lvl, fmt, args...); + } + + void log(source_loc loc, level::level_enum lvl, const char *msg); + void log(level::level_enum lvl, const char *msg); + + template + void trace(const char *fmt, const Args &... args) + { + log(level::trace, fmt, args...); + } + + template + void debug(const char *fmt, const Args &... args) + { + log(level::debug, fmt, args...); + } + + template + void info(const char *fmt, const Args &... args) + { + log(level::info, fmt, args...); + } + + template + void warn(const char *fmt, const Args &... args) + { + log(level::warn, fmt, args...); + } + + template + void error(const char *fmt, const Args &... args) + { + log(level::err, fmt, args...); + } + + template + void critical(const char *fmt, const Args &... args) + { + log(level::critical, fmt, args...); + } + + template + void log(level::level_enum lvl, const T &msg) + { + log(source_loc{}, lvl, msg); + } + + // T can be statically converted to string_view + template::value, T>::type * = nullptr> + void log(source_loc loc, level::level_enum lvl, const T &msg) + { + if (!should_log(lvl)) { - log(source_loc{}, lvl, fmt, args...); + return; } - - void log(source_loc loc, level::level_enum lvl, const char *msg); - void log(level::level_enum lvl, const char *msg); - - template - void trace(const char *fmt, const Args &... args) + try { - log(level::trace, fmt, args...); + details::log_msg log_msg(loc, &name_, lvl, msg); + sink_it_(log_msg); } - - template - void debug(const char *fmt, const Args &... args) + catch (const std::exception &ex) { - log(level::debug, fmt, args...); + err_handler_(ex.what()); } - - template - void info(const char *fmt, const Args &... args) + catch (...) { - log(level::info, fmt, args...); + err_handler_("Unknown exception in logger"); } + } - template - void warn(const char *fmt, const Args &... args) + // T cannot be statically converted to string_view + template::value, T>::type * = nullptr> + void log(source_loc loc, level::level_enum lvl, const T &msg) + { + if (!should_log(lvl)) { - log(level::warn, fmt, args...); + return; } - - template - void error(const char *fmt, const Args &... args) + try { - log(level::err, fmt, args...); + 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); } - - template - void critical(const char *fmt, const Args &... args) + catch (const std::exception &ex) { - log(level::critical, fmt, args...); + err_handler_(ex.what()); } - - - template - void log(level::level_enum lvl, const T &msg) + catch (...) { - log(source_loc{}, lvl, msg); + err_handler_("Unknown exception in logger"); } + } - // T can be statically converted to string_view - template::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"); - } - } + template + void trace(const T &msg) + { + log(level::trace, msg); + } - // T cannot be statically converted to string_view - template::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 + void debug(const T &msg) + { + log(level::debug, msg); + } - template - void trace(const T &msg) - { - log(level::trace, msg); - } + template + void info(const T &msg) + { + log(level::info, msg); + } - template - void debug(const T &msg) - { - log(level::debug, msg); - } + template + void warn(const T &msg) + { + log(level::warn, msg); + } - template - void info(const T &msg) - { - log(level::info, msg); - } + template + void error(const T &msg) + { + log(level::err, msg); + } - template - void warn(const T &msg) - { - log(level::warn, msg); - } - - template - void error(const T &msg) - { - log(level::err, msg); - } - - template - void critical(const T &msg) - { - log(level::critical, msg); - } + template + void critical(const T &msg) + { + log(level::critical, msg); + } #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT #ifndef _WIN32 #error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows #else - template - void log(source_loc source, level::level_enum lvl, const wchar_t *fmt, const Args &... args) + template + void log(source_loc source, level::level_enum lvl, const wchar_t *fmt, const Args &... args) + { + if (!should_log(lvl)) { - 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"); - } + return; } - template - void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) + try { - log(source_loc{}, lvl, fmt, args...); + // 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 - void trace(const wchar_t *fmt, const Args &... args) - { - log(level::trace, fmt, args...); - } + template + void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) + { + log(source_loc{}, lvl, fmt, args...); + } - template - void debug(const wchar_t *fmt, const Args &... args) - { - log(level::debug, fmt, args...); - } + template + void trace(const wchar_t *fmt, const Args &... args) + { + log(level::trace, fmt, args...); + } - template - void info(const wchar_t *fmt, const Args &... args) - { - log(level::info, fmt, args...); - } + template + void debug(const wchar_t *fmt, const Args &... args) + { + log(level::debug, fmt, args...); + } - template - void warn(const wchar_t *fmt, const Args &... args) - { - log(level::warn, fmt, args...); - } + template + void info(const wchar_t *fmt, const Args &... args) + { + log(level::info, fmt, args...); + } - template - void error(const wchar_t *fmt, const Args &... args) - { - log(level::err, fmt, args...); - } + template + void warn(const wchar_t *fmt, const Args &... args) + { + log(level::warn, fmt, args...); + } - template - void critical(const wchar_t *fmt, const Args &... args) - { - log(level::critical, fmt, args...); - } + template + void error(const wchar_t *fmt, const Args &... args) + { + log(level::err, fmt, args...); + } + + template + void critical(const wchar_t *fmt, const Args &... args) + { + log(level::critical, fmt, args...); + } #endif // _WIN32 -#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT +#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT - 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. - // each sink will get a seperate instance of the formatter object. - void set_formatter(std::unique_ptr f); + // set formatting for the sinks in this logger. + // each sink will get a seperate instance of the formatter object. + void set_formatter(std::unique_ptr 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 - void flush(); - void flush_on(level::level_enum log_level); - level::level_enum flush_level() const; + // flush functions + void flush(); + void flush_on(level::level_enum log_level); + level::level_enum flush_level() const; - // sinks - const std::vector &sinks() const; + // sinks + const std::vector &sinks() const; - std::vector &sinks(); + std::vector &sinks(); - // error handler - void set_error_handler(err_handler); - - // create new logger with same sinks and configuration. - virtual std::shared_ptr clone(std::string logger_name); + // error handler + void set_error_handler(err_handler); - protected: - virtual void sink_it_(details::log_msg &msg); + // create new logger with same sinks and configuration. + virtual std::shared_ptr clone(std::string logger_name); - virtual void flush_(); - bool should_flush_(const details::log_msg &msg); +protected: + virtual void sink_it_(details::log_msg &msg); - // default error handler. - // print the error to stderr with the max rate of 1 message/minute. - void err_handler_(const std::string &msg); - - const std::string name_; - std::vector sinks_; - spdlog::level_t level_{spdlog::logger::default_level()}; - spdlog::level_t flush_level_{level::off}; - err_handler custom_err_handler_{nullptr}; + virtual void flush_(); + bool should_flush_(const details::log_msg &msg); + // default error handler. + // print the error to stderr with the max rate of 1 message/minute. + void err_handler_(const std::string &msg); + const std::string name_; + std::vector sinks_; + spdlog::level_t level_{spdlog::logger::default_level()}; + spdlog::level_t flush_level_{level::off}; + err_handler custom_err_handler_{nullptr}; }; } // namespace spdlog diff --git a/include/spdlog/sinks/sink.h b/include/spdlog/sinks/sink.h index 8515b041..bfa19e03 100644 --- a/include/spdlog/sinks/sink.h +++ b/include/spdlog/sinks/sink.h @@ -17,7 +17,7 @@ class sink public: sink(); - explicit sink(std::unique_ptr formatter); + explicit sink(std::unique_ptr formatter); virtual ~sink() = default; virtual void log(const details::log_msg &msg) = 0; virtual void flush() = 0; @@ -25,9 +25,9 @@ public: virtual void set_formatter(std::unique_ptr sink_formatter) = 0; bool should_log(level::level_enum msg_level) const; - + void set_level(level::level_enum log_level); - + level::level_enum level() const; protected: diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 0c2589e8..aaa93886 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -328,7 +328,8 @@ inline void critical(const wchar_t *fmt, const Args &... args) // #define SPDLOG_LOGGER_CALL(logger, level, ...) \ - do { \ + do \ + { \ if (logger->should_log(level)) \ logger->log(spdlog::source_loc{SPDLOG_FILE_BASENAME(__FILE__), __LINE__, SPDLOG_FUNCTION}, level, __VA_ARGS__); \ } while (0) diff --git a/tests/test_misc.cpp b/tests/test_misc.cpp index 5f4c094c..7400dd8f 100644 --- a/tests/test_misc.cpp +++ b/tests/test_misc.cpp @@ -107,7 +107,7 @@ TEST_CASE("clone-logger", "[clone]") cloned->info("Some message 2"); auto test_sink = std::static_pointer_cast(cloned->sinks()[0]); - + spdlog::drop_all(); } @@ -128,7 +128,7 @@ TEST_CASE("clone async", "[clone]") spdlog::details::os::sleep_for_millis(10); - auto test_sink = std::static_pointer_cast(cloned->sinks()[0]); + auto test_sink = std::static_pointer_cast(cloned->sinks()[0]); spdlog::drop_all(); } From f414198feeb6057d117c15a967a2ca13958afbce Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 27 Apr 2019 02:42:33 +0300 Subject: [PATCH 080/157] Cmake fix --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8bb9460d..1dadcb43 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -47,7 +47,7 @@ if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) set(SPDLOG_MASTER_PROJECT ON) endif() -option(SPDLOG_HEADER_ONLY "Header only version. Turn OFF to build as static lib" ON) +option(SPDLOG_HEADER_ONLY "Header only version. Turn OFF to build as static lib" OFF) 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)" ON) option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) @@ -107,7 +107,7 @@ endif() #--------------------------------------------------------------------------------------- install(DIRECTORY ${HEADER_BASE}/spdlog DESTINATION include) -if(!SPDLOG_HEADER_ONLY) +if(NOT SPDLOG_HEADER_ONLY) install(TARGETS spdlog ARCHIVE DESTINATION lib) endif() From 69fcaf14e5337911149c638d41bd30b97b735946 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 27 Apr 2019 18:44:48 +0300 Subject: [PATCH 081/157] wip static-lib --- CMakeLists.txt | 43 +++++++--------------- include/spdlog/async_logger.h | 4 +- include/spdlog/common.h | 7 ++-- include/spdlog/details/file_helper.h | 4 +- include/spdlog/details/log_msg.h | 4 +- include/spdlog/details/os.h | 2 +- include/spdlog/details/pattern_formatter.h | 2 +- include/spdlog/details/registry.h | 4 +- include/spdlog/details/thread_pool.h | 2 + include/spdlog/impl/async_logger.cpp | 2 +- include/spdlog/impl/file_helper.cpp | 2 +- include/spdlog/impl/log_msg.cpp | 2 +- include/spdlog/impl/logger.cpp | 2 +- include/spdlog/impl/os.cpp | 2 +- include/spdlog/impl/pattern_formatter.cpp | 4 +- include/spdlog/impl/registry.cpp | 2 +- include/spdlog/impl/sink.cpp | 2 +- include/spdlog/logger.h | 4 +- include/spdlog/sinks/sink.h | 4 +- 19 files changed, 43 insertions(+), 55 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1dadcb43..19d777a3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,8 +1,5 @@ - -# -# Copyright(c) 2015 Ruslan Baratov. +# Copyright(c) 2019 spdlog # Distributed under the MIT License (http://opensource.org/licenses/MIT) -# cmake_minimum_required(VERSION 3.1) project(spdlog VERSION 1.3.1 LANGUAGES CXX) @@ -47,48 +44,36 @@ if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) set(SPDLOG_MASTER_PROJECT ON) endif() -option(SPDLOG_HEADER_ONLY "Header only version. Turn OFF to build as static lib" OFF) +option(SPDLOG_STATIC_LIB "Build as static lib" OFF) 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)" ON) option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) -set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include") +set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include/spdlog") -if(SPDLOG_HEADER_ONLY) - add_definitions(-DSPDLOG_HEADER_ONLY) - add_library(spdlog INTERFACE) - add_library(spdlog::spdlog ALIAS spdlog) - target_include_directories( - spdlog - INTERFACE - "$" - ) - -else() - remove_definitions(-DSPDLOG_HEADER_ONLY) - file(GLOB SRC_FILES ${HEADER_BASE}/spdlog/impl/*.cpp) +if(SPDLOG_STATIC_LIB) + add_definitions(-DSPDLOG_STATIC_LIB) + file(GLOB SRC_FILES ${HEADER_BASE}/impl/*.cpp) add_library(spdlog STATIC ${SRC_FILES}) - add_library(spdlog::spdlog ALIAS spdlog) - target_include_directories( - spdlog - PUBLIC - "$" - ) + target_include_directories(spdlog PUBLIC "$") +else() + add_library(spdlog INTERFACE) + target_include_directories(spdlog INTERFACE "$") endif() +add_library(spdlog::spdlog ALIAS spdlog) + if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) find_package(fmt REQUIRED CONFIG) endif() - if(SPDLOG_FMT_EXTERNAL) target_compile_definitions(spdlog INTERFACE SPDLOG_FMT_EXTERNAL) target_link_libraries(spdlog INTERFACE fmt::fmt) endif() - if(SPDLOG_BUILD_EXAMPLES) add_subdirectory(example) endif() @@ -105,9 +90,9 @@ endif() #--------------------------------------------------------------------------------------- # install #--------------------------------------------------------------------------------------- -install(DIRECTORY ${HEADER_BASE}/spdlog DESTINATION include) +install(DIRECTORY ${HEADER_BASE} DESTINATION include) -if(NOT SPDLOG_HEADER_ONLY) +if(SPDLOG_STATIC_LIB) install(TARGETS spdlog ARCHIVE DESTINATION lib) endif() diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index b0b644a4..0178b39d 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -65,6 +65,6 @@ private: }; } // namespace spdlog -#ifdef SPDLOG_HEADER_ONLY +#ifndef SPDLOG_STATIC_LIB #include "spdlog/impl/async_logger.cpp" -#endif // SPDLOG_HEADER_ONLY +#endif diff --git a/include/spdlog/common.h b/include/spdlog/common.h index add4000b..0bcd03f5 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -23,10 +23,11 @@ #include "spdlog/fmt/fmt.h" -#ifdef SPDLOG_HEADER_ONLY -#define SPDLOG_INLINE inline -#else + +#ifdef SPDLOG_STATIC_LIB #define SPDLOG_INLINE +#else +#define SPDLOG_INLINE inline #endif // visual studio upto 2013 does not support noexcept nor constexpr diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index 9f7fceaa..6f9d7020 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -57,6 +57,6 @@ private: } // namespace details } // namespace spdlog -#ifdef SPDLOG_HEADER_ONLY +#ifndef SPDLOG_STATIC_LIB #include "spdlog/impl/file_helper.cpp" -#endif // ! SPDLOG_HEADER_ONLY +#endif diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index e9cacbb7..fea55a40 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -33,6 +33,6 @@ struct log_msg } // namespace details } // namespace spdlog -#ifdef SPDLOG_HEADER_ONLY +#ifndef SPDLOG_STATIC_LIB #include "spdlog/impl/log_msg.cpp" -#endif // SPDLOG_HEADER_ONLY +#endif diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 5f87f5fd..0467e944 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -88,6 +88,6 @@ void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target } // namespace details } // namespace spdlog -#ifdef SPDLOG_HEADER_ONLY +#ifndef SPDLOG_STATIC_LIB #include "spdlog/impl/os.cpp" #endif diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 210efd23..8866b8bd 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -97,6 +97,6 @@ private: }; } // namespace spdlog -#ifdef SPDLOG_HEADER_ONLY +#ifndef SPDLOG_STATIC_LIB #include "spdlog/impl/pattern_formatter.cpp" #endif diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 93d35e87..d6f4dbea 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -101,6 +101,6 @@ private: } // namespace details } // namespace spdlog -#ifdef SPDLOG_HEADER_ONLY +#ifndef SPDLOG_STATIC_LIB #include "spdlog/impl/registry.cpp" -#endif // SPDLOG_HEADER_ONLY +#endif diff --git a/include/spdlog/details/thread_pool.h b/include/spdlog/details/thread_pool.h index 35578971..a1efcee6 100644 --- a/include/spdlog/details/thread_pool.h +++ b/include/spdlog/details/thread_pool.h @@ -11,6 +11,8 @@ #include namespace spdlog { +class async_logger; + namespace details { using async_logger_ptr = std::shared_ptr; diff --git a/include/spdlog/impl/async_logger.cpp b/include/spdlog/impl/async_logger.cpp index e915042e..eeae49f9 100644 --- a/include/spdlog/impl/async_logger.cpp +++ b/include/spdlog/impl/async_logger.cpp @@ -1,4 +1,4 @@ -#ifndef SPDLOG_HEADER_ONLY +#ifdef SPDLOG_STATIC_LIB #include "spdlog/async_logger.h" #endif diff --git a/include/spdlog/impl/file_helper.cpp b/include/spdlog/impl/file_helper.cpp index 70a86eb8..eb8b9193 100644 --- a/include/spdlog/impl/file_helper.cpp +++ b/include/spdlog/impl/file_helper.cpp @@ -3,7 +3,7 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#ifndef SPDLOG_HEADER_ONLY +#ifdef SPDLOG_STATIC_LIB #include "spdlog/details/file_helper.h" #endif diff --git a/include/spdlog/impl/log_msg.cpp b/include/spdlog/impl/log_msg.cpp index ec4f8642..e854a1ba 100644 --- a/include/spdlog/impl/log_msg.cpp +++ b/include/spdlog/impl/log_msg.cpp @@ -1,7 +1,7 @@ #include "spdlog/details/os.h" #include "spdlog/sinks/sink.h" -#ifndef SPDLOG_HEADER_ONLY +#ifdef SPDLOG_STATIC_LIB #include "spdlog/details/log_msg.h" #endif diff --git a/include/spdlog/impl/logger.cpp b/include/spdlog/impl/logger.cpp index 7dcfc973..01316b64 100644 --- a/include/spdlog/impl/logger.cpp +++ b/include/spdlog/impl/logger.cpp @@ -1,4 +1,4 @@ -#ifndef SPDLOG_HEADER_ONLY +#ifdef SPDLOG_STATIC_LIB #include "spdlog/logger.h" #endif diff --git a/include/spdlog/impl/os.cpp b/include/spdlog/impl/os.cpp index ecd5a611..e4260dba 100644 --- a/include/spdlog/impl/os.cpp +++ b/include/spdlog/impl/os.cpp @@ -2,7 +2,7 @@ // Copyright(c) 2015 Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#ifndef SPDLOG_HEADER_ONLY +#ifdef SPDLOG_STATIC_LIB #include "spdlog/details/os.h" #endif diff --git a/include/spdlog/impl/pattern_formatter.cpp b/include/spdlog/impl/pattern_formatter.cpp index f1d43cf8..abcc7b36 100644 --- a/include/spdlog/impl/pattern_formatter.cpp +++ b/include/spdlog/impl/pattern_formatter.cpp @@ -3,9 +3,9 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#ifndef SPDLOG_HEADER_ONLY +#ifdef SPDLOG_STATIC_LIB #include "spdlog/details/pattern_formatter.h" -#endif // !SPDLOG_HEADER_ONLY +#endif #include "spdlog/details/fmt_helper.h" #include "spdlog/details/log_msg.h" diff --git a/include/spdlog/impl/registry.cpp b/include/spdlog/impl/registry.cpp index ca0247eb..9a80aeea 100644 --- a/include/spdlog/impl/registry.cpp +++ b/include/spdlog/impl/registry.cpp @@ -2,7 +2,7 @@ // Copyright(c) 2015 Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#ifndef SPDLOG_HEADER_ONLY +#ifdef SPDLOG_STATIC_LIB #include "spdlog/details/registry.h" #endif diff --git a/include/spdlog/impl/sink.cpp b/include/spdlog/impl/sink.cpp index 04adb9be..938fc73c 100644 --- a/include/spdlog/impl/sink.cpp +++ b/include/spdlog/impl/sink.cpp @@ -1,7 +1,7 @@ #include "spdlog/common.h" #include "spdlog/details/pattern_formatter.h" -#ifndef SPDLOG_HEADER_ONLY +#ifdef SPDLOG_STATIC_LIB #include "spdlog/sinks/sink.h" #endif diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 91371320..804abf33 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -340,6 +340,6 @@ protected: }; } // namespace spdlog -#ifdef SPDLOG_HEADER_ONLY +#ifndef SPDLOG_STATIC_LIB #include "spdlog/impl/logger.cpp" -#endif // SPDLOG_HEADER_ONLY +#endif diff --git a/include/spdlog/sinks/sink.h b/include/spdlog/sinks/sink.h index bfa19e03..1fc1f1d7 100644 --- a/include/spdlog/sinks/sink.h +++ b/include/spdlog/sinks/sink.h @@ -41,6 +41,6 @@ protected: } // namespace sinks } // namespace spdlog -#ifdef SPDLOG_HEADER_ONLY +#ifndef SPDLOG_STATIC_LIB #include "spdlog/impl/sink.cpp" -#endif // SPDLOG_HEADER_ONLY +#endif From c9887874bc310ccc32367c49a9c13666d471b1c9 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 27 Apr 2019 19:37:59 +0300 Subject: [PATCH 082/157] wip cmake --- CMakeLists.txt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 19d777a3..eff1ed16 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -29,6 +29,8 @@ if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCH add_compile_options("-Wfatal-errors") endif() +set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include/spdlog") + #--------------------------------------------------------------------------------------- # address sanitizers check #--------------------------------------------------------------------------------------- @@ -44,20 +46,20 @@ if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) set(SPDLOG_MASTER_PROJECT ON) endif() -option(SPDLOG_STATIC_LIB "Build as static lib" OFF) +option(SPDLOG_STATIC_LIB "Build as static lib" ON) 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)" ON) option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) -set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include/spdlog") if(SPDLOG_STATIC_LIB) add_definitions(-DSPDLOG_STATIC_LIB) file(GLOB SRC_FILES ${HEADER_BASE}/impl/*.cpp) add_library(spdlog STATIC ${SRC_FILES}) target_include_directories(spdlog PUBLIC "$") + target_link_libraries(spdlog -Wl,--as-needed) else() add_library(spdlog INTERFACE) target_include_directories(spdlog INTERFACE "$") @@ -100,4 +102,3 @@ endif() # register project in CMake user registry #--------------------------------------------------------------------------------------- export(PACKAGE ${PROJECT_NAME}) - From de1cdb2dbefbd1e8f2fc5624245c285f08689de3 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 27 Apr 2019 19:38:26 +0300 Subject: [PATCH 083/157] wip cmake --- CMakeLists.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index eff1ed16..ed57deeb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright(c) 2019 spdlog +# Copyright(c) 2019 spdlog authors # Distributed under the MIT License (http://opensource.org/licenses/MIT) cmake_minimum_required(VERSION 3.1) @@ -53,7 +53,6 @@ option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) - if(SPDLOG_STATIC_LIB) add_definitions(-DSPDLOG_STATIC_LIB) file(GLOB SRC_FILES ${HEADER_BASE}/impl/*.cpp) From 3ecc3ab7987efa91f10f600ccb92f855d2783f6e Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 27 Apr 2019 19:38:39 +0300 Subject: [PATCH 084/157] wip cmake --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ed57deeb..153fdaf4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -46,7 +46,7 @@ if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) set(SPDLOG_MASTER_PROJECT ON) endif() -option(SPDLOG_STATIC_LIB "Build as static lib" ON) +option(SPDLOG_STATIC_LIB "Build as static lib" OFF) 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)" ON) option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) From 338125b93a99253cfe80dcb77503eeba0b733702 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 27 Apr 2019 19:40:24 +0300 Subject: [PATCH 085/157] wip cmake --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 153fdaf4..4e77fd2e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -29,8 +29,6 @@ if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCH add_compile_options("-Wfatal-errors") endif() -set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include/spdlog") - #--------------------------------------------------------------------------------------- # address sanitizers check #--------------------------------------------------------------------------------------- @@ -53,6 +51,8 @@ option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) +set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include/spdlog") + if(SPDLOG_STATIC_LIB) add_definitions(-DSPDLOG_STATIC_LIB) file(GLOB SRC_FILES ${HEADER_BASE}/impl/*.cpp) From eedb43d756be3a27856e77b86423f56581b19f97 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 27 Apr 2019 19:41:25 +0300 Subject: [PATCH 086/157] wip cmake --- CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4e77fd2e..96c00762 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,9 +39,10 @@ include(cmake/sanitizers.cmake) #--------------------------------------------------------------------------------------- # 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) +else() + set(SPDLOG_MASTER_PROJECT OFF) endif() option(SPDLOG_STATIC_LIB "Build as static lib" OFF) From 7b15a3d34536b9cc9abbfde6c01c9a7df5a8b058 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 27 Apr 2019 19:42:19 +0300 Subject: [PATCH 087/157] wip cmake --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 96c00762..30cc59c2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -47,8 +47,8 @@ endif() option(SPDLOG_STATIC_LIB "Build as static lib" OFF) 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)" ON) -option(SPDLOG_BUILD_TESTS "Build tests" ${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" OFF) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) From 576e389788a612caa20bb749700122d484fa74bd Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 8 May 2019 16:34:20 +0300 Subject: [PATCH 088/157] static lib by default and tests --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 30cc59c2..c9af23ef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,10 +45,10 @@ else() set(SPDLOG_MASTER_PROJECT OFF) endif() -option(SPDLOG_STATIC_LIB "Build as static lib" OFF) +option(SPDLOG_STATIC_LIB "Build as static lib" ONg) 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" OFF) +option(SPDLOG_BUILD_TESTS "Build tests" ON) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) From 29c949ab03821fdf354e7ffa573d2cf95e794c08 Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 8 May 2019 16:36:14 +0300 Subject: [PATCH 089/157] static lib by default --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c9af23ef..179a0adf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,7 +45,7 @@ else() set(SPDLOG_MASTER_PROJECT OFF) endif() -option(SPDLOG_STATIC_LIB "Build as static lib" ONg) +option(SPDLOG_STATIC_LIB "Build as static lib" ON) 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" ON) From 5d0eb6dda5cfe7d8aaea3f3f218cd3cdf49f0dd3 Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 8 May 2019 17:16:56 +0300 Subject: [PATCH 090/157] wip static-lib --- include/spdlog/.spdlog.h.kate-swp | Bin 223 -> 0 bytes include/spdlog/details/os.h | 4 +- include/spdlog/details/periodic_worker.h | 42 ++------ include/spdlog/details/thread_pool.h | 106 +++------------------ include/spdlog/impl/os.cpp | 6 +- include/spdlog/impl/periodic_worker.cpp | 45 +++++++++ include/spdlog/impl/thread_pool.cpp | 116 +++++++++++++++++++++++ 7 files changed, 186 insertions(+), 133 deletions(-) delete mode 100644 include/spdlog/.spdlog.h.kate-swp create mode 100644 include/spdlog/impl/periodic_worker.cpp create mode 100644 include/spdlog/impl/thread_pool.cpp diff --git a/include/spdlog/.spdlog.h.kate-swp b/include/spdlog/.spdlog.h.kate-swp deleted file mode 100644 index 546ce39c13ff21174480c7ca37b4bbaa0f150501..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 223 zcmZQzU=Z?7EJ;-eE>A2_aLdd|RWQ;sU|?VnacVxPmHPaMuS>XK#qA{v7f2m=-xBNz zlraKgS0HA(zT6cq;06?6R7ddL(fA(78uUPt=mJbIfgm6Qrh*w_q7qPu6^I#K5PUWe UKiD-Gq#Ps<;TAmwbX0OBhn$^ZZW diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 0467e944..5cf97635 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -68,9 +68,9 @@ size_t thread_id() SPDLOG_NOEXCEPT; // See https://github.com/gabime/spdlog/issues/609 void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT; -std::string filename_to_str(const filename_t &filename); +std::string filename_to_str(const filename_t &filename) SPDLOG_NOEXCEPT; -int pid(); +int pid() SPDLOG_NOEXCEPT; // Determine if the terminal supports colors // Source: https://github.com/agauniyal/rang/ diff --git a/include/spdlog/details/periodic_worker.h b/include/spdlog/details/periodic_worker.h index fa6488d1..9e9cd731 100644 --- a/include/spdlog/details/periodic_worker.h +++ b/include/spdlog/details/periodic_worker.h @@ -23,43 +23,12 @@ namespace details { class periodic_worker { public: - periodic_worker(const std::function &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 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 std::function &callback_fun, std::chrono::seconds interval); periodic_worker(const periodic_worker &) = delete; periodic_worker &operator=(const periodic_worker &) = delete; - // stop the worker thread and join it - ~periodic_worker() - { - if (worker_thread_.joinable()) - { - { - std::lock_guard lock(mutex_); - active_ = false; - } - cv_.notify_one(); - worker_thread_.join(); - } - } + ~periodic_worker(); + private: bool active_; @@ -69,3 +38,8 @@ private: }; } // namespace details } // namespace spdlog + + +#ifndef SPDLOG_STATIC_LIB +#include "spdlog/impl/periodic_worker.cpp" +#endif diff --git a/include/spdlog/details/thread_pool.h b/include/spdlog/details/thread_pool.h index a1efcee6..80c2d11f 100644 --- a/include/spdlog/details/thread_pool.h +++ b/include/spdlog/details/thread_pool.h @@ -123,118 +123,36 @@ public: using item_type = async_msg; using q_type = details::mpmc_blocking_queue; - 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); - } - } - + thread_pool(size_t q_max_items, size_t threads_n); // message all threads to terminate gracefully join them - ~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); - } + ~thread_pool(); - for (auto &t : threads_) - { - t.join(); - } - } - catch (...) - { - } - } thread_pool(const 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) - { - async_msg async_m(std::move(worker_ptr), async_msg_type::log, msg); - post_async_msg_(std::move(async_m), 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); + size_t overrun_counter(); - 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: q_type q_; std::vector threads_; - void 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 worker_loop_() - { - while (process_next_msg_()) {}; - } + void post_async_msg_(async_msg &&new_msg, async_overflow_policy overflow_policy); + void worker_loop_(); // process next message in the queue // return true if this thread should still be active (while no terminate msg // was received) - bool process_next_msg_() - { - 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; - } + bool process_next_msg_(); }; } // namespace details } // namespace spdlog + +#ifndef SPDLOG_STATIC_LIB +#include "spdlog/impl/thread_pool.cpp" +#endif \ No newline at end of file diff --git a/include/spdlog/impl/os.cpp b/include/spdlog/impl/os.cpp index e4260dba..ed174cf1 100644 --- a/include/spdlog/impl/os.cpp +++ b/include/spdlog/impl/os.cpp @@ -340,19 +340,19 @@ SPDLOG_INLINE void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT // 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_INLINE std::string filename_to_str(const filename_t &filename) SPDLOG_NOEXCEPT { std::wstring_convert, wchar_t> c; return c.to_bytes(filename); } #else -SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) +SPDLOG_INLINE std::string filename_to_str(const filename_t &filename) SPDLOG_NOEXCEPT { return filename; } #endif -SPDLOG_INLINE int pid() +SPDLOG_INLINE int pid() SPDLOG_NOEXCEPT { #ifdef _WIN32 diff --git a/include/spdlog/impl/periodic_worker.cpp b/include/spdlog/impl/periodic_worker.cpp new file mode 100644 index 00000000..6c0e997d --- /dev/null +++ b/include/spdlog/impl/periodic_worker.cpp @@ -0,0 +1,45 @@ +// +// Created by gabi on 5/8/19. +// + +#ifdef SPDLOG_STATIC_LIB +#include "spdlog/details/periodic_worker.h" +#endif + +#include "spdlog/common.h" + +SPDLOG_INLINE spdlog::details::periodic_worker::periodic_worker(const std::function &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 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 spdlog::details::periodic_worker::~periodic_worker() +{ + if (worker_thread_.joinable()) + { + { + std::lock_guard lock(mutex_); + active_ = false; + } + cv_.notify_one(); + worker_thread_.join(); + } +} + diff --git a/include/spdlog/impl/thread_pool.cpp b/include/spdlog/impl/thread_pool.cpp new file mode 100644 index 00000000..66c26fd6 --- /dev/null +++ b/include/spdlog/impl/thread_pool.cpp @@ -0,0 +1,116 @@ +#ifdef SPDLOG_STATIC_LIB +#include "spdlog/async_logger.h" +#include "spdlog/details/thread_pool.h" + +template class spdlog::details::mpmc_blocking_queue; + +#endif + +#include "spdlog/common.h" + +SPDLOG_INLINE spdlog::details::thread_pool::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 +SPDLOG_INLINE spdlog::details::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 spdlog::details::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 spdlog::details::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 spdlog::details::thread_pool::overrun_counter() +{ + return q_.overrun_counter(); +} + +void SPDLOG_INLINE spdlog::details::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 spdlog::details::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 spdlog::details::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; +} + + + + From 1ac6c9f9c21e94b0d3934f3fef2402f86824c511 Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 8 May 2019 17:17:11 +0300 Subject: [PATCH 091/157] clang-format static-lib --- include/spdlog/common.h | 1 - include/spdlog/details/periodic_worker.h | 2 - include/spdlog/details/thread_pool.h | 2 - include/spdlog/impl/periodic_worker.cpp | 1 - include/spdlog/impl/thread_pool.cpp | 62 ++++++++++++------------ 5 files changed, 30 insertions(+), 38 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 0bcd03f5..7af05411 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -23,7 +23,6 @@ #include "spdlog/fmt/fmt.h" - #ifdef SPDLOG_STATIC_LIB #define SPDLOG_INLINE #else diff --git a/include/spdlog/details/periodic_worker.h b/include/spdlog/details/periodic_worker.h index 9e9cd731..03e611aa 100644 --- a/include/spdlog/details/periodic_worker.h +++ b/include/spdlog/details/periodic_worker.h @@ -29,7 +29,6 @@ public: // stop the worker thread and join it ~periodic_worker(); - private: bool active_; std::thread worker_thread_; @@ -39,7 +38,6 @@ private: } // namespace details } // namespace spdlog - #ifndef SPDLOG_STATIC_LIB #include "spdlog/impl/periodic_worker.cpp" #endif diff --git a/include/spdlog/details/thread_pool.h b/include/spdlog/details/thread_pool.h index 80c2d11f..a872c303 100644 --- a/include/spdlog/details/thread_pool.h +++ b/include/spdlog/details/thread_pool.h @@ -127,7 +127,6 @@ public: // message all threads to terminate gracefully join them ~thread_pool(); - thread_pool(const thread_pool &) = delete; thread_pool &operator=(thread_pool &&) = delete; @@ -135,7 +134,6 @@ public: void post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy overflow_policy); size_t overrun_counter(); - private: q_type q_; diff --git a/include/spdlog/impl/periodic_worker.cpp b/include/spdlog/impl/periodic_worker.cpp index 6c0e997d..33f82ae9 100644 --- a/include/spdlog/impl/periodic_worker.cpp +++ b/include/spdlog/impl/periodic_worker.cpp @@ -42,4 +42,3 @@ SPDLOG_INLINE spdlog::details::periodic_worker::~periodic_worker() worker_thread_.join(); } } - diff --git a/include/spdlog/impl/thread_pool.cpp b/include/spdlog/impl/thread_pool.cpp index 66c26fd6..e97c30a5 100644 --- a/include/spdlog/impl/thread_pool.cpp +++ b/include/spdlog/impl/thread_pool.cpp @@ -8,19 +8,20 @@ template class spdlog::details::mpmc_blocking_queue; #include "spdlog/common.h" -SPDLOG_INLINE spdlog::details::thread_pool::thread_pool(size_t q_max_items, size_t threads_n) : q_(q_max_items) +SPDLOG_INLINE spdlog::details::thread_pool::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); - } + // 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 @@ -43,7 +44,8 @@ SPDLOG_INLINE spdlog::details::thread_pool::~thread_pool() } } -void SPDLOG_INLINE spdlog::details::thread_pool::post_log(async_logger_ptr &&worker_ptr, details::log_msg &msg, async_overflow_policy overflow_policy) +void SPDLOG_INLINE spdlog::details::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); @@ -90,27 +92,23 @@ bool SPDLOG_INLINE spdlog::details::thread_pool::process_next_msg_() 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::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; - } + case async_msg_type::terminate: + { + return false; + } } assert(false && "Unexpected async_msg_type"); return true; } - - - - From c031ae2aabb9f6356ee107c6c6ff6bf4edee8b6b Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 8 May 2019 17:37:25 +0300 Subject: [PATCH 092/157] Cmake message --- CMakeLists.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 179a0adf..6ebb465e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,7 +12,7 @@ if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE) endif() -message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) + #--------------------------------------------------------------------------------------- # compiler config @@ -54,6 +54,9 @@ option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include/spdlog") +message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) +message(STATUS "Static lib: " ${SPDLOG_STATIC_LIB}) + if(SPDLOG_STATIC_LIB) add_definitions(-DSPDLOG_STATIC_LIB) file(GLOB SRC_FILES ${HEADER_BASE}/impl/*.cpp) From 6651a48c4db192caee3c3bba521b3bcd6141f4f9 Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 8 May 2019 17:50:23 +0300 Subject: [PATCH 093/157] wip --- include/spdlog/impl/base_sink.cpp | 54 +++++++++++++++++++++++++++++ include/spdlog/impl/thread_pool.cpp | 2 -- include/spdlog/sinks/base_sink.h | 45 ++++++------------------ 3 files changed, 64 insertions(+), 37 deletions(-) create mode 100644 include/spdlog/impl/base_sink.cpp diff --git a/include/spdlog/impl/base_sink.cpp b/include/spdlog/impl/base_sink.cpp new file mode 100644 index 00000000..13b16ab2 --- /dev/null +++ b/include/spdlog/impl/base_sink.cpp @@ -0,0 +1,54 @@ +#ifdef SPDLOG_STATIC_LIB +#include "spdlog/sinks/base_sink.h" + +#include "spdlog/details/null_mutex.h" +#include +template class spdlog::sinks::base_sink; +template class spdlog::sinks::base_sink; +#endif + +#include "spdlog/common.h" +#include "spdlog/details/pattern_formatter.h" + +template +void SPDLOG_INLINE spdlog::sinks::base_sink::log(const details::log_msg &msg) +{ + std::lock_guard lock(mutex_); + sink_it_(msg); +} + +template +void SPDLOG_INLINE spdlog::sinks::base_sink::flush() +{ + std::lock_guard lock(mutex_); + flush_(); +} + +template +void SPDLOG_INLINE spdlog::sinks::base_sink::set_pattern(const std::string &pattern) +{ + std::lock_guard lock(mutex_); + set_pattern_(pattern); +} + +template +void SPDLOG_INLINE spdlog::sinks::base_sink::set_formatter(std::unique_ptr sink_formatter) +{ + std::lock_guard lock(mutex_); + set_formatter_(std::move(sink_formatter)); +} + +template +void SPDLOG_INLINE spdlog::sinks::base_sink::set_pattern_(const std::string &pattern) +{ + set_formatter_(details::make_unique(pattern)); +} + +template +void SPDLOG_INLINE spdlog::sinks::base_sink::set_formatter_(std::unique_ptr sink_formatter) +{ + formatter_ = std::move(sink_formatter); +} + + + diff --git a/include/spdlog/impl/thread_pool.cpp b/include/spdlog/impl/thread_pool.cpp index e97c30a5..fa8f961d 100644 --- a/include/spdlog/impl/thread_pool.cpp +++ b/include/spdlog/impl/thread_pool.cpp @@ -11,8 +11,6 @@ template class spdlog::details::mpmc_blocking_queue; SPDLOG_INLINE spdlog::details::thread_pool::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 " diff --git a/include/spdlog/sinks/base_sink.h b/include/spdlog/sinks/base_sink.h index 22595182..2ed1730a 100644 --- a/include/spdlog/sinks/base_sink.h +++ b/include/spdlog/sinks/base_sink.h @@ -13,7 +13,6 @@ #include "spdlog/common.h" #include "spdlog/details/log_msg.h" -#include "spdlog/formatter.h" #include "spdlog/sinks/sink.h" namespace spdlog { @@ -25,45 +24,21 @@ public: base_sink() = default; base_sink(const base_sink &) = delete; base_sink &operator=(const base_sink &) = delete; - - void log(const details::log_msg &msg) final - { - std::lock_guard lock(mutex_); - sink_it_(msg); - } - - void flush() final - { - std::lock_guard lock(mutex_); - flush_(); - } - - void set_pattern(const std::string &pattern) final - { - std::lock_guard lock(mutex_); - set_pattern_(pattern); - } - - void set_formatter(std::unique_ptr sink_formatter) final - { - std::lock_guard lock(mutex_); - set_formatter_(std::move(sink_formatter)); - } + void log(const details::log_msg &msg) final; + void flush() final;void set_pattern(const std::string &pattern) final; + void set_formatter(std::unique_ptr sink_formatter) final; protected: virtual void sink_it_(const details::log_msg &msg) = 0; virtual void flush_() = 0; - - virtual void set_pattern_(const std::string &pattern) - { - set_formatter_(details::make_unique(pattern)); - } - - virtual void set_formatter_(std::unique_ptr sink_formatter) - { - formatter_ = std::move(sink_formatter); - } + virtual void set_pattern_(const std::string &pattern); + virtual void set_formatter_(std::unique_ptr sink_formatter); Mutex mutex_; }; } // namespace sinks } // namespace spdlog + + +#ifndef SPDLOG_STATIC_LIB +#include "spdlog/impl/base_sink.cpp" +#endif \ No newline at end of file From 2b90ab496a507dbf3c24358fcf201f0ab25cdec1 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 10 May 2019 18:48:03 +0300 Subject: [PATCH 094/157] ansicolor_sink.cpp --- include/spdlog/impl/ansicolor_sink.cpp | 105 +++++++++++++++++++++++++ include/spdlog/impl/base_sink.cpp | 15 ++-- include/spdlog/sinks/ansicolor_sink.h | 98 ++++------------------- include/spdlog/sinks/base_sink.h | 4 +- 4 files changed, 127 insertions(+), 95 deletions(-) create mode 100644 include/spdlog/impl/ansicolor_sink.cpp diff --git a/include/spdlog/impl/ansicolor_sink.cpp b/include/spdlog/impl/ansicolor_sink.cpp new file mode 100644 index 00000000..97bbfd8e --- /dev/null +++ b/include/spdlog/impl/ansicolor_sink.cpp @@ -0,0 +1,105 @@ +#ifdef SPDLOG_STATIC_LIB +#include "spdlog/sinks/ansicolor_sink.h" +#endif + +#include "spdlog/details/os.h" + +template +SPDLOG_INLINE spdlog::sinks::ansicolor_sink::ansicolor_sink() + : target_file_(TargetStream::stream()) + , mutex_(ConsoleMutex::mutex()) + +{ + should_do_colors_ = details::os::in_terminal(target_file_) && details::os::is_color_terminal(); + 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 +SPDLOG_INLINE void spdlog::sinks::ansicolor_sink::set_color( + level::level_enum color_level, const std::string &color) +{ + std::lock_guard lock(mutex_); + colors_[color_level] = color; +} + +template +SPDLOG_INLINE void spdlog::sinks::ansicolor_sink::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 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 +SPDLOG_INLINE void spdlog::sinks::ansicolor_sink::flush() +{ + std::lock_guard lock(mutex_); + fflush(target_file_); +} + +template +SPDLOG_INLINE void spdlog::sinks::ansicolor_sink::set_pattern(const std::string &pattern) +{ + std::lock_guard lock(mutex_); + formatter_ = std::unique_ptr(new pattern_formatter(pattern)); +} + +template +SPDLOG_INLINE void spdlog::sinks::ansicolor_sink::set_formatter( + std::unique_ptr sink_formatter) +{ + std::lock_guard lock(mutex_); + formatter_ = std::move(sink_formatter); +} + +template +SPDLOG_INLINE bool spdlog::sinks::ansicolor_sink::should_color() +{ + return should_do_colors_; +} + +template +SPDLOG_INLINE void spdlog::sinks::ansicolor_sink::print_ccode_(const std::string &color_code) +{ + fwrite(color_code.data(), sizeof(char), color_code.size(), target_file_); +} + +template +SPDLOG_INLINE void spdlog::sinks::ansicolor_sink::print_range_( + const fmt::memory_buffer &formatted, size_t start, size_t end) +{ + fwrite(formatted.data() + start, sizeof(char), end - start, target_file_); +} + +// template instantiate stdout_mt, stdout_st +template class spdlog::sinks::ansicolor_sink; +template class spdlog::sinks::ansicolor_sink; + +// template instantiate stderr_mt, stderr_st +template class spdlog::sinks::ansicolor_sink; +template class spdlog::sinks::ansicolor_sink; diff --git a/include/spdlog/impl/base_sink.cpp b/include/spdlog/impl/base_sink.cpp index 13b16ab2..e3b5b125 100644 --- a/include/spdlog/impl/base_sink.cpp +++ b/include/spdlog/impl/base_sink.cpp @@ -10,45 +10,42 @@ template class spdlog::sinks::base_sink; #include "spdlog/common.h" #include "spdlog/details/pattern_formatter.h" -template +template void SPDLOG_INLINE spdlog::sinks::base_sink::log(const details::log_msg &msg) { std::lock_guard lock(mutex_); sink_it_(msg); } -template +template void SPDLOG_INLINE spdlog::sinks::base_sink::flush() { std::lock_guard lock(mutex_); flush_(); } -template +template void SPDLOG_INLINE spdlog::sinks::base_sink::set_pattern(const std::string &pattern) { std::lock_guard lock(mutex_); set_pattern_(pattern); } -template +template void SPDLOG_INLINE spdlog::sinks::base_sink::set_formatter(std::unique_ptr sink_formatter) { std::lock_guard lock(mutex_); set_formatter_(std::move(sink_formatter)); } -template +template void SPDLOG_INLINE spdlog::sinks::base_sink::set_pattern_(const std::string &pattern) { set_formatter_(details::make_unique(pattern)); } -template +template void SPDLOG_INLINE spdlog::sinks::base_sink::set_formatter_(std::unique_ptr sink_formatter) { formatter_ = std::move(sink_formatter); } - - - diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index 1cb797ba..44d5a287 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -11,9 +11,7 @@ #include "spdlog/details/console_globals.h" #include "spdlog/details/null_mutex.h" -#include "spdlog/details/os.h" #include "spdlog/sinks/sink.h" - #include #include #include @@ -28,36 +26,22 @@ namespace sinks { * of the message. * If no color terminal detected, omit the escape codes. */ -template +template class ansicolor_sink final : public sink { public: using mutex_t = typename ConsoleMutex::mutex_t; - ansicolor_sink() - : target_file_(TargetStream::stream()) - , mutex_(ConsoleMutex::mutex()) - - { - should_do_colors_ = details::os::in_terminal(target_file_) && details::os::is_color_terminal(); - 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(); ~ansicolor_sink() override = default; ansicolor_sink(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) - { - std::lock_guard lock(mutex_); - colors_[color_level] = color; - } + void set_color(level::level_enum color_level, const std::string &color); + void log(const details::log_msg &msg) override; + void flush() override; + void set_pattern(const std::string &pattern) final; + void set_formatter(std::unique_ptr sink_formatter) override; + bool should_color(); /// Formatting codes const std::string reset = "\033[m"; @@ -89,70 +73,13 @@ public: const std::string on_cyan = "\033[46m"; 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 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 lock(mutex_); - fflush(target_file_); - } - - void set_pattern(const std::string &pattern) final - { - std::lock_guard lock(mutex_); - formatter_ = std::unique_ptr(new pattern_formatter(pattern)); - } - - void set_formatter(std::unique_ptr sink_formatter) override - { - std::lock_guard lock(mutex_); - formatter_ = std::move(sink_formatter); - } - - bool should_color() - { - return should_do_colors_; - } - private: - 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_; mutex_t &mutex_; - bool should_do_colors_; std::unordered_map 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; @@ -162,5 +89,8 @@ using ansicolor_stderr_sink_mt = ansicolor_sink; } // namespace sinks - } // namespace spdlog + +#ifndef SPDLOG_STATIC_LIB +#include "spdlog/impl/ansicolor_sink.cpp" +#endif \ No newline at end of file diff --git a/include/spdlog/sinks/base_sink.h b/include/spdlog/sinks/base_sink.h index 2ed1730a..000a6e20 100644 --- a/include/spdlog/sinks/base_sink.h +++ b/include/spdlog/sinks/base_sink.h @@ -25,7 +25,8 @@ public: base_sink(const base_sink &) = delete; base_sink &operator=(const base_sink &) = delete; void log(const details::log_msg &msg) final; - void flush() final;void set_pattern(const std::string &pattern) final; + void flush() final; + void set_pattern(const std::string &pattern) final; void set_formatter(std::unique_ptr sink_formatter) final; protected: @@ -38,7 +39,6 @@ protected: } // namespace sinks } // namespace spdlog - #ifndef SPDLOG_STATIC_LIB #include "spdlog/impl/base_sink.cpp" #endif \ No newline at end of file From 17bec5c3cee293a0d56d27fd3faa6f17655b47ea Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 11 May 2019 01:33:48 +0300 Subject: [PATCH 095/157] Use fmt src file instead of inline in static lib build --- include/spdlog/fmt/fmt.h | 4 +- include/spdlog/impl/fmt-format.cpp | 59 ++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 include/spdlog/impl/fmt-format.cpp diff --git a/include/spdlog/fmt/fmt.h b/include/spdlog/fmt/fmt.h index 616af0cc..bb644839 100644 --- a/include/spdlog/fmt/fmt.h +++ b/include/spdlog/fmt/fmt.h @@ -11,15 +11,17 @@ // #if !defined(SPDLOG_FMT_EXTERNAL) +#ifndef SPDLOG_STATIC_LIB #ifndef FMT_HEADER_ONLY #define FMT_HEADER_ONLY #endif +#endif #ifndef FMT_USE_WINDOWS_H #define FMT_USE_WINDOWS_H 0 #endif #include "bundled/core.h" #include "bundled/format.h" -#else // external fmtlib +#else // SPDLOG_FMT_EXTERNAL is defined - use external fmtlib #include #include #endif diff --git a/include/spdlog/impl/fmt-format.cpp b/include/spdlog/impl/fmt-format.cpp new file mode 100644 index 00000000..dadfc8dd --- /dev/null +++ b/include/spdlog/impl/fmt-format.cpp @@ -0,0 +1,59 @@ +// Formatting library for C++ +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include "fmt/format-inl.h" + +FMT_BEGIN_NAMESPACE +template struct internal::basic_data; +template FMT_API internal::locale_ref::locale_ref(const std::locale &loc); +template FMT_API std::locale internal::locale_ref::get() const; + +// Explicit instantiations for char. + +template FMT_API char internal::thousands_sep_impl(locale_ref); + +template FMT_API void internal::basic_buffer::append(const char *, const char *); + +template FMT_API void internal::arg_map::init( + const basic_format_args &args); + +template FMT_API int internal::char_traits::format_float( + char *, std::size_t, const char *, int, double); + +template FMT_API int internal::char_traits::format_float( + char *, std::size_t, const char *, int, long double); + +template FMT_API std::string internal::vformat( + string_view, basic_format_args); + +template FMT_API format_context::iterator internal::vformat_to( + internal::buffer &, string_view, basic_format_args); + +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::append( + const wchar_t *, const wchar_t *); + +template FMT_API void internal::arg_map::init( + const basic_format_args &); + +template FMT_API int internal::char_traits::format_float( + wchar_t *, std::size_t, const wchar_t *, int, double); + +template FMT_API int internal::char_traits::format_float( + wchar_t *, std::size_t, const wchar_t *, int, long double); + +template FMT_API std::wstring internal::vformat( + wstring_view, basic_format_args); +FMT_END_NAMESPACE From 14381fe8d00f86f63ca71e853068c90c8b11453e Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sat, 11 May 2019 03:05:22 +0300 Subject: [PATCH 096/157] Update os.h --- include/spdlog/details/os.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 5cf97635..8858ae68 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -5,6 +5,7 @@ #pragma once #include "spdlog/common.h" +#include // std::time_t namespace spdlog { namespace details { From 49708f209b13d628db1097140c86cf9ae5994676 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 11 May 2019 12:28:36 +0300 Subject: [PATCH 097/157] fix inclusion of fmt --- include/spdlog/fmt/fmt.h | 4 +- include/spdlog/impl/fmt-format.cpp | 64 ++++++++++++++++-------------- 2 files changed, 36 insertions(+), 32 deletions(-) diff --git a/include/spdlog/fmt/fmt.h b/include/spdlog/fmt/fmt.h index bb644839..c8f47158 100644 --- a/include/spdlog/fmt/fmt.h +++ b/include/spdlog/fmt/fmt.h @@ -22,6 +22,6 @@ #include "bundled/core.h" #include "bundled/format.h" #else // SPDLOG_FMT_EXTERNAL is defined - use external fmtlib -#include -#include +#include "fmt/core.h" +#include "fmt/format.h" #endif diff --git a/include/spdlog/impl/fmt-format.cpp b/include/spdlog/impl/fmt-format.cpp index dadfc8dd..70ccb8a3 100644 --- a/include/spdlog/impl/fmt-format.cpp +++ b/include/spdlog/impl/fmt-format.cpp @@ -5,55 +5,59 @@ // // For the license information refer to format.h. +#if !defined(SPDLOG_FMT_EXTERNAL) +#include "spdlog/fmt/bundled/format-inl.h" +#else #include "fmt/format-inl.h" +#endif FMT_BEGIN_NAMESPACE -template struct internal::basic_data; -template FMT_API internal::locale_ref::locale_ref(const std::locale &loc); -template FMT_API std::locale internal::locale_ref::get() const; + template struct internal::basic_data; + template FMT_API internal::locale_ref::locale_ref(const std::locale &loc); + template FMT_API std::locale internal::locale_ref::get() const; // Explicit instantiations for char. -template FMT_API char internal::thousands_sep_impl(locale_ref); + template FMT_API char internal::thousands_sep_impl(locale_ref); -template FMT_API void internal::basic_buffer::append(const char *, const char *); + template FMT_API void internal::basic_buffer::append(const char *, const char *); -template FMT_API void internal::arg_map::init( - const basic_format_args &args); + template FMT_API void internal::arg_map::init( + const basic_format_args &args); -template FMT_API int internal::char_traits::format_float( - char *, std::size_t, const char *, int, double); + template FMT_API int internal::char_traits::format_float( + char *, std::size_t, const char *, int, double); -template FMT_API int internal::char_traits::format_float( - char *, std::size_t, const char *, int, long double); + template FMT_API int internal::char_traits::format_float( + char *, std::size_t, const char *, int, long double); -template FMT_API std::string internal::vformat( - string_view, basic_format_args); + template FMT_API std::string internal::vformat( + string_view, basic_format_args); -template FMT_API format_context::iterator internal::vformat_to( - internal::buffer &, string_view, basic_format_args); + template FMT_API format_context::iterator internal::vformat_to( + internal::buffer &, string_view, basic_format_args); -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); + 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 wchar_t internal::thousands_sep_impl(locale_ref); -template FMT_API void internal::basic_buffer::append( - const wchar_t *, const wchar_t *); + template FMT_API void internal::basic_buffer::append( + const wchar_t *, const wchar_t *); -template FMT_API void internal::arg_map::init( - const basic_format_args &); + template FMT_API void internal::arg_map::init( + const basic_format_args &); -template FMT_API int internal::char_traits::format_float( - wchar_t *, std::size_t, const wchar_t *, int, double); + template FMT_API int internal::char_traits::format_float( + wchar_t *, std::size_t, const wchar_t *, int, double); -template FMT_API int internal::char_traits::format_float( - wchar_t *, std::size_t, const wchar_t *, int, long double); + template FMT_API int internal::char_traits::format_float( + wchar_t *, std::size_t, const wchar_t *, int, long double); -template FMT_API std::wstring internal::vformat( - wstring_view, basic_format_args); + template FMT_API std::wstring internal::vformat( + wstring_view, basic_format_args); FMT_END_NAMESPACE From 9564eb2edb81ad099b617e66699dbe11a5e1efd3 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 11 May 2019 13:19:53 +0300 Subject: [PATCH 098/157] Moved cpp files to inl.h --- example/example.cpp | 227 +----------------- .../async_logger.cpp => async_logger-inl.h} | 4 - include/spdlog/async_logger.h | 2 +- .../file_helper-inl.h} | 4 - include/spdlog/details/file_helper.h | 2 +- .../log_msg.cpp => details/log_msg-inl.h} | 4 - include/spdlog/details/log_msg.h | 2 +- .../spdlog/{impl/os.cpp => details/os-inl.h} | 3 - include/spdlog/details/os.h | 2 +- .../pattern_formatter-inl.h} | 4 - include/spdlog/details/pattern_formatter.h | 2 +- .../periodic_worker-inl.h} | 4 - include/spdlog/details/periodic_worker.h | 2 +- .../registry.cpp => details/registry-inl.h} | 3 - include/spdlog/details/registry.h | 2 +- .../thread_pool-inl.h} | 7 - include/spdlog/details/thread_pool.h | 2 +- .../spdlog/{impl/logger.cpp => logger-inl.h} | 4 - include/spdlog/logger.h | 2 +- .../ansicolor_sink-inl.h} | 12 - include/spdlog/sinks/ansicolor_sink.h | 2 +- .../base_sink.cpp => sinks/base_sink-inl.h} | 9 - include/spdlog/sinks/base_sink.h | 2 +- .../{impl/sink.cpp => sinks/sink-inl.h} | 4 - include/spdlog/sinks/sink.h | 2 +- .../impl/fmt-format.cpp => src/format.cc | 0 26 files changed, 16 insertions(+), 297 deletions(-) rename include/spdlog/{impl/async_logger.cpp => async_logger-inl.h} (97%) rename include/spdlog/{impl/file_helper.cpp => details/file_helper-inl.h} (97%) rename include/spdlog/{impl/log_msg.cpp => details/log_msg-inl.h} (90%) rename include/spdlog/{impl/os.cpp => details/os-inl.h} (99%) rename include/spdlog/{impl/pattern_formatter.cpp => details/pattern_formatter-inl.h} (99%) rename include/spdlog/{impl/periodic_worker.cpp => details/periodic_worker-inl.h} (92%) rename include/spdlog/{impl/registry.cpp => details/registry-inl.h} (99%) rename include/spdlog/{impl/thread_pool.cpp => details/thread_pool-inl.h} (93%) rename include/spdlog/{impl/logger.cpp => logger-inl.h} (98%) rename include/spdlog/{impl/ansicolor_sink.cpp => sinks/ansicolor_sink-inl.h} (84%) rename include/spdlog/{impl/base_sink.cpp => sinks/base_sink-inl.h} (82%) rename include/spdlog/{impl/sink.cpp => sinks/sink-inl.h} (92%) rename include/spdlog/impl/fmt-format.cpp => src/format.cc (100%) diff --git a/example/example.cpp b/example/example.cpp index 345f8bd1..dc3ebc75 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -7,229 +7,10 @@ // // -#include - -void stdout_logger_example(); -void basic_example(); -void rotating_example(); -void daily_example(); -void async_example(); -void binary_example(); -void trace_example(); -void multi_sink_example(); -void user_defined_example(); -void err_handler_example(); -void syslog_example(); -void clone_example(); #include "spdlog/spdlog.h" -int main(int, char *[]) -{ - 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::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); - spdlog::info("Support for floats {:03.2f}", 1.23456); - spdlog::info("Positional args are {1} {0}..", "too", "supported"); - spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left"); - - // Runtime log levels - spdlog::set_level(spdlog::level::info); // Set global log level to info - spdlog::debug("This message should not be displayed!"); - spdlog::set_level(spdlog::level::trace); // Set specific logger's log level - spdlog::debug("This message should be displayed.."); - - // Customize msg format for all loggers - spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v"); - spdlog::info("This an info message with custom format"); - spdlog::set_pattern("%+"); // back to default format - - try - { - stdout_logger_example(); - basic_example(); - rotating_example(); - daily_example(); - clone_example(); - async_example(); - binary_example(); - multi_sink_example(); - user_defined_example(); - err_handler_example(); - trace_example(); - - // Flush all *registered* loggers using a worker thread every 3 seconds. - // note: registered loggers *must* be thread safe for this to work correctly! - spdlog::flush_every(std::chrono::seconds(3)); - - // Apply some function on all registered loggers - spdlog::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); - - // Release all spdlog resources, and drop all loggers in the registry. - // This is optional (only mandatory if using windows + async log). - spdlog::shutdown(); - } - - // Exceptions will only be thrown upon failed logger or sink construction (not during logging). - catch (const spdlog::spdlog_ex &ex) - { - std::printf("Log initialization failed: %s\n", ex.what()); - return 1; - } -} - -#include "spdlog/sinks/stdout_color_sinks.h" -// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed. -void stdout_logger_example() -{ - // Create color multi threaded logger. - auto console = spdlog::stdout_color_mt("console"); - // or for stderr: - // auto console = spdlog::stderr_color_mt("error-logger"); -} - -#include "spdlog/sinks/basic_file_sink.h" -void basic_example() -{ - // Create basic file logger (not rotated). - auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt"); -} - -#include "spdlog/sinks/rotating_file_sink.h" -void rotating_example() -{ - // Create a file rotating logger with 5mb size max and 3 rotated files. - auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); -} - -#include "spdlog/sinks/daily_file_sink.h" -void daily_example() -{ - // Create a daily logger - a new file is created every day on 2:30am. - auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); -} - -// Clone a logger and give it new name. -// Useful for creating component/subsystem loggers from some "root" logger. -void clone_example() -{ - auto network_logger = spdlog::default_logger()->clone("network"); - network_logger->info("Logging network stuff.."); -} - -#include "spdlog/async.h" -void async_example() -{ - // Default thread pool settings can be modified *before* creating the async logger: - // spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread. - auto async_file = spdlog::basic_logger_mt("async_file_logger", "logs/async_log.txt"); - // alternatively: - // auto async_file = spdlog::create_async("async_file_logger", "logs/async_log.txt"); - - for (int i = 1; i < 101; ++i) - { - async_file->info("Async message #{}", i); - } -} - -// Log binary data as hex. -// Many types of std::container types can be used. -// Iterator ranges are supported too. -// Format flags: -// {:X} - print in uppercase. -// {:s} - don't separate each byte with space. -// {:p} - don't print the position on each line start. -// {:n} - don't split the output to lines. - -#include "spdlog/fmt/bin_to_hex.h" -void binary_example() -{ - std::vector buf; - for (int i = 0; i < 80; i++) - { - buf.push_back(static_cast(i & 0xff)); - } - spdlog::info("Binary example: {}", spdlog::to_hex(buf)); - spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10)); - // more examples: - // logger->info("uppercase: {:X}", spdlog::to_hex(buf)); - // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf)); - // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf)); -} - -// Compile time log levels. -// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE) -void trace_example() -{ - // trace from default logger - SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23); - // debug from default logger - SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23); - - // trace from logger object - auto logger = spdlog::get("file_logger"); - SPDLOG_LOGGER_TRACE(logger, "another trace message"); -} - -// A logger with multiple sinks (stdout and file) - each with a different format and log level. -void multi_sink_example() -{ - auto console_sink = std::make_shared(); - console_sink->set_level(spdlog::level::warn); - console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v"); - - auto file_sink = std::make_shared("logs/multisink.txt", true); - file_sink->set_level(spdlog::level::trace); - - spdlog::logger logger("multi_sink", {console_sink, file_sink}); - logger.set_level(spdlog::level::debug); - logger.warn("this should appear in both console and file"); - logger.info("this message should not appear in the console, only in the file"); -} - -// User defined types logging by implementing operator<< -#include "spdlog/fmt/ostr.h" // must be included -struct my_type -{ - int i; - template - friend OStream &operator<<(OStream &os, const my_type &c) - { - return os << "[my_type i=" << c.i << "]"; - } -}; - -void user_defined_example() -{ - spdlog::info("user defined type: {}", my_type{14}); -} - -// Custom error handler. Will be triggered on log failure. -void err_handler_example() -{ - // can be set globally or per logger(logger->set_error_handler(..)) - spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); }); -} - -// syslog example (linux/osx/freebsd) -#ifndef _WIN32 -#include "spdlog/sinks/syslog_sink.h" -void syslog_example() -{ - std::string ident = "spdlog-example"; - auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID); - syslog_logger->warn("This is warning that will end up in syslog."); -} -#endif - -// Android example. -#if defined(__ANDROID__) -#include "spdlog/sinks/android_sink.h" -void android_example() -{ - std::string tag = "spdlog-android"; - auto android_logger = spdlog::android_logger_mt("android", tag); - android_logger->critical("Use \"adb shell logcat\" to view this message."); -} - -#endif +int main(int, char *[]) { + int i = 123; + spdlog::info("HELLO STATIC! {}", i); +} \ No newline at end of file diff --git a/include/spdlog/impl/async_logger.cpp b/include/spdlog/async_logger-inl.h similarity index 97% rename from include/spdlog/impl/async_logger.cpp rename to include/spdlog/async_logger-inl.h index eeae49f9..57ecfd73 100644 --- a/include/spdlog/impl/async_logger.cpp +++ b/include/spdlog/async_logger-inl.h @@ -1,7 +1,3 @@ -#ifdef SPDLOG_STATIC_LIB -#include "spdlog/async_logger.h" -#endif - // async logger implementation // uses a thread pool to perform the actual logging diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index 0178b39d..6056ee07 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -66,5 +66,5 @@ private: } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "spdlog/impl/async_logger.cpp" +#include "async_logger-inl.h" #endif diff --git a/include/spdlog/impl/file_helper.cpp b/include/spdlog/details/file_helper-inl.h similarity index 97% rename from include/spdlog/impl/file_helper.cpp rename to include/spdlog/details/file_helper-inl.h index eb8b9193..d40763ec 100644 --- a/include/spdlog/impl/file_helper.cpp +++ b/include/spdlog/details/file_helper-inl.h @@ -3,10 +3,6 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#ifdef SPDLOG_STATIC_LIB -#include "spdlog/details/file_helper.h" - -#endif #include "spdlog/details/os.h" #include diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index 6f9d7020..6530b18b 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -58,5 +58,5 @@ private: } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "spdlog/impl/file_helper.cpp" +#include "file_helper-inl.h" #endif diff --git a/include/spdlog/impl/log_msg.cpp b/include/spdlog/details/log_msg-inl.h similarity index 90% rename from include/spdlog/impl/log_msg.cpp rename to include/spdlog/details/log_msg-inl.h index e854a1ba..653b596e 100644 --- a/include/spdlog/impl/log_msg.cpp +++ b/include/spdlog/details/log_msg-inl.h @@ -1,10 +1,6 @@ #include "spdlog/details/os.h" #include "spdlog/sinks/sink.h" -#ifdef SPDLOG_STATIC_LIB -#include "spdlog/details/log_msg.h" -#endif - SPDLOG_INLINE spdlog::details::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) diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index fea55a40..8774dea6 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -34,5 +34,5 @@ struct log_msg } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "spdlog/impl/log_msg.cpp" +#include "log_msg-inl.h" #endif diff --git a/include/spdlog/impl/os.cpp b/include/spdlog/details/os-inl.h similarity index 99% rename from include/spdlog/impl/os.cpp rename to include/spdlog/details/os-inl.h index ed174cf1..0b33a17e 100644 --- a/include/spdlog/impl/os.cpp +++ b/include/spdlog/details/os-inl.h @@ -2,9 +2,6 @@ // Copyright(c) 2015 Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#ifdef SPDLOG_STATIC_LIB -#include "spdlog/details/os.h" -#endif #include #include diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 8858ae68..2d04640a 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -90,5 +90,5 @@ void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "spdlog/impl/os.cpp" +#include "os-inl.h" #endif diff --git a/include/spdlog/impl/pattern_formatter.cpp b/include/spdlog/details/pattern_formatter-inl.h similarity index 99% rename from include/spdlog/impl/pattern_formatter.cpp rename to include/spdlog/details/pattern_formatter-inl.h index abcc7b36..662c6bc3 100644 --- a/include/spdlog/impl/pattern_formatter.cpp +++ b/include/spdlog/details/pattern_formatter-inl.h @@ -3,10 +3,6 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#ifdef SPDLOG_STATIC_LIB -#include "spdlog/details/pattern_formatter.h" -#endif - #include "spdlog/details/fmt_helper.h" #include "spdlog/details/log_msg.h" #include "spdlog/details/os.h" diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 8866b8bd..f25e6b72 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -98,5 +98,5 @@ private: } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "spdlog/impl/pattern_formatter.cpp" +#include "pattern_formatter-inl.h" #endif diff --git a/include/spdlog/impl/periodic_worker.cpp b/include/spdlog/details/periodic_worker-inl.h similarity index 92% rename from include/spdlog/impl/periodic_worker.cpp rename to include/spdlog/details/periodic_worker-inl.h index 33f82ae9..9e9a81d7 100644 --- a/include/spdlog/impl/periodic_worker.cpp +++ b/include/spdlog/details/periodic_worker-inl.h @@ -2,10 +2,6 @@ // Created by gabi on 5/8/19. // -#ifdef SPDLOG_STATIC_LIB -#include "spdlog/details/periodic_worker.h" -#endif - #include "spdlog/common.h" SPDLOG_INLINE spdlog::details::periodic_worker::periodic_worker(const std::function &callback_fun, std::chrono::seconds interval) diff --git a/include/spdlog/details/periodic_worker.h b/include/spdlog/details/periodic_worker.h index 03e611aa..a28a237f 100644 --- a/include/spdlog/details/periodic_worker.h +++ b/include/spdlog/details/periodic_worker.h @@ -39,5 +39,5 @@ private: } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "spdlog/impl/periodic_worker.cpp" +#include "periodic_worker-inl.h" #endif diff --git a/include/spdlog/impl/registry.cpp b/include/spdlog/details/registry-inl.h similarity index 99% rename from include/spdlog/impl/registry.cpp rename to include/spdlog/details/registry-inl.h index 9a80aeea..4727414e 100644 --- a/include/spdlog/impl/registry.cpp +++ b/include/spdlog/details/registry-inl.h @@ -2,9 +2,6 @@ // Copyright(c) 2015 Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#ifdef SPDLOG_STATIC_LIB -#include "spdlog/details/registry.h" -#endif #include "spdlog/common.h" #include "spdlog/details/periodic_worker.h" diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index d6f4dbea..47464726 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -102,5 +102,5 @@ private: } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "spdlog/impl/registry.cpp" +#include "registry-inl.h" #endif diff --git a/include/spdlog/impl/thread_pool.cpp b/include/spdlog/details/thread_pool-inl.h similarity index 93% rename from include/spdlog/impl/thread_pool.cpp rename to include/spdlog/details/thread_pool-inl.h index fa8f961d..30c849de 100644 --- a/include/spdlog/impl/thread_pool.cpp +++ b/include/spdlog/details/thread_pool-inl.h @@ -1,10 +1,3 @@ -#ifdef SPDLOG_STATIC_LIB -#include "spdlog/async_logger.h" -#include "spdlog/details/thread_pool.h" - -template class spdlog::details::mpmc_blocking_queue; - -#endif #include "spdlog/common.h" diff --git a/include/spdlog/details/thread_pool.h b/include/spdlog/details/thread_pool.h index a872c303..21bef56f 100644 --- a/include/spdlog/details/thread_pool.h +++ b/include/spdlog/details/thread_pool.h @@ -152,5 +152,5 @@ private: } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "spdlog/impl/thread_pool.cpp" +#include "thread_pool-inl.h" #endif \ No newline at end of file diff --git a/include/spdlog/impl/logger.cpp b/include/spdlog/logger-inl.h similarity index 98% rename from include/spdlog/impl/logger.cpp rename to include/spdlog/logger-inl.h index 01316b64..5e817d4b 100644 --- a/include/spdlog/impl/logger.cpp +++ b/include/spdlog/logger-inl.h @@ -1,7 +1,3 @@ -#ifdef SPDLOG_STATIC_LIB -#include "spdlog/logger.h" -#endif - #include "spdlog/sinks/sink.h" #include "spdlog/details/pattern_formatter.h" diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 804abf33..17a70150 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -341,5 +341,5 @@ protected: } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "spdlog/impl/logger.cpp" +#include "logger-inl.h #endif diff --git a/include/spdlog/impl/ansicolor_sink.cpp b/include/spdlog/sinks/ansicolor_sink-inl.h similarity index 84% rename from include/spdlog/impl/ansicolor_sink.cpp rename to include/spdlog/sinks/ansicolor_sink-inl.h index 97bbfd8e..fa40570d 100644 --- a/include/spdlog/impl/ansicolor_sink.cpp +++ b/include/spdlog/sinks/ansicolor_sink-inl.h @@ -1,7 +1,3 @@ -#ifdef SPDLOG_STATIC_LIB -#include "spdlog/sinks/ansicolor_sink.h" -#endif - #include "spdlog/details/os.h" template @@ -95,11 +91,3 @@ SPDLOG_INLINE void spdlog::sinks::ansicolor_sink::pr { fwrite(formatted.data() + start, sizeof(char), end - start, target_file_); } - -// template instantiate stdout_mt, stdout_st -template class spdlog::sinks::ansicolor_sink; -template class spdlog::sinks::ansicolor_sink; - -// template instantiate stderr_mt, stderr_st -template class spdlog::sinks::ansicolor_sink; -template class spdlog::sinks::ansicolor_sink; diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index 44d5a287..3adce3eb 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -92,5 +92,5 @@ using ansicolor_stderr_sink_st = ansicolor_sink -template class spdlog::sinks::base_sink; -template class spdlog::sinks::base_sink; -#endif - #include "spdlog/common.h" #include "spdlog/details/pattern_formatter.h" diff --git a/include/spdlog/sinks/base_sink.h b/include/spdlog/sinks/base_sink.h index 000a6e20..e3a3924a 100644 --- a/include/spdlog/sinks/base_sink.h +++ b/include/spdlog/sinks/base_sink.h @@ -40,5 +40,5 @@ protected: } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "spdlog/impl/base_sink.cpp" +#include "base_sink-inl.h" #endif \ No newline at end of file diff --git a/include/spdlog/impl/sink.cpp b/include/spdlog/sinks/sink-inl.h similarity index 92% rename from include/spdlog/impl/sink.cpp rename to include/spdlog/sinks/sink-inl.h index 938fc73c..559018b6 100644 --- a/include/spdlog/impl/sink.cpp +++ b/include/spdlog/sinks/sink-inl.h @@ -1,10 +1,6 @@ #include "spdlog/common.h" #include "spdlog/details/pattern_formatter.h" -#ifdef SPDLOG_STATIC_LIB -#include "spdlog/sinks/sink.h" -#endif - SPDLOG_INLINE spdlog::sinks::sink::sink() : formatter_{details::make_unique()} { diff --git a/include/spdlog/sinks/sink.h b/include/spdlog/sinks/sink.h index 1fc1f1d7..01273d18 100644 --- a/include/spdlog/sinks/sink.h +++ b/include/spdlog/sinks/sink.h @@ -42,5 +42,5 @@ protected: } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "spdlog/impl/sink.cpp" +#include "sink-inl.h" #endif diff --git a/include/spdlog/impl/fmt-format.cpp b/src/format.cc similarity index 100% rename from include/spdlog/impl/fmt-format.cpp rename to src/format.cc From f809427575aa0acb63853904a6679f693d17300c Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 11 May 2019 13:20:11 +0300 Subject: [PATCH 099/157] Moved cpp files to inl.h --- src/spdlog.cpp | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/spdlog.cpp diff --git a/src/spdlog.cpp b/src/spdlog.cpp new file mode 100644 index 00000000..a09dd9a1 --- /dev/null +++ b/src/spdlog.cpp @@ -0,0 +1,49 @@ +#include +#include "spdlog/details/null_mutex.h" + +#include "spdlog/logger.h" +#include "spdlog/logger-inl.h" + +#include "spdlog/async_logger.h" +#include "spdlog/async_logger-inl.h" + +#include "spdlog/async_logger.h" +#include "spdlog/async_logger-inl.h" + +#include "spdlog/details/log_msg.h" +#include "spdlog/details/log_msg-inl.h" + +#include "spdlog/sinks/sink.h" +#include "spdlog/sinks/sink-inl.h" + +#include "spdlog/sinks/base_sink.h" +#include "spdlog/sinks/base_sink-inl.h" +template class spdlog::sinks::base_sink; +template class spdlog::sinks::base_sink; + +#include "spdlog/details/registry.h" +#include "spdlog/details/registry-inl.h" + +#include "spdlog/details/os.h" +#include "spdlog/details/os-inl.h" + +#include "spdlog/details/periodic_worker.h" +#include "spdlog/details/periodic_worker-inl.h" + +#include "spdlog/details/file_helper.h" +#include "spdlog/details/file_helper-inl.h" + +#include "spdlog/details/pattern_formatter.h" +#include "spdlog/details/pattern_formatter-inl.h" + +#include "spdlog/details/thread_pool.h" +#include "spdlog/details/thread_pool-inl.h" +template class spdlog::details::mpmc_blocking_queue; + +#include "spdlog/sinks/ansicolor_sink.h" +#include "spdlog/sinks/ansicolor_sink-inl.h" +// template instantiate stdout_mt, stdout_st, stderr_mt, stderr_st +template class spdlog::sinks::ansicolor_sink; +template class spdlog::sinks::ansicolor_sink; +template class spdlog::sinks::ansicolor_sink; +template class spdlog::sinks::ansicolor_sink; From 005450ff13b268ab5e78a15dfd5d0b342327e91a Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 11 May 2019 13:52:46 +0300 Subject: [PATCH 100/157] wip --- CMakeLists.txt | 3 ++- include/spdlog/async_logger.h | 7 ++----- include/spdlog/logger.h | 2 +- src/spdlog.cpp | 7 ++----- 4 files changed, 7 insertions(+), 12 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6ebb465e..775e236f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -59,7 +59,8 @@ message(STATUS "Static lib: " ${SPDLOG_STATIC_LIB}) if(SPDLOG_STATIC_LIB) add_definitions(-DSPDLOG_STATIC_LIB) - file(GLOB SRC_FILES ${HEADER_BASE}/impl/*.cpp) + set(SRC_BASE "${CMAKE_CURRENT_SOURCE_DIR}/src") + set(SRC_FILES "${SRC_BASE}/spdlog.cpp" "${SRC_BASE}/format.cc") add_library(spdlog STATIC ${SRC_FILES}) target_include_directories(spdlog PUBLIC "$") target_link_libraries(spdlog -Wl,--as-needed) diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index 6056ee07..71c628e5 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -5,17 +5,14 @@ #pragma once -// Very fast asynchronous logger (millions of logs per second on an average -// desktop) -// Uses pre allocated lockfree queue for maximum throughput even under large -// number of threads. +// Fast asynchronous logger. +// Uses pre allocated queue. // Creates a single back thread to pop messages from the queue and log them. // // Upon each log write the logger: // 1. Checks if its log level is enough to log the message // 2. Push a new copy of the message to a queue (or block the caller until // space is available in the queue) -// 3. will throw spdlog_ex upon log exceptions // Upon destruction, logs all remaining messages in the queue before // destructing.. diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 17a70150..0c152e2d 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -341,5 +341,5 @@ protected: } // namespace spdlog #ifndef SPDLOG_STATIC_LIB -#include "logger-inl.h +#include "logger-inl.h" #endif diff --git a/src/spdlog.cpp b/src/spdlog.cpp index a09dd9a1..6b1cb5f4 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -1,4 +1,5 @@ -#include +#include "spdlog/spdlog.h" + #include "spdlog/details/null_mutex.h" #include "spdlog/logger.h" @@ -7,9 +8,6 @@ #include "spdlog/async_logger.h" #include "spdlog/async_logger-inl.h" -#include "spdlog/async_logger.h" -#include "spdlog/async_logger-inl.h" - #include "spdlog/details/log_msg.h" #include "spdlog/details/log_msg-inl.h" @@ -42,7 +40,6 @@ template class spdlog::details::mpmc_blocking_queue; #include "spdlog/sinks/ansicolor_sink.h" #include "spdlog/sinks/ansicolor_sink-inl.h" -// template instantiate stdout_mt, stdout_st, stderr_mt, stderr_st template class spdlog::sinks::ansicolor_sink; template class spdlog::sinks::ansicolor_sink; template class spdlog::sinks::ansicolor_sink; From 46ef71e3ecad2681eaddbc80be6f56e177827028 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 11 May 2019 20:06:17 +0300 Subject: [PATCH 101/157] Normalized copyright message --- example/example.cpp | 4 ++-- include/spdlog/async.h | 5 +---- include/spdlog/async_logger-inl.h | 6 ++++-- include/spdlog/async_logger.h | 4 +--- include/spdlog/common-inl.h | 4 ++++ include/spdlog/common.h | 4 +--- include/spdlog/details/circular_q.h | 4 +--- include/spdlog/details/console_globals.h | 8 ++++---- include/spdlog/details/file_helper-inl.h | 6 +++--- include/spdlog/details/file_helper.h | 4 +--- include/spdlog/details/fmt_helper.h | 6 ++---- include/spdlog/details/log_msg-inl.h | 5 +++++ include/spdlog/details/log_msg.h | 4 +--- include/spdlog/details/mpmc_blocking_q.h | 8 +++----- include/spdlog/details/null_mutex.h | 4 +--- include/spdlog/details/os-inl.h | 5 ++--- include/spdlog/details/os.h | 5 ++--- include/spdlog/details/pattern_formatter-inl.h | 6 +++--- include/spdlog/details/pattern_formatter.h | 5 ++--- include/spdlog/details/periodic_worker-inl.h | 7 +++---- include/spdlog/details/periodic_worker.h | 5 +---- include/spdlog/details/registry-inl.h | 6 +++--- include/spdlog/details/registry.h | 4 +--- include/spdlog/details/thread_pool-inl.h | 4 ++++ include/spdlog/details/thread_pool.h | 3 +++ include/spdlog/formatter.h | 4 +--- include/spdlog/logger-inl.h | 5 +++++ include/spdlog/logger.h | 4 +--- include/spdlog/sinks/android_sink.h | 4 +--- include/spdlog/sinks/ansicolor_sink-inl.h | 5 +++++ include/spdlog/sinks/ansicolor_sink.h | 4 +--- include/spdlog/sinks/base_sink-inl.h | 5 +++++ include/spdlog/sinks/base_sink.h | 4 +--- include/spdlog/sinks/basic_file_sink.h | 4 +--- include/spdlog/sinks/daily_file_sink.h | 4 +--- include/spdlog/sinks/dist_sink.h | 4 +--- include/spdlog/sinks/msvc_sink.h | 2 -- include/spdlog/sinks/null_sink.h | 4 +--- include/spdlog/sinks/ostream_sink.h | 4 +--- include/spdlog/sinks/rotating_file_sink.h | 4 +--- include/spdlog/sinks/sink-inl.h | 5 +++++ include/spdlog/sinks/sink.h | 5 +---- include/spdlog/sinks/stdout_color_sinks.h | 4 +--- include/spdlog/sinks/stdout_sinks.h | 4 +--- include/spdlog/sinks/syslog_sink.h | 4 +--- include/spdlog/sinks/systemd_sink.h | 2 -- include/spdlog/sinks/wincolor_sink.h | 4 +--- include/spdlog/spdlog.h | 6 +++--- include/spdlog/tweakme.h | 4 +--- include/spdlog/version.h | 4 +--- src/format.cc | 6 ++++-- src/spdlog.cpp | 3 +++ 52 files changed, 106 insertions(+), 132 deletions(-) create mode 100644 include/spdlog/common-inl.h diff --git a/example/example.cpp b/example/example.cpp index dc3ebc75..519e1a7e 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -7,10 +7,10 @@ // // - #include "spdlog/spdlog.h" -int main(int, char *[]) { +int main(int, char *[]) +{ int i = 123; spdlog::info("HELLO STATIC! {}", i); } \ No newline at end of file diff --git a/include/spdlog/async.h b/include/spdlog/async.h index 971becd7..a13cbdc7 100644 --- a/include/spdlog/async.h +++ b/include/spdlog/async.h @@ -1,8 +1,5 @@ - -// -// Copyright(c) 2018 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/async_logger-inl.h b/include/spdlog/async_logger-inl.h index 57ecfd73..84b5cd71 100644 --- a/include/spdlog/async_logger-inl.h +++ b/include/spdlog/async_logger-inl.h @@ -1,5 +1,7 @@ -// async logger implementation -// uses a thread pool to perform the actual logging +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once #include "spdlog/sinks/sink.h" #include "spdlog/details/thread_pool.h" diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index 71c628e5..907cf720 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/common-inl.h b/include/spdlog/common-inl.h new file mode 100644 index 00000000..3a6f2edd --- /dev/null +++ b/include/spdlog/common-inl.h @@ -0,0 +1,4 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once \ No newline at end of file diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 7af05411..0dd010a5 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/details/circular_q.h b/include/spdlog/details/circular_q.h index b01325bb..4bf5ca13 100644 --- a/include/spdlog/details/circular_q.h +++ b/include/spdlog/details/circular_q.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2018 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// // cirucal q view of std::vector. #pragma once diff --git a/include/spdlog/details/console_globals.h b/include/spdlog/details/console_globals.h index e2afb6bf..443f8657 100644 --- a/include/spdlog/details/console_globals.h +++ b/include/spdlog/details/console_globals.h @@ -1,8 +1,8 @@ -#pragma once -// -// Copyright(c) 2018 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// + +#pragma once + #include "spdlog/details/null_mutex.h" #include diff --git a/include/spdlog/details/file_helper-inl.h b/include/spdlog/details/file_helper-inl.h index d40763ec..3e709654 100644 --- a/include/spdlog/details/file_helper-inl.h +++ b/include/spdlog/details/file_helper-inl.h @@ -1,7 +1,7 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// + +#pragma once #include "spdlog/details/os.h" diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index 6530b18b..87a0076a 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index 16035555..da253720 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -1,7 +1,5 @@ -// -// Created by gabi on 6/15/18. -// - +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once #include diff --git a/include/spdlog/details/log_msg-inl.h b/include/spdlog/details/log_msg-inl.h index 653b596e..d8ca61a4 100644 --- a/include/spdlog/details/log_msg-inl.h +++ b/include/spdlog/details/log_msg-inl.h @@ -1,3 +1,8 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + #include "spdlog/details/os.h" #include "spdlog/sinks/sink.h" diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 8774dea6..9d3cbab4 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/details/mpmc_blocking_q.h b/include/spdlog/details/mpmc_blocking_q.h index ca789fc6..3a383bfe 100644 --- a/include/spdlog/details/mpmc_blocking_q.h +++ b/include/spdlog/details/mpmc_blocking_q.h @@ -1,9 +1,7 @@ -#pragma once - -// -// Copyright(c) 2018 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// + +#pragma once // multi producer-multi consumer blocking queue. // enqueue(..) - will block until room found to put the new message. diff --git a/include/spdlog/details/null_mutex.h b/include/spdlog/details/null_mutex.h index 3f495bd9..2dc1f98b 100644 --- a/include/spdlog/details/null_mutex.h +++ b/include/spdlog/details/null_mutex.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/details/os-inl.h b/include/spdlog/details/os-inl.h index 0b33a17e..cc4690d6 100644 --- a/include/spdlog/details/os-inl.h +++ b/include/spdlog/details/os-inl.h @@ -1,8 +1,7 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// +#pragma once #include #include #include diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 2d04640a..dc4ce16b 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -1,7 +1,6 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// + #pragma once #include "spdlog/common.h" diff --git a/include/spdlog/details/pattern_formatter-inl.h b/include/spdlog/details/pattern_formatter-inl.h index 662c6bc3..efb5f1e6 100644 --- a/include/spdlog/details/pattern_formatter-inl.h +++ b/include/spdlog/details/pattern_formatter-inl.h @@ -1,7 +1,7 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// + +#pragma once #include "spdlog/details/fmt_helper.h" #include "spdlog/details/log_msg.h" diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index f25e6b72..4b36ed06 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -1,9 +1,8 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once + #include "spdlog/common.h" #include "spdlog/details/log_msg.h" #include "spdlog/details/os.h" diff --git a/include/spdlog/details/periodic_worker-inl.h b/include/spdlog/details/periodic_worker-inl.h index 9e9a81d7..dc363913 100644 --- a/include/spdlog/details/periodic_worker-inl.h +++ b/include/spdlog/details/periodic_worker-inl.h @@ -1,8 +1,7 @@ -// -// Created by gabi on 5/8/19. -// +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) -#include "spdlog/common.h" +#pragma once SPDLOG_INLINE spdlog::details::periodic_worker::periodic_worker(const std::function &callback_fun, std::chrono::seconds interval) { diff --git a/include/spdlog/details/periodic_worker.h b/include/spdlog/details/periodic_worker.h index a28a237f..da8ca8bb 100644 --- a/include/spdlog/details/periodic_worker.h +++ b/include/spdlog/details/periodic_worker.h @@ -1,8 +1,5 @@ - -// -// Copyright(c) 2018 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/details/registry-inl.h b/include/spdlog/details/registry-inl.h index 4727414e..168c4c54 100644 --- a/include/spdlog/details/registry-inl.h +++ b/include/spdlog/details/registry-inl.h @@ -1,7 +1,7 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// + +#pragma once #include "spdlog/common.h" #include "spdlog/details/periodic_worker.h" diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 47464726..267d30a2 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/details/thread_pool-inl.h b/include/spdlog/details/thread_pool-inl.h index 30c849de..d9618215 100644 --- a/include/spdlog/details/thread_pool-inl.h +++ b/include/spdlog/details/thread_pool-inl.h @@ -1,3 +1,7 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once #include "spdlog/common.h" diff --git a/include/spdlog/details/thread_pool.h b/include/spdlog/details/thread_pool.h index 21bef56f..cc14bb39 100644 --- a/include/spdlog/details/thread_pool.h +++ b/include/spdlog/details/thread_pool.h @@ -1,3 +1,6 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + #pragma once #include "spdlog/details/fmt_helper.h" diff --git a/include/spdlog/formatter.h b/include/spdlog/formatter.h index a7ef6b8b..16d86969 100644 --- a/include/spdlog/formatter.h +++ b/include/spdlog/formatter.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/logger-inl.h b/include/spdlog/logger-inl.h index 5e817d4b..c0d13f11 100644 --- a/include/spdlog/logger-inl.h +++ b/include/spdlog/logger-inl.h @@ -1,3 +1,8 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + #include "spdlog/sinks/sink.h" #include "spdlog/details/pattern_formatter.h" diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 0c152e2d..21814121 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015-2108 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/android_sink.h b/include/spdlog/sinks/android_sink.h index ae7f7733..70073ae4 100644 --- a/include/spdlog/sinks/android_sink.h +++ b/include/spdlog/sinks/android_sink.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/ansicolor_sink-inl.h b/include/spdlog/sinks/ansicolor_sink-inl.h index fa40570d..63da482e 100644 --- a/include/spdlog/sinks/ansicolor_sink-inl.h +++ b/include/spdlog/sinks/ansicolor_sink-inl.h @@ -1,3 +1,8 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + #include "spdlog/details/os.h" template diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index 3adce3eb..1eb8c931 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2017 spdlog authors. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/base_sink-inl.h b/include/spdlog/sinks/base_sink-inl.h index 607cf390..177bbb69 100644 --- a/include/spdlog/sinks/base_sink-inl.h +++ b/include/spdlog/sinks/base_sink-inl.h @@ -1,3 +1,8 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + #include "spdlog/common.h" #include "spdlog/details/pattern_formatter.h" diff --git a/include/spdlog/sinks/base_sink.h b/include/spdlog/sinks/base_sink.h index e3a3924a..2ecf11b1 100644 --- a/include/spdlog/sinks/base_sink.h +++ b/include/spdlog/sinks/base_sink.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once // diff --git a/include/spdlog/sinks/basic_file_sink.h b/include/spdlog/sinks/basic_file_sink.h index facc7209..249a6f31 100644 --- a/include/spdlog/sinks/basic_file_sink.h +++ b/include/spdlog/sinks/basic_file_sink.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015-2018 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/daily_file_sink.h b/include/spdlog/sinks/daily_file_sink.h index 08392c16..a240294c 100644 --- a/include/spdlog/sinks/daily_file_sink.h +++ b/include/spdlog/sinks/daily_file_sink.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/dist_sink.h b/include/spdlog/sinks/dist_sink.h index 44de3913..90da7dd2 100644 --- a/include/spdlog/sinks/dist_sink.h +++ b/include/spdlog/sinks/dist_sink.h @@ -1,7 +1,5 @@ -// -// Copyright (c) 2015 David Schury, Gabi Melman +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/msvc_sink.h b/include/spdlog/sinks/msvc_sink.h index f06c16c7..6866dd7a 100644 --- a/include/spdlog/sinks/msvc_sink.h +++ b/include/spdlog/sinks/msvc_sink.h @@ -1,7 +1,5 @@ -// // Copyright(c) 2016 Alexander Dalshov. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/null_sink.h b/include/spdlog/sinks/null_sink.h index 54f322c4..ab681575 100644 --- a/include/spdlog/sinks/null_sink.h +++ b/include/spdlog/sinks/null_sink.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/ostream_sink.h b/include/spdlog/sinks/ostream_sink.h index 22e377b6..f060ecde 100644 --- a/include/spdlog/sinks/ostream_sink.h +++ b/include/spdlog/sinks/ostream_sink.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/rotating_file_sink.h b/include/spdlog/sinks/rotating_file_sink.h index 35f33a4d..ab658532 100644 --- a/include/spdlog/sinks/rotating_file_sink.h +++ b/include/spdlog/sinks/rotating_file_sink.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/sink-inl.h b/include/spdlog/sinks/sink-inl.h index 559018b6..1ec317a3 100644 --- a/include/spdlog/sinks/sink-inl.h +++ b/include/spdlog/sinks/sink-inl.h @@ -1,3 +1,8 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + #include "spdlog/common.h" #include "spdlog/details/pattern_formatter.h" diff --git a/include/spdlog/sinks/sink.h b/include/spdlog/sinks/sink.h index 01273d18..2c5ef9bd 100644 --- a/include/spdlog/sinks/sink.h +++ b/include/spdlog/sinks/sink.h @@ -1,12 +1,9 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once #include "spdlog/details/log_msg.h" -//#include "spdlog/details/pattern_formatter.h" #include "spdlog/formatter.h" namespace spdlog { diff --git a/include/spdlog/sinks/stdout_color_sinks.h b/include/spdlog/sinks/stdout_color_sinks.h index 5accda44..bc8fcbab 100644 --- a/include/spdlog/sinks/stdout_color_sinks.h +++ b/include/spdlog/sinks/stdout_color_sinks.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2018 spdlog +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/stdout_sinks.h b/include/spdlog/sinks/stdout_sinks.h index bf8e9790..6b7fd3ec 100644 --- a/include/spdlog/sinks/stdout_sinks.h +++ b/include/spdlog/sinks/stdout_sinks.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/syslog_sink.h b/include/spdlog/sinks/syslog_sink.h index c3bcd844..53226d6a 100644 --- a/include/spdlog/sinks/syslog_sink.h +++ b/include/spdlog/sinks/syslog_sink.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/systemd_sink.h b/include/spdlog/sinks/systemd_sink.h index be143194..dfdc8b72 100644 --- a/include/spdlog/sinks/systemd_sink.h +++ b/include/spdlog/sinks/systemd_sink.h @@ -1,7 +1,5 @@ -// // Copyright(c) 2019 ZVYAGIN.Alexander@gmail.com // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index 1fdf8c56..70ee4a60 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2016 spdlog +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index aaa93886..db67dba6 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -1,12 +1,12 @@ -// -// Copyright(c) 2015-2018 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// + // spdlog main header file. // see example.cpp for usage example #ifndef SPDLOG_H #define SPDLOG_H + #pragma once #include "spdlog/common.h" diff --git a/include/spdlog/tweakme.h b/include/spdlog/tweakme.h index beae4f74..37c2e6cf 100644 --- a/include/spdlog/tweakme.h +++ b/include/spdlog/tweakme.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/include/spdlog/version.h b/include/spdlog/version.h index 87a68bd1..0bbf338d 100644 --- a/include/spdlog/version.h +++ b/include/spdlog/version.h @@ -1,7 +1,5 @@ -// -// Copyright(c) 2015 Gabi Melman. +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// #pragma once diff --git a/src/format.cc b/src/format.cc index 70ccb8a3..f2a014da 100644 --- a/src/format.cc +++ b/src/format.cc @@ -1,10 +1,12 @@ -// Formatting library for C++ -// // Copyright (c) 2012 - 2016, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. + +// Slightly modified version of fmt lib to include bundled format-inl.h + + #if !defined(SPDLOG_FMT_EXTERNAL) #include "spdlog/fmt/bundled/format-inl.h" #else diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 6b1cb5f4..c41ca6e9 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -1,3 +1,6 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + #include "spdlog/spdlog.h" #include "spdlog/details/null_mutex.h" From 540f8653555ac63b3f1d35e178acfb92514d9179 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 11 May 2019 20:15:03 +0300 Subject: [PATCH 102/157] Normalized copyright message --- include/spdlog/common-inl.h | 21 ++++++++++++++++++++- include/spdlog/common.h | 23 +++++++---------------- src/spdlog.cpp | 6 +++++- 3 files changed, 32 insertions(+), 18 deletions(-) diff --git a/include/spdlog/common-inl.h b/include/spdlog/common-inl.h index 3a6f2edd..40e746f2 100644 --- a/include/spdlog/common-inl.h +++ b/include/spdlog/common-inl.h @@ -1,4 +1,23 @@ // Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -#pragma once \ No newline at end of file +#pragma once + + +SPDLOG_INLINE spdlog::spdlog_ex::spdlog_ex(std::string msg) +: msg_(std::move(msg)) +{ +} + +SPDLOG_INLINE spdlog::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::spdlog_ex::what() const SPDLOG_NOEXCEPT +{ + return msg_.c_str(); +} + diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 0dd010a5..64eff8d1 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -191,22 +191,9 @@ enum class pattern_time_type class spdlog_ex : public std::exception { public: - explicit spdlog_ex(std::string msg) - : msg_(std::move(msg)) - { - } - - 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(); - } + explicit spdlog_ex(std::string msg); + spdlog_ex(const std::string &msg, int last_errno); + const char *what() const SPDLOG_NOEXCEPT override; private: std::string msg_; @@ -246,3 +233,7 @@ std::unique_ptr make_unique(Args &&... args) #endif } // namespace details } // namespace spdlog + +#ifndef SPDLOG_STATIC_LIB +#include "commont-inl.h" +#endif \ No newline at end of file diff --git a/src/spdlog.cpp b/src/spdlog.cpp index c41ca6e9..465812c5 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -1,7 +1,11 @@ // Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -#include "spdlog/spdlog.h" +#include + +#include "spdlog/common.h" +#include "spdlog/common-inl.h" + #include "spdlog/details/null_mutex.h" From 6bcb422c80517d577f6693d752d93e662c792230 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 00:22:39 +0300 Subject: [PATCH 103/157] clang format and SPLDOG_HEADER_ONLY macro --- .clang-format | 6 +- CMakeLists.txt | 2 +- example/example.cpp | 13 ++-- include/spdlog/async_logger-inl.h | 9 +-- include/spdlog/async_logger.h | 2 +- include/spdlog/common-inl.h | 40 ++++++++++-- include/spdlog/common.h | 38 +++-------- include/spdlog/details/circular_q.h | 3 +- include/spdlog/details/console_globals.h | 1 - include/spdlog/details/file_helper-inl.h | 1 + include/spdlog/details/file_helper.h | 2 +- include/spdlog/details/log_msg-inl.h | 16 +++-- include/spdlog/details/log_msg.h | 3 +- include/spdlog/details/mpmc_blocking_q.h | 3 +- include/spdlog/details/null_mutex.h | 3 +- include/spdlog/details/os.h | 2 +- .../spdlog/details/pattern_formatter-inl.h | 54 +++++---------- include/spdlog/details/pattern_formatter.h | 11 ++-- include/spdlog/details/periodic_worker-inl.h | 10 ++- include/spdlog/details/periodic_worker.h | 2 +- include/spdlog/details/registry.h | 2 +- include/spdlog/details/thread_pool-inl.h | 25 +++---- include/spdlog/details/thread_pool.h | 11 ++-- include/spdlog/fmt/bin_to_hex.h | 3 +- include/spdlog/fmt/fmt.h | 2 +- include/spdlog/logger-inl.h | 56 ++++++++-------- include/spdlog/logger.h | 11 ++-- include/spdlog/sinks/android_sink.h | 3 +- include/spdlog/sinks/ansicolor_sink.h | 2 +- include/spdlog/sinks/ostream_sink.h | 3 +- include/spdlog/sinks/sink-inl.h | 6 +- include/spdlog/sinks/sink.h | 2 +- include/spdlog/sinks/stdout_sinks.h | 3 +- src/format.cc | 65 ------------------- src/format.cpp | 51 +++++++++++++++ src/spdlog.cpp | 7 +- tests/test_errors.cpp | 3 +- 37 files changed, 227 insertions(+), 249 deletions(-) delete mode 100644 src/format.cc create mode 100644 src/format.cpp diff --git a/.clang-format b/.clang-format index aa95f7a5..bd1caad1 100644 --- a/.clang-format +++ b/.clang-format @@ -32,9 +32,9 @@ BraceWrapping: BeforeCatch: true BeforeElse: true IndentBraces: false - SplitEmptyFunction: true - SplitEmptyRecord: true - SplitEmptyNamespace: true + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false BreakBeforeBinaryOperators: None BreakBeforeBraces: Custom BreakBeforeInheritanceComma: false diff --git a/CMakeLists.txt b/CMakeLists.txt index 775e236f..4b2775b0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,7 +60,7 @@ message(STATUS "Static lib: " ${SPDLOG_STATIC_LIB}) if(SPDLOG_STATIC_LIB) add_definitions(-DSPDLOG_STATIC_LIB) set(SRC_BASE "${CMAKE_CURRENT_SOURCE_DIR}/src") - set(SRC_FILES "${SRC_BASE}/spdlog.cpp" "${SRC_BASE}/format.cc") + set(SRC_FILES "${SRC_BASE}/spdlog.cpp" "${SRC_BASE}/format.cpp") add_library(spdlog STATIC ${SRC_FILES}) target_include_directories(spdlog PUBLIC "$") target_link_libraries(spdlog -Wl,--as-needed) diff --git a/example/example.cpp b/example/example.cpp index 519e1a7e..532bbb5c 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -7,10 +7,15 @@ // // -#include "spdlog/spdlog.h" - +//#include "spdlog/spdlog.h" +#include "spdlog/logger.h" +//#include "spdlog/sinks/stdout_color_sinks.h" int main(int, char *[]) { - int i = 123; - spdlog::info("HELLO STATIC! {}", i); + spdlog::logger *l = nullptr; + const int i = 123; + l->info("HELLO STATIC! {}", i); + l->info("HELLO STATIC! {}", "GABI"); + l->info("HELLO STATIC! {} {}", "GABI", i); + l->warn("HELLO STATIC! {} {}", "GABI", i); } \ No newline at end of file diff --git a/include/spdlog/async_logger-inl.h b/include/spdlog/async_logger-inl.h index 84b5cd71..027366c8 100644 --- a/include/spdlog/async_logger-inl.h +++ b/include/spdlog/async_logger-inl.h @@ -16,20 +16,17 @@ SPDLOG_INLINE spdlog::async_logger::async_logger( : logger(std::move(logger_name), begin, end) , thread_pool_(std::move(tp)) , overflow_policy_(overflow_policy) -{ -} +{} SPDLOG_INLINE spdlog::async_logger::async_logger( std::string logger_name, sinks_init_list sinks_list, std::weak_ptr tp, async_overflow_policy overflow_policy) : async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), std::move(tp), overflow_policy) -{ -} +{} SPDLOG_INLINE spdlog::async_logger::async_logger( std::string logger_name, sink_ptr single_sink, std::weak_ptr tp, async_overflow_policy overflow_policy) : async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy) -{ -} +{} // send the log message to the thread pool SPDLOG_INLINE void spdlog::async_logger::sink_it_(details::log_msg &msg) diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index 907cf720..9651da4d 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -60,6 +60,6 @@ private: }; } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB +#ifdef SPDLOG_HEADER_ONLY #include "async_logger-inl.h" #endif diff --git a/include/spdlog/common-inl.h b/include/spdlog/common-inl.h index 40e746f2..dd619a57 100644 --- a/include/spdlog/common-inl.h +++ b/include/spdlog/common-inl.h @@ -1,23 +1,53 @@ // Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -#pragma once +#pragma once +namespace spdlog { +namespace level { +static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES; -SPDLOG_INLINE spdlog::spdlog_ex::spdlog_ex(std::string msg) -: msg_(std::move(msg)) +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 spdlog::spdlog_ex::spdlog_ex(const std::string &msg, int last_errno) +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++; + } + 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::spdlog_ex::what() const SPDLOG_NOEXCEPT +SPDLOG_INLINE const char *spdlog_ex::what() const SPDLOG_NOEXCEPT { return msg_.c_str(); } +} // namespace spdlog diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 64eff8d1..f37f08fe 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -22,8 +22,10 @@ #include "spdlog/fmt/fmt.h" #ifdef SPDLOG_STATIC_LIB +#undef SPDLOG_HEADER_ONLY #define SPDLOG_INLINE #else +#define SPDLOG_HEADER_ONLY #define SPDLOG_INLINE inline #endif @@ -138,39 +140,18 @@ enum level_enum "trace", "debug", "info", "warning", "error", "critical", "off" \ } #endif -static string_view_t level_string_views[] SPDLOG_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 -{ - return level_string_views[l]; -} - -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++; - } - return level::off; -} +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; } // namespace level @@ -206,8 +187,7 @@ struct source_loc : filename{filename_in} , line{line_in} , funcname{funcname_in} - { - } + {} SPDLOG_CONSTEXPR bool empty() const SPDLOG_NOEXCEPT { @@ -234,6 +214,6 @@ std::unique_ptr make_unique(Args &&... args) } // namespace details } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB -#include "commont-inl.h" +#ifdef SPDLOG_HEADER_ONLY +#include "common-inl.h" #endif \ No newline at end of file diff --git a/include/spdlog/details/circular_q.h b/include/spdlog/details/circular_q.h index 4bf5ca13..b6324e06 100644 --- a/include/spdlog/details/circular_q.h +++ b/include/spdlog/details/circular_q.h @@ -17,8 +17,7 @@ public: explicit circular_q(size_t max_items) : max_items_(max_items + 1) // one item is reserved as marker for full q , v_(max_items_) - { - } + {} // push back, overrun (oldest) item if no room left void push_back(T &&item) diff --git a/include/spdlog/details/console_globals.h b/include/spdlog/details/console_globals.h index 443f8657..85ff9023 100644 --- a/include/spdlog/details/console_globals.h +++ b/include/spdlog/details/console_globals.h @@ -3,7 +3,6 @@ #pragma once - #include "spdlog/details/null_mutex.h" #include #include diff --git a/include/spdlog/details/file_helper-inl.h b/include/spdlog/details/file_helper-inl.h index 3e709654..fef3be01 100644 --- a/include/spdlog/details/file_helper-inl.h +++ b/include/spdlog/details/file_helper-inl.h @@ -14,6 +14,7 @@ namespace spdlog { namespace details { + SPDLOG_INLINE file_helper::~file_helper() { close(); diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index 87a0076a..afacc4c6 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -55,6 +55,6 @@ private: } // namespace details } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB +#ifdef SPDLOG_HEADER_ONLY #include "file_helper-inl.h" #endif diff --git a/include/spdlog/details/log_msg-inl.h b/include/spdlog/details/log_msg-inl.h index d8ca61a4..b619f7ce 100644 --- a/include/spdlog/details/log_msg-inl.h +++ b/include/spdlog/details/log_msg-inl.h @@ -6,7 +6,10 @@ #include "spdlog/details/os.h" #include "spdlog/sinks/sink.h" -SPDLOG_INLINE spdlog::details::log_msg::log_msg( +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) @@ -19,10 +22,11 @@ SPDLOG_INLINE spdlog::details::log_msg::log_msg( #endif , source(loc) , payload(view) -{ -} +{} -SPDLOG_INLINE spdlog::details::log_msg::log_msg(const std::string *loggers_name, spdlog::level::level_enum lvl, spdlog::string_view_t 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) -{ -} \ No newline at end of file +{} + +} // namespace details +} // namespace spdlog diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 9d3cbab4..152d27ad 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -11,7 +11,6 @@ namespace details { struct log_msg { 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); log_msg(const log_msg &other) = default; @@ -31,6 +30,6 @@ struct log_msg } // namespace details } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB +#ifdef SPDLOG_HEADER_ONLY #include "log_msg-inl.h" #endif diff --git a/include/spdlog/details/mpmc_blocking_q.h b/include/spdlog/details/mpmc_blocking_q.h index 3a383bfe..4d162d83 100644 --- a/include/spdlog/details/mpmc_blocking_q.h +++ b/include/spdlog/details/mpmc_blocking_q.h @@ -25,8 +25,7 @@ public: using item_type = T; explicit mpmc_blocking_queue(size_t max_items) : q_(max_items) - { - } + {} #ifndef __MINGW32__ // try to enqueue and block if no room left diff --git a/include/spdlog/details/null_mutex.h b/include/spdlog/details/null_mutex.h index 2dc1f98b..aa54f79a 100644 --- a/include/spdlog/details/null_mutex.h +++ b/include/spdlog/details/null_mutex.h @@ -25,8 +25,7 @@ struct null_atomic_int explicit null_atomic_int(int val) : value(val) - { - } + {} int load(std::memory_order) const { diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index dc4ce16b..3197ec69 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -88,6 +88,6 @@ void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target } // namespace details } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB +#ifdef SPDLOG_HEADER_ONLY #include "os-inl.h" #endif diff --git a/include/spdlog/details/pattern_formatter-inl.h b/include/spdlog/details/pattern_formatter-inl.h index efb5f1e6..9275d8ef 100644 --- a/include/spdlog/details/pattern_formatter-inl.h +++ b/include/spdlog/details/pattern_formatter-inl.h @@ -58,8 +58,7 @@ public: scoped_pad(spdlog::string_view_t txt, padding_info &padinfo, fmt::memory_buffer &dest) : scoped_pad(txt.size(), padinfo, dest) - { - } + {} ~scoped_pad() { @@ -90,8 +89,7 @@ class name_formatter : public flag_formatter public: explicit name_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -113,8 +111,7 @@ class level_formatter : public flag_formatter public: explicit level_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -137,8 +134,7 @@ class short_level_formatter : public flag_formatter public: explicit short_level_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -169,8 +165,7 @@ class a_formatter : public flag_formatter public: explicit a_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -187,8 +182,7 @@ class A_formatter : public flag_formatter public: explicit A_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -205,8 +199,7 @@ class b_formatter : public flag_formatter public: explicit b_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -224,8 +217,7 @@ class B_formatter : public flag_formatter public: explicit B_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -241,8 +233,7 @@ class c_formatter final : public flag_formatter public: explicit c_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -273,8 +264,7 @@ class C_formatter final : public flag_formatter public: explicit C_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -290,8 +280,7 @@ class D_formatter final : public flag_formatter public: explicit D_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -327,8 +316,7 @@ class m_formatter final : public flag_formatter public: explicit m_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -344,8 +332,7 @@ class d_formatter final : public flag_formatter public: explicit d_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -361,8 +348,7 @@ class H_formatter final : public flag_formatter public: explicit H_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -707,8 +693,7 @@ class ch_formatter final : public flag_formatter public: explicit ch_formatter(char ch) : ch_(ch) - { - } + {} void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override { @@ -746,8 +731,7 @@ class color_start_formatter final : public flag_formatter public: explicit color_start_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -759,8 +743,7 @@ class color_stop_formatter final : public flag_formatter public: explicit color_stop_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -864,8 +847,7 @@ class full_formatter final : public flag_formatter public: explicit full_formatter(padding_info padinfo) : flag_formatter(padinfo) - { - } + {} void format(const details::log_msg &msg, const std::tm &tm_time, fmt::memory_buffer &dest) override { diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 4b36ed06..b6052c1b 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -6,7 +6,6 @@ #include "spdlog/common.h" #include "spdlog/details/log_msg.h" #include "spdlog/details/os.h" -#include "spdlog/fmt/fmt.h" #include "spdlog/formatter.h" #include @@ -33,8 +32,7 @@ struct padding_info padding_info(size_t width, padding_info::pad_side side) : width_(width) , side_(side) - { - } + {} bool enabled() const { @@ -49,8 +47,7 @@ class flag_formatter public: explicit flag_formatter(padding_info padinfo) : padinfo_(padinfo) - { - } + {} flag_formatter() = default; virtual ~flag_formatter() = default; virtual void format(const details::log_msg &msg, const std::tm &tm_time, fmt::memory_buffer &dest) = 0; @@ -83,8 +80,8 @@ private: std::tm cached_tm_; std::chrono::seconds last_log_secs_; std::vector> formatters_; - std::tm get_time_(const details::log_msg &msg); + std::tm get_time_(const details::log_msg &msg); void handle_flag_(char flag, details::padding_info padding); // Extract given pad spec (e.g. %8X) @@ -96,6 +93,6 @@ private: }; } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB +#ifdef SPDLOG_HEADER_ONLY #include "pattern_formatter-inl.h" #endif diff --git a/include/spdlog/details/periodic_worker-inl.h b/include/spdlog/details/periodic_worker-inl.h index dc363913..cfc9af72 100644 --- a/include/spdlog/details/periodic_worker-inl.h +++ b/include/spdlog/details/periodic_worker-inl.h @@ -2,8 +2,9 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once - -SPDLOG_INLINE spdlog::details::periodic_worker::periodic_worker(const std::function &callback_fun, std::chrono::seconds interval) +namespace spdlog { +namespace details { +SPDLOG_INLINE periodic_worker::periodic_worker(const std::function &callback_fun, std::chrono::seconds interval) { active_ = (interval > std::chrono::seconds::zero()); if (!active_) @@ -25,7 +26,7 @@ SPDLOG_INLINE spdlog::details::periodic_worker::periodic_worker(const std::funct } // stop the worker thread and join it -SPDLOG_INLINE spdlog::details::periodic_worker::~periodic_worker() +SPDLOG_INLINE periodic_worker::~periodic_worker() { if (worker_thread_.joinable()) { @@ -37,3 +38,6 @@ SPDLOG_INLINE spdlog::details::periodic_worker::~periodic_worker() worker_thread_.join(); } } + +} // namespace details +} // namespace spdlog diff --git a/include/spdlog/details/periodic_worker.h b/include/spdlog/details/periodic_worker.h index da8ca8bb..24b9b96c 100644 --- a/include/spdlog/details/periodic_worker.h +++ b/include/spdlog/details/periodic_worker.h @@ -35,6 +35,6 @@ private: } // namespace details } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB +#ifdef SPDLOG_HEADER_ONLY #include "periodic_worker-inl.h" #endif diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 267d30a2..bc6b2cc2 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -99,6 +99,6 @@ private: } // namespace details } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB +#ifdef SPDLOG_HEADER_ONLY #include "registry-inl.h" #endif diff --git a/include/spdlog/details/thread_pool-inl.h b/include/spdlog/details/thread_pool-inl.h index d9618215..a7b77437 100644 --- a/include/spdlog/details/thread_pool-inl.h +++ b/include/spdlog/details/thread_pool-inl.h @@ -5,7 +5,9 @@ #include "spdlog/common.h" -SPDLOG_INLINE spdlog::details::thread_pool::thread_pool(size_t q_max_items, size_t threads_n) +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) @@ -20,7 +22,7 @@ SPDLOG_INLINE spdlog::details::thread_pool::thread_pool(size_t q_max_items, size } // message all threads to terminate gracefully join them -SPDLOG_INLINE spdlog::details::thread_pool::~thread_pool() +SPDLOG_INLINE thread_pool::~thread_pool() { try { @@ -35,28 +37,26 @@ SPDLOG_INLINE spdlog::details::thread_pool::~thread_pool() } } catch (...) - { - } + {} } -void SPDLOG_INLINE spdlog::details::thread_pool::post_log( - async_logger_ptr &&worker_ptr, details::log_msg &msg, async_overflow_policy overflow_policy) +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 spdlog::details::thread_pool::post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy 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 spdlog::details::thread_pool::overrun_counter() +size_t SPDLOG_INLINE thread_pool::overrun_counter() { return q_.overrun_counter(); } -void SPDLOG_INLINE spdlog::details::thread_pool::post_async_msg_(async_msg &&new_msg, async_overflow_policy overflow_policy) +void SPDLOG_INLINE thread_pool::post_async_msg_(async_msg &&new_msg, async_overflow_policy overflow_policy) { if (overflow_policy == async_overflow_policy::block) { @@ -68,7 +68,7 @@ void SPDLOG_INLINE spdlog::details::thread_pool::post_async_msg_(async_msg &&new } } -void SPDLOG_INLINE spdlog::details::thread_pool::worker_loop_() +void SPDLOG_INLINE thread_pool::worker_loop_() { while (process_next_msg_()) {}; } @@ -76,7 +76,7 @@ void SPDLOG_INLINE spdlog::details::thread_pool::worker_loop_() // process next message in the queue // return true if this thread should still be active (while no terminate msg // was received) -bool SPDLOG_INLINE spdlog::details::thread_pool::process_next_msg_() +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)); @@ -107,3 +107,6 @@ bool SPDLOG_INLINE spdlog::details::thread_pool::process_next_msg_() assert(false && "Unexpected async_msg_type"); return true; } + +} // namespace details +} // namespace spdlog diff --git a/include/spdlog/details/thread_pool.h b/include/spdlog/details/thread_pool.h index cc14bb39..42761d7a 100644 --- a/include/spdlog/details/thread_pool.h +++ b/include/spdlog/details/thread_pool.h @@ -57,8 +57,7 @@ struct async_msg msg_id(other.msg_id), source(other.source), worker_ptr(std::move(other.worker_ptr)) - { - } + {} async_msg &operator=(async_msg &&other) SPDLOG_NOEXCEPT { @@ -98,13 +97,11 @@ struct async_msg , msg_id(0) , source() , worker_ptr(std::move(worker)) - { - } + {} explicit async_msg(async_msg_type the_type) : async_msg(nullptr, the_type) - { - } + {} // copy into log_msg log_msg to_log_msg() @@ -154,6 +151,6 @@ private: } // namespace details } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB +#ifdef SPDLOG_HEADER_ONLY #include "thread_pool-inl.h" #endif \ No newline at end of file diff --git a/include/spdlog/fmt/bin_to_hex.h b/include/spdlog/fmt/bin_to_hex.h index 35233802..4a091dde 100644 --- a/include/spdlog/fmt/bin_to_hex.h +++ b/include/spdlog/fmt/bin_to_hex.h @@ -31,8 +31,7 @@ public: bytes_range(It range_begin, It range_end) : begin_(range_begin) , end_(range_end) - { - } + {} It begin() const { diff --git a/include/spdlog/fmt/fmt.h b/include/spdlog/fmt/fmt.h index c8f47158..5d039b8c 100644 --- a/include/spdlog/fmt/fmt.h +++ b/include/spdlog/fmt/fmt.h @@ -11,7 +11,7 @@ // #if !defined(SPDLOG_FMT_EXTERNAL) -#ifndef SPDLOG_STATIC_LIB +#ifdef SPDLOG_HEADER_ONLY #ifndef FMT_HEADER_ONLY #define FMT_HEADER_ONLY #endif diff --git a/include/spdlog/logger-inl.h b/include/spdlog/logger-inl.h index c0d13f11..4d0c5e24 100644 --- a/include/spdlog/logger-inl.h +++ b/include/spdlog/logger-inl.h @@ -6,8 +6,9 @@ #include "spdlog/sinks/sink.h" #include "spdlog/details/pattern_formatter.h" +namespace spdlog { // public methods -SPDLOG_INLINE void spdlog::logger::log(spdlog::source_loc loc, spdlog::level::level_enum lvl, const char *msg) +SPDLOG_INLINE void logger::log(source_loc loc, level::level_enum lvl, const char *msg) { if (!should_log(lvl)) { @@ -16,7 +17,7 @@ SPDLOG_INLINE void spdlog::logger::log(spdlog::source_loc loc, spdlog::level::le try { - details::log_msg log_msg(loc, &name_, lvl, spdlog::string_view_t(msg)); + details::log_msg log_msg(loc, &name_, lvl, string_view_t(msg)); sink_it_(log_msg); } catch (const std::exception &ex) @@ -29,39 +30,39 @@ SPDLOG_INLINE void spdlog::logger::log(spdlog::source_loc loc, spdlog::level::le } } -SPDLOG_INLINE void spdlog::logger::log(level::level_enum lvl, const char *msg) +SPDLOG_INLINE void logger::log(level::level_enum lvl, const char *msg) { log(source_loc{}, lvl, msg); } -SPDLOG_INLINE bool spdlog::logger::should_log(spdlog::level::level_enum msg_level) const +SPDLOG_INLINE bool logger::should_log(level::level_enum msg_level) const { return msg_level >= level_.load(std::memory_order_relaxed); } -SPDLOG_INLINE void spdlog::logger::set_level(spdlog::level::level_enum log_level) +SPDLOG_INLINE void logger::set_level(level::level_enum log_level) { level_.store(log_level); } -SPDLOG_INLINE spdlog::level::level_enum spdlog::logger::default_level() +SPDLOG_INLINE level::level_enum logger::default_level() { - return static_cast(SPDLOG_ACTIVE_LEVEL); + return static_cast(SPDLOG_ACTIVE_LEVEL); } -SPDLOG_INLINE spdlog::level::level_enum spdlog::logger::level() const +SPDLOG_INLINE level::level_enum logger::level() const { - return static_cast(level_.load(std::memory_order_relaxed)); + return static_cast(level_.load(std::memory_order_relaxed)); } -SPDLOG_INLINE const std::string &spdlog::logger::name() const +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 spdlog::logger::set_formatter(std::unique_ptr f) +SPDLOG_INLINE void logger::set_formatter(std::unique_ptr f) { for (auto &sink : sinks_) { @@ -69,14 +70,14 @@ SPDLOG_INLINE void spdlog::logger::set_formatter(std::unique_ptr(std::move(pattern), time_type); + auto new_formatter = details::make_unique(std::move(pattern), time_type); set_formatter(std::move(new_formatter)); } // flush functions -SPDLOG_INLINE void spdlog::logger::flush() +SPDLOG_INLINE void logger::flush() { try { @@ -92,37 +93,37 @@ SPDLOG_INLINE void spdlog::logger::flush() } } -SPDLOG_INLINE void spdlog::logger::flush_on(level::level_enum log_level) +SPDLOG_INLINE void logger::flush_on(level::level_enum log_level) { flush_level_.store(log_level); } -SPDLOG_INLINE spdlog::level::level_enum spdlog::logger::flush_level() const +SPDLOG_INLINE level::level_enum logger::flush_level() const { - return static_cast(flush_level_.load(std::memory_order_relaxed)); + return static_cast(flush_level_.load(std::memory_order_relaxed)); } // sinks -SPDLOG_INLINE const std::vector &spdlog::logger::sinks() const +SPDLOG_INLINE const std::vector &logger::sinks() const { return sinks_; } -SPDLOG_INLINE std::vector &spdlog::logger::sinks() +SPDLOG_INLINE std::vector &logger::sinks() { return sinks_; } // error handler -SPDLOG_INLINE void spdlog::logger::set_error_handler(err_handler 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 spdlog::logger::clone(std::string logger_name) +SPDLOG_INLINE std::shared_ptr logger::clone(std::string logger_name) { - auto cloned = std::make_shared(std::move(logger_name), sinks_.begin(), sinks_.end()); + auto cloned = std::make_shared(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_); @@ -130,7 +131,7 @@ SPDLOG_INLINE std::shared_ptr spdlog::logger::clone(std::string } // protected methods -SPDLOG_INLINE void spdlog::logger::sink_it_(spdlog::details::log_msg &msg) +SPDLOG_INLINE void logger::sink_it_(details::log_msg &msg) { for (auto &sink : sinks_) { @@ -146,7 +147,7 @@ SPDLOG_INLINE void spdlog::logger::sink_it_(spdlog::details::log_msg &msg) } } -SPDLOG_INLINE void spdlog::logger::flush_() +SPDLOG_INLINE void logger::flush_() { for (auto &sink : sinks_) { @@ -154,13 +155,13 @@ SPDLOG_INLINE void spdlog::logger::flush_() } } -SPDLOG_INLINE bool spdlog::logger::should_flush_(const spdlog::details::log_msg &msg) +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 spdlog::logger::err_handler_(const std::string &msg) +SPDLOG_INLINE void logger::err_handler_(const std::string &msg) { if (custom_err_handler_) { @@ -168,9 +169,10 @@ SPDLOG_INLINE void spdlog::logger::err_handler_(const std::string &msg) } else { - auto tm_time = spdlog::details::os::localtime(); + 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 \ No newline at end of file diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 21814121..89fed05d 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -35,17 +35,14 @@ public: logger(std::string name, It begin, It end) : name_(std::move(name)) , sinks_(begin, end) - { - } + {} 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; @@ -338,6 +335,6 @@ protected: }; } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB +#ifdef SPDLOG_HEADER_ONLY #include "logger-inl.h" #endif diff --git a/include/spdlog/sinks/android_sink.h b/include/spdlog/sinks/android_sink.h index 70073ae4..52b1ac8c 100644 --- a/include/spdlog/sinks/android_sink.h +++ b/include/spdlog/sinks/android_sink.h @@ -35,8 +35,7 @@ public: explicit android_sink(std::string tag = "spdlog", bool use_raw_msg = false) : tag_(std::move(tag)) , use_raw_msg_(use_raw_msg) - { - } + {} protected: void sink_it_(const details::log_msg &msg) override diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index 1eb8c931..08a30aae 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -89,6 +89,6 @@ using ansicolor_stderr_sink_st = ansicolor_sink()} -{ -} +{} SPDLOG_INLINE spdlog::sinks::sink::sink(std::unique_ptr formatter) : formatter_{std::move(formatter)} -{ -} +{} SPDLOG_INLINE bool spdlog::sinks::sink::should_log(spdlog::level::level_enum msg_level) const { diff --git a/include/spdlog/sinks/sink.h b/include/spdlog/sinks/sink.h index 2c5ef9bd..263cbe5b 100644 --- a/include/spdlog/sinks/sink.h +++ b/include/spdlog/sinks/sink.h @@ -38,6 +38,6 @@ protected: } // namespace sinks } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB +#ifdef SPDLOG_HEADER_ONLY #include "sink-inl.h" #endif diff --git a/include/spdlog/sinks/stdout_sinks.h b/include/spdlog/sinks/stdout_sinks.h index 6b7fd3ec..91274c11 100644 --- a/include/spdlog/sinks/stdout_sinks.h +++ b/include/spdlog/sinks/stdout_sinks.h @@ -26,8 +26,7 @@ public: stdout_sink() : mutex_(ConsoleMutex::mutex()) , file_(TargetStream::stream()) - { - } + {} ~stdout_sink() override = default; stdout_sink(const stdout_sink &other) = delete; diff --git a/src/format.cc b/src/format.cc deleted file mode 100644 index f2a014da..00000000 --- a/src/format.cc +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2012 - 2016, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - - -// Slightly modified version of fmt lib to include bundled format-inl.h - - -#if !defined(SPDLOG_FMT_EXTERNAL) -#include "spdlog/fmt/bundled/format-inl.h" -#else -#include "fmt/format-inl.h" -#endif - -FMT_BEGIN_NAMESPACE - template struct internal::basic_data; - template FMT_API internal::locale_ref::locale_ref(const std::locale &loc); - template FMT_API std::locale internal::locale_ref::get() const; - -// Explicit instantiations for char. - - template FMT_API char internal::thousands_sep_impl(locale_ref); - - template FMT_API void internal::basic_buffer::append(const char *, const char *); - - template FMT_API void internal::arg_map::init( - const basic_format_args &args); - - template FMT_API int internal::char_traits::format_float( - char *, std::size_t, const char *, int, double); - - template FMT_API int internal::char_traits::format_float( - char *, std::size_t, const char *, int, long double); - - template FMT_API std::string internal::vformat( - string_view, basic_format_args); - - template FMT_API format_context::iterator internal::vformat_to( - internal::buffer &, string_view, basic_format_args); - - 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::append( - const wchar_t *, const wchar_t *); - - template FMT_API void internal::arg_map::init( - const basic_format_args &); - - template FMT_API int internal::char_traits::format_float( - wchar_t *, std::size_t, const wchar_t *, int, double); - - template FMT_API int internal::char_traits::format_float( - wchar_t *, std::size_t, const wchar_t *, int, long double); - - template FMT_API std::wstring internal::vformat( - wstring_view, basic_format_args); -FMT_END_NAMESPACE diff --git a/src/format.cpp b/src/format.cpp new file mode 100644 index 00000000..0a98d58b --- /dev/null +++ b/src/format.cpp @@ -0,0 +1,51 @@ +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +// Slightly modified version of fmt lib to include bundled format-inl.h + +#if !defined(SPDLOG_FMT_EXTERNAL) +#include "spdlog/fmt/bundled/format-inl.h" +#else +#include "fmt/format-inl.h" +#endif + +FMT_BEGIN_NAMESPACE +template struct internal::basic_data; +template FMT_API internal::locale_ref::locale_ref(const std::locale &loc); +template FMT_API std::locale internal::locale_ref::get() const; + +// Explicit instantiations for char. + +template FMT_API char internal::thousands_sep_impl(locale_ref); + +template FMT_API void internal::basic_buffer::append(const char *, const char *); + +template FMT_API void internal::arg_map::init(const basic_format_args &args); + +template FMT_API int internal::char_traits::format_float(char *, std::size_t, const char *, int, double); + +template FMT_API int internal::char_traits::format_float(char *, std::size_t, const char *, int, long double); + +template FMT_API std::string internal::vformat(string_view, basic_format_args); + +template FMT_API format_context::iterator internal::vformat_to(internal::buffer &, string_view, basic_format_args); + +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::append(const wchar_t *, const wchar_t *); + +template FMT_API void internal::arg_map::init(const basic_format_args &); + +template FMT_API int internal::char_traits::format_float(wchar_t *, std::size_t, const wchar_t *, int, double); + +template FMT_API int internal::char_traits::format_float(wchar_t *, std::size_t, const wchar_t *, int, long double); + +template FMT_API std::wstring internal::vformat(wstring_view, basic_format_args); +FMT_END_NAMESPACE diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 465812c5..7c75ca31 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -2,11 +2,11 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) #include +#include #include "spdlog/common.h" #include "spdlog/common-inl.h" - #include "spdlog/details/null_mutex.h" #include "spdlog/logger.h" @@ -51,3 +51,8 @@ template class spdlog::sinks::ansicolor_sink; template class spdlog::sinks::ansicolor_sink; template class spdlog::sinks::ansicolor_sink; + +// fmt_helper templates +#include "spdlog/details/fmt_helper.h" +template void spdlog::details::fmt_helper::append_string_view(spdlog::string_view_t view, fmt::memory_buffer &dest); +template spdlog::string_view_t spdlog::details::fmt_helper::to_string_view(const fmt::memory_buffer &buf) SPDLOG_NOEXCEPT; diff --git a/tests/test_errors.cpp b/tests/test_errors.cpp index 24075634..65185d3c 100644 --- a/tests/test_errors.cpp +++ b/tests/test_errors.cpp @@ -39,8 +39,7 @@ TEST_CASE("default_error_handler", "[errors]]") } struct custom_ex -{ -}; +{}; TEST_CASE("custom_error_handler", "[errors]]") { prepare_logdir(); From bb3dc8795334c2a7670c674d1319b7b4900b3494 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 00:32:57 +0300 Subject: [PATCH 104/157] Fixed include order and example --- example/example.cpp | 17 ++++++----------- include/spdlog/common.h | 3 ++- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 532bbb5c..c76640a7 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -7,15 +7,10 @@ // // -//#include "spdlog/spdlog.h" -#include "spdlog/logger.h" -//#include "spdlog/sinks/stdout_color_sinks.h" -int main(int, char *[]) -{ - spdlog::logger *l = nullptr; - const int i = 123; - l->info("HELLO STATIC! {}", i); - l->info("HELLO STATIC! {}", "GABI"); - l->info("HELLO STATIC! {} {}", "GABI", i); - l->warn("HELLO STATIC! {} {}", "GABI", i); + +#include "spdlog/spdlog.h" + +int main(int, char *[]) { + int i = 123; + spdlog::info("HELLO STATIC! {}", i); } \ No newline at end of file diff --git a/include/spdlog/common.h b/include/spdlog/common.h index f37f08fe..d885ac61 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -19,7 +19,6 @@ #include #endif -#include "spdlog/fmt/fmt.h" #ifdef SPDLOG_STATIC_LIB #undef SPDLOG_HEADER_ONLY @@ -29,6 +28,8 @@ #define SPDLOG_INLINE inline #endif +#include "spdlog/fmt/fmt.h" + // visual studio upto 2013 does not support noexcept nor constexpr #if defined(_MSC_VER) && (_MSC_VER < 1900) #define SPDLOG_NOEXCEPT throw() From fb9e51d943443d67b7172494783cd43c6632ce9a Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 00:34:55 +0300 Subject: [PATCH 105/157] Fixed include order and example --- example/example.cpp | 227 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 223 insertions(+), 4 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index c76640a7..345f8bd1 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -7,10 +7,229 @@ // // +#include + +void stdout_logger_example(); +void basic_example(); +void rotating_example(); +void daily_example(); +void async_example(); +void binary_example(); +void trace_example(); +void multi_sink_example(); +void user_defined_example(); +void err_handler_example(); +void syslog_example(); +void clone_example(); #include "spdlog/spdlog.h" -int main(int, char *[]) { - int i = 123; - spdlog::info("HELLO STATIC! {}", i); -} \ No newline at end of file +int main(int, char *[]) +{ + 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::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); + spdlog::info("Support for floats {:03.2f}", 1.23456); + spdlog::info("Positional args are {1} {0}..", "too", "supported"); + spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left"); + + // Runtime log levels + spdlog::set_level(spdlog::level::info); // Set global log level to info + spdlog::debug("This message should not be displayed!"); + spdlog::set_level(spdlog::level::trace); // Set specific logger's log level + spdlog::debug("This message should be displayed.."); + + // Customize msg format for all loggers + spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v"); + spdlog::info("This an info message with custom format"); + spdlog::set_pattern("%+"); // back to default format + + try + { + stdout_logger_example(); + basic_example(); + rotating_example(); + daily_example(); + clone_example(); + async_example(); + binary_example(); + multi_sink_example(); + user_defined_example(); + err_handler_example(); + trace_example(); + + // Flush all *registered* loggers using a worker thread every 3 seconds. + // note: registered loggers *must* be thread safe for this to work correctly! + spdlog::flush_every(std::chrono::seconds(3)); + + // Apply some function on all registered loggers + spdlog::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); + + // Release all spdlog resources, and drop all loggers in the registry. + // This is optional (only mandatory if using windows + async log). + spdlog::shutdown(); + } + + // Exceptions will only be thrown upon failed logger or sink construction (not during logging). + catch (const spdlog::spdlog_ex &ex) + { + std::printf("Log initialization failed: %s\n", ex.what()); + return 1; + } +} + +#include "spdlog/sinks/stdout_color_sinks.h" +// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed. +void stdout_logger_example() +{ + // Create color multi threaded logger. + auto console = spdlog::stdout_color_mt("console"); + // or for stderr: + // auto console = spdlog::stderr_color_mt("error-logger"); +} + +#include "spdlog/sinks/basic_file_sink.h" +void basic_example() +{ + // Create basic file logger (not rotated). + auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt"); +} + +#include "spdlog/sinks/rotating_file_sink.h" +void rotating_example() +{ + // Create a file rotating logger with 5mb size max and 3 rotated files. + auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); +} + +#include "spdlog/sinks/daily_file_sink.h" +void daily_example() +{ + // Create a daily logger - a new file is created every day on 2:30am. + auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); +} + +// Clone a logger and give it new name. +// Useful for creating component/subsystem loggers from some "root" logger. +void clone_example() +{ + auto network_logger = spdlog::default_logger()->clone("network"); + network_logger->info("Logging network stuff.."); +} + +#include "spdlog/async.h" +void async_example() +{ + // Default thread pool settings can be modified *before* creating the async logger: + // spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread. + auto async_file = spdlog::basic_logger_mt("async_file_logger", "logs/async_log.txt"); + // alternatively: + // auto async_file = spdlog::create_async("async_file_logger", "logs/async_log.txt"); + + for (int i = 1; i < 101; ++i) + { + async_file->info("Async message #{}", i); + } +} + +// Log binary data as hex. +// Many types of std::container types can be used. +// Iterator ranges are supported too. +// Format flags: +// {:X} - print in uppercase. +// {:s} - don't separate each byte with space. +// {:p} - don't print the position on each line start. +// {:n} - don't split the output to lines. + +#include "spdlog/fmt/bin_to_hex.h" +void binary_example() +{ + std::vector buf; + for (int i = 0; i < 80; i++) + { + buf.push_back(static_cast(i & 0xff)); + } + spdlog::info("Binary example: {}", spdlog::to_hex(buf)); + spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10)); + // more examples: + // logger->info("uppercase: {:X}", spdlog::to_hex(buf)); + // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf)); + // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf)); +} + +// Compile time log levels. +// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE) +void trace_example() +{ + // trace from default logger + SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23); + // debug from default logger + SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23); + + // trace from logger object + auto logger = spdlog::get("file_logger"); + SPDLOG_LOGGER_TRACE(logger, "another trace message"); +} + +// A logger with multiple sinks (stdout and file) - each with a different format and log level. +void multi_sink_example() +{ + auto console_sink = std::make_shared(); + console_sink->set_level(spdlog::level::warn); + console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v"); + + auto file_sink = std::make_shared("logs/multisink.txt", true); + file_sink->set_level(spdlog::level::trace); + + spdlog::logger logger("multi_sink", {console_sink, file_sink}); + logger.set_level(spdlog::level::debug); + logger.warn("this should appear in both console and file"); + logger.info("this message should not appear in the console, only in the file"); +} + +// User defined types logging by implementing operator<< +#include "spdlog/fmt/ostr.h" // must be included +struct my_type +{ + int i; + template + friend OStream &operator<<(OStream &os, const my_type &c) + { + return os << "[my_type i=" << c.i << "]"; + } +}; + +void user_defined_example() +{ + spdlog::info("user defined type: {}", my_type{14}); +} + +// Custom error handler. Will be triggered on log failure. +void err_handler_example() +{ + // can be set globally or per logger(logger->set_error_handler(..)) + spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); }); +} + +// syslog example (linux/osx/freebsd) +#ifndef _WIN32 +#include "spdlog/sinks/syslog_sink.h" +void syslog_example() +{ + std::string ident = "spdlog-example"; + auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID); + syslog_logger->warn("This is warning that will end up in syslog."); +} +#endif + +// Android example. +#if defined(__ANDROID__) +#include "spdlog/sinks/android_sink.h" +void android_example() +{ + std::string tag = "spdlog-android"; + auto android_logger = spdlog::android_logger_mt("android", tag); + android_logger->critical("Use \"adb shell logcat\" to view this message."); +} + +#endif From 8b244ca988570bc7f01d5a2c682cde0bce013784 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 00:43:58 +0300 Subject: [PATCH 106/157] Moved format.cpp into spdlog.cpp - this way only one src file is needed --- CMakeLists.txt | 2 +- include/spdlog/common.h | 1 - src/format.cpp | 51 ----------------------------------------- src/spdlog.cpp | 51 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 52 insertions(+), 53 deletions(-) delete mode 100644 src/format.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4b2775b0..1a82606d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,7 +60,7 @@ message(STATUS "Static lib: " ${SPDLOG_STATIC_LIB}) if(SPDLOG_STATIC_LIB) add_definitions(-DSPDLOG_STATIC_LIB) set(SRC_BASE "${CMAKE_CURRENT_SOURCE_DIR}/src") - set(SRC_FILES "${SRC_BASE}/spdlog.cpp" "${SRC_BASE}/format.cpp") + set(SRC_FILES "${SRC_BASE}/spdlog.cpp") add_library(spdlog STATIC ${SRC_FILES}) target_include_directories(spdlog PUBLIC "$") target_link_libraries(spdlog -Wl,--as-needed) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index d885ac61..819f3abb 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -19,7 +19,6 @@ #include #endif - #ifdef SPDLOG_STATIC_LIB #undef SPDLOG_HEADER_ONLY #define SPDLOG_INLINE diff --git a/src/format.cpp b/src/format.cpp deleted file mode 100644 index 0a98d58b..00000000 --- a/src/format.cpp +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2012 - 2016, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -// Slightly modified version of fmt lib to include bundled format-inl.h - -#if !defined(SPDLOG_FMT_EXTERNAL) -#include "spdlog/fmt/bundled/format-inl.h" -#else -#include "fmt/format-inl.h" -#endif - -FMT_BEGIN_NAMESPACE -template struct internal::basic_data; -template FMT_API internal::locale_ref::locale_ref(const std::locale &loc); -template FMT_API std::locale internal::locale_ref::get() const; - -// Explicit instantiations for char. - -template FMT_API char internal::thousands_sep_impl(locale_ref); - -template FMT_API void internal::basic_buffer::append(const char *, const char *); - -template FMT_API void internal::arg_map::init(const basic_format_args &args); - -template FMT_API int internal::char_traits::format_float(char *, std::size_t, const char *, int, double); - -template FMT_API int internal::char_traits::format_float(char *, std::size_t, const char *, int, long double); - -template FMT_API std::string internal::vformat(string_view, basic_format_args); - -template FMT_API format_context::iterator internal::vformat_to(internal::buffer &, string_view, basic_format_args); - -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::append(const wchar_t *, const wchar_t *); - -template FMT_API void internal::arg_map::init(const basic_format_args &); - -template FMT_API int internal::char_traits::format_float(wchar_t *, std::size_t, const wchar_t *, int, double); - -template FMT_API int internal::char_traits::format_float(wchar_t *, std::size_t, const wchar_t *, int, long double); - -template FMT_API std::wstring internal::vformat(wstring_view, basic_format_args); -FMT_END_NAMESPACE diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 7c75ca31..9052bc2a 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -56,3 +56,54 @@ template class spdlog::sinks::ansicolor_sink; +template FMT_API internal::locale_ref::locale_ref(const std::locale &loc); +template FMT_API std::locale internal::locale_ref::get() const; + +// Explicit instantiations for char. + +template FMT_API char internal::thousands_sep_impl(locale_ref); + +template FMT_API void internal::basic_buffer::append(const char *, const char *); + +template FMT_API void internal::arg_map::init(const basic_format_args &args); + +template FMT_API int internal::char_traits::format_float(char *, std::size_t, const char *, int, double); + +template FMT_API int internal::char_traits::format_float(char *, std::size_t, const char *, int, long double); + +template FMT_API std::string internal::vformat(string_view, basic_format_args); + +template FMT_API format_context::iterator internal::vformat_to(internal::buffer &, string_view, basic_format_args); + +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::append(const wchar_t *, const wchar_t *); + +template FMT_API void internal::arg_map::init(const basic_format_args &); + +template FMT_API int internal::char_traits::format_float(wchar_t *, std::size_t, const wchar_t *, int, double); + +template FMT_API int internal::char_traits::format_float(wchar_t *, std::size_t, const wchar_t *, int, long double); + +template FMT_API std::wstring internal::vformat(wstring_view, basic_format_args); +FMT_END_NAMESPACE From 369b2f7cd26c99d59d27465cbc1e6c93842a0bb0 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 00:44:26 +0300 Subject: [PATCH 107/157] Moved format.cpp into spdlog.cpp - this way only one src file is needed --- src/spdlog.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 9052bc2a..359c3b2f 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -57,11 +57,10 @@ template class spdlog::sinks::ansicolor_sink Date: Sun, 12 May 2019 00:50:43 +0300 Subject: [PATCH 108/157] Don't include fmt format.cc source if using external fmt --- src/spdlog.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 359c3b2f..57a70067 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -58,15 +58,12 @@ template void spdlog::details::fmt_helper::append_string_view(spdlog::string_vie template spdlog::string_view_t spdlog::details::fmt_helper::to_string_view(const fmt::memory_buffer &buf) SPDLOG_NOEXCEPT; -// Slightly modified version of fmt lib's format.cc source file +// 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" -#else -#include "fmt/format-inl.h" -#endif FMT_BEGIN_NAMESPACE template struct internal::basic_data; @@ -106,3 +103,5 @@ template FMT_API int internal::char_traits::format_float(wchar_t *, std template FMT_API std::wstring internal::vformat(wstring_view, basic_format_args); FMT_END_NAMESPACE + +#endif \ No newline at end of file From ca9c8ae5fb95dfcba20bd79525f603ea37def172 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 01:01:37 +0300 Subject: [PATCH 109/157] Warn if compiling spdlog.cpp under header only configuration --- src/spdlog.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 57a70067..5ec66b81 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -1,10 +1,14 @@ // Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) +#ifndef SPDLOG_STATIC_LIB +#warning spdlog is in header only configuration. please define SPDLOG_STATIC_LIB +#endif #include #include #include "spdlog/common.h" + #include "spdlog/common-inl.h" #include "spdlog/details/null_mutex.h" From 654f7eceeefe475ab386b743e0246e136a00b04f Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 01:04:48 +0300 Subject: [PATCH 110/157] #error if compiling spdlog.cpp under header only configuration --- src/spdlog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 5ec66b81..7399c4ee 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -1,7 +1,7 @@ // Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) #ifndef SPDLOG_STATIC_LIB -#warning spdlog is in header only configuration. please define SPDLOG_STATIC_LIB +#error spdlog is in HEADER_ONLY configuration. Define SPDLOG_STATIC_LIB to compile this file. #endif #include From 3834acad5b2d524dd554d82ed2c455ab15f963c0 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 01:12:46 +0300 Subject: [PATCH 111/157] #error if compiling spdlog.cpp under header only configuration --- src/spdlog.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 7399c4ee..60b18966 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -1,7 +1,8 @@ // Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) + #ifndef SPDLOG_STATIC_LIB -#error spdlog is in HEADER_ONLY configuration. Define SPDLOG_STATIC_LIB to compile this file. +#error Please define SPDLOG_STATIC_LIB to compile this file. #endif #include From 42e30468a9f97e9bc9a90ec8a3896543e67f92cc Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 01:43:30 +0300 Subject: [PATCH 112/157] added rotating_file_sink to static build --- include/spdlog/sinks/rotating_file_sink-inl.h | 132 ++++++++++++++++++ include/spdlog/sinks/rotating_file_sink.h | 106 ++------------ src/spdlog.cpp | 6 +- 3 files changed, 150 insertions(+), 94 deletions(-) create mode 100644 include/spdlog/sinks/rotating_file_sink-inl.h diff --git a/include/spdlog/sinks/rotating_file_sink-inl.h b/include/spdlog/sinks/rotating_file_sink-inl.h new file mode 100644 index 00000000..17a4ee93 --- /dev/null +++ b/include/spdlog/sinks/rotating_file_sink-inl.h @@ -0,0 +1,132 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + +#include "spdlog/common.h" + +#include "spdlog/details/file_helper.h" +#include "spdlog/details/null_mutex.h" +#include "spdlog/fmt/fmt.h" + +#include +#include +#include +#include +#include +#include + + +namespace spdlog { +namespace sinks { + +template +SPDLOG_INLINE rotating_file_sink::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 +SPDLOG_INLINE filename_t rotating_file_sink::calc_filename(const filename_t &filename, std::size_t index) +{ + typename std::conditional::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 +SPDLOG_INLINE const filename_t &rotating_file_sink::filename() const +{ + return file_helper_.filename(); +} + +template +SPDLOG_INLINE void rotating_file_sink::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 +SPDLOG_INLINE void rotating_file_sink::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 +SPDLOG_INLINE void rotating_file_sink::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 +SPDLOG_INLINE bool rotating_file_sink::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 diff --git a/include/spdlog/sinks/rotating_file_sink.h b/include/spdlog/sinks/rotating_file_sink.h index ab658532..0ce71a61 100644 --- a/include/spdlog/sinks/rotating_file_sink.h +++ b/include/spdlog/sinks/rotating_file_sink.h @@ -2,22 +2,16 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once - #ifndef SPDLOG_H #include "spdlog/spdlog.h" #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/details/file_helper.h" -#include #include -#include #include #include -#include namespace spdlog { namespace sinks { @@ -29,60 +23,15 @@ template class rotating_file_sink final : public base_sink { public: - 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)) - , 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_(); - } - } + rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open = false); + static filename_t calc_filename(const filename_t &filename, std::size_t index); + const filename_t &filename() const; - // 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::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: - void sink_it_(const details::log_msg &msg) 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 sink_it_(const details::log_msg &msg) override; + void flush_() override; - void flush_() override - { - file_helper_.flush(); - } private: // Rotate files: @@ -90,45 +39,11 @@ private: // log.1.txt -> log.2.txt // log.2.txt -> log.3.txt // log.3.txt -> delete - 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); - } + void rotate_(); // delete the target if exists, and rename the src file to target // return true on success, false otherwise. - 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; - } + bool rename_file(const filename_t &src_filename, const filename_t &target_filename); filename_t base_filename_; std::size_t max_size_; @@ -160,3 +75,8 @@ inline std::shared_ptr rotating_logger_st( return Factory::template create(logger_name, filename, max_file_size, max_files, rotate_on_open); } } // namespace spdlog + + +#ifdef SPDLOG_HEADER_ONLY +#include "rotating_file_sink-inl.h" +#endif \ No newline at end of file diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 60b18966..c5fbf8f0 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -31,6 +31,11 @@ template class spdlog::sinks::base_sink; template class spdlog::sinks::base_sink; +#include "spdlog/sinks/rotating_file_sink.h" +#include "spdlog/sinks/rotating_file_sink-inl.h" +template class spdlog::sinks::rotating_file_sink; +template class spdlog::sinks::rotating_file_sink; + #include "spdlog/details/registry.h" #include "spdlog/details/registry-inl.h" @@ -62,7 +67,6 @@ template class spdlog::sinks::ansicolor_sink Date: Sun, 12 May 2019 02:10:39 +0300 Subject: [PATCH 113/157] wip static-lib --- include/spdlog/sinks/rotating_file_sink-inl.h | 3 --- include/spdlog/sinks/rotating_file_sink.h | 4 +--- src/spdlog.cpp | 17 +++-------------- 3 files changed, 4 insertions(+), 20 deletions(-) diff --git a/include/spdlog/sinks/rotating_file_sink-inl.h b/include/spdlog/sinks/rotating_file_sink-inl.h index 17a4ee93..db13a738 100644 --- a/include/spdlog/sinks/rotating_file_sink-inl.h +++ b/include/spdlog/sinks/rotating_file_sink-inl.h @@ -16,7 +16,6 @@ #include #include - namespace spdlog { namespace sinks { @@ -54,8 +53,6 @@ SPDLOG_INLINE filename_t rotating_file_sink::calc_filename(const filename return fmt::to_string(w); } - - template SPDLOG_INLINE const filename_t &rotating_file_sink::filename() const { diff --git a/include/spdlog/sinks/rotating_file_sink.h b/include/spdlog/sinks/rotating_file_sink.h index 0ce71a61..a454086b 100644 --- a/include/spdlog/sinks/rotating_file_sink.h +++ b/include/spdlog/sinks/rotating_file_sink.h @@ -2,6 +2,7 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once + #ifndef SPDLOG_H #include "spdlog/spdlog.h" #endif @@ -27,12 +28,10 @@ public: static filename_t calc_filename(const filename_t &filename, std::size_t index); const filename_t &filename() const; - protected: void sink_it_(const details::log_msg &msg) override; void flush_() override; - private: // Rotate files: // log.txt -> log.1.txt @@ -76,7 +75,6 @@ inline std::shared_ptr rotating_logger_st( } } // namespace spdlog - #ifdef SPDLOG_HEADER_ONLY #include "rotating_file_sink-inl.h" #endif \ No newline at end of file diff --git a/src/spdlog.cpp b/src/spdlog.cpp index c5fbf8f0..4a16a0d9 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -16,6 +16,9 @@ #include "spdlog/logger.h" #include "spdlog/logger-inl.h" +template class std::shared_ptr; +template class std::function; +template spdlog::logger::logger(std::string name, sinks_init_list::iterator begin, sinks_init_list::iterator end); #include "spdlog/async_logger.h" #include "spdlog/async_logger-inl.h" @@ -80,36 +83,22 @@ template FMT_API internal::locale_ref::locale_ref(const std::locale &loc); template FMT_API std::locale internal::locale_ref::get() const; // Explicit instantiations for char. - template FMT_API char internal::thousands_sep_impl(locale_ref); - template FMT_API void internal::basic_buffer::append(const char *, const char *); - template FMT_API void internal::arg_map::init(const basic_format_args &args); - template FMT_API int internal::char_traits::format_float(char *, std::size_t, const char *, int, double); - template FMT_API int internal::char_traits::format_float(char *, std::size_t, const char *, int, long double); - template FMT_API std::string internal::vformat(string_view, basic_format_args); - template FMT_API format_context::iterator internal::vformat_to(internal::buffer &, string_view, basic_format_args); - 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::append(const wchar_t *, const wchar_t *); - template FMT_API void internal::arg_map::init(const basic_format_args &); - template FMT_API int internal::char_traits::format_float(wchar_t *, std::size_t, const wchar_t *, int, double); - template FMT_API int internal::char_traits::format_float(wchar_t *, std::size_t, const wchar_t *, int, long double); - template FMT_API std::wstring internal::vformat(wstring_view, basic_format_args); FMT_END_NAMESPACE From 130bc26b9ad674b09130e3b83128fc5d83ba4ce0 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 02:16:31 +0300 Subject: [PATCH 114/157] wip static-lib --- src/spdlog.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 4a16a0d9..83299175 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -16,8 +16,6 @@ #include "spdlog/logger.h" #include "spdlog/logger-inl.h" -template class std::shared_ptr; -template class std::function; template spdlog::logger::logger(std::string name, sinks_init_list::iterator begin, sinks_init_list::iterator end); #include "spdlog/async_logger.h" From 01f5efa1d97dfb1d6c8ff0f16851d84527315a3f Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 15:32:54 +0300 Subject: [PATCH 115/157] Added wincolor sink to static build --- include/spdlog/sinks/wincolor_sink-inl.h | 102 +++++++++++++++++++++++ include/spdlog/sinks/wincolor_sink.h | 100 ++++------------------ src/spdlog.cpp | 10 +++ 3 files changed, 127 insertions(+), 85 deletions(-) create mode 100644 include/spdlog/sinks/wincolor_sink-inl.h diff --git a/include/spdlog/sinks/wincolor_sink-inl.h b/include/spdlog/sinks/wincolor_sink-inl.h new file mode 100644 index 00000000..e778496f --- /dev/null +++ b/include/spdlog/sinks/wincolor_sink-inl.h @@ -0,0 +1,102 @@ +#pragma once + + +namespace spdlog { +namespace sinks { +template +SPDLOG_INLINE wincolor_sink::wincolor_sink() + : out_handle_(TargetStream::handle()) + , mutex_(ConsoleMutex::mutex()) +{ + 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 +SPDLOG_INLINE SPDLOG_INLINE wincolor_sink::~wincolor_sink() +{ + this->flush(); +} + +// change the color for the given level +template +void SPDLOG_INLINE wincolor_sink::set_color(level::level_enum level, WORD color) +{ + std::lock_guard lock(mutex_); + colors_[level] = color; +} + +template +void SPDLOG_INLINE wincolor_sink::log(const details::log_msg &msg) +{ + std::lock_guard lock(mutex_); + fmt::memory_buffer formatted; + formatter_->format(msg, formatted); + if (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 + { + print_range_(formatted, 0, formatted.size()); + } +} + +template +void SPDLOG_INLINE wincolor_sink::flush() +{ + // windows console always flushed? +} + +template +void SPDLOG_INLINE wincolor_sink::set_pattern(const std::string &pattern) +{ + std::lock_guard lock(mutex_); + formatter_ = std::unique_ptr(new pattern_formatter(pattern)); +} + +template +void SPDLOG_INLINE wincolor_sink::set_formatter(std::unique_ptr sink_formatter) +{ + std::lock_guard lock(mutex_); + formatter_ = std::move(sink_formatter); +} + +// set color and return the orig console attributes (for resetting later) +template +WORD SPDLOG_INLINE wincolor_sink::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(~(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 +void SPDLOG_INLINE wincolor_sink::print_range_(const fmt::memory_buffer &formatted, size_t start, size_t end) +{ + auto size = static_cast(end - start); + ::WriteConsoleA(out_handle_, formatted.data() + start, size, nullptr, nullptr); +} + +} +} // namespace spdlog \ No newline at end of file diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index 70ee4a60..fd17b3d6 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -24,7 +24,7 @@ namespace sinks { * Windows color console sink. Uses WriteConsoleA to write to the console with * colors */ -template +template class wincolor_sink : public sink { public: @@ -35,100 +35,30 @@ public: const WORD WHITE = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; const WORD YELLOW = FOREGROUND_RED | FOREGROUND_GREEN; - wincolor_sink() - : out_handle_(OutHandle::handle()) - , mutex_(ConsoleMutex::mutex()) - { - 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(); + ~wincolor_sink() override; wincolor_sink(const wincolor_sink &other) = delete; wincolor_sink &operator=(const wincolor_sink &other) = delete; // change the color for the given level - void set_color(level::level_enum level, WORD color) - { - std::lock_guard lock(mutex_); - colors_[level] = color; - } - - void log(const details::log_msg &msg) final override - { - std::lock_guard lock(mutex_); - fmt::memory_buffer formatted; - formatter_->format(msg, formatted); - if (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 - { - 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 lock(mutex_); - formatter_ = std::unique_ptr(new pattern_formatter(pattern)); - } - - void set_formatter(std::unique_ptr sink_formatter) override final - { - std::lock_guard lock(mutex_); - formatter_ = std::move(sink_formatter); - } + void set_color(level::level_enum level, WORD color); + void log(const details::log_msg &msg) final override; + void flush() final override; + void set_pattern(const std::string &pattern) override final; + void set_formatter(std::unique_ptr sink_formatter) override final; + private: - using mutex_t = typename ConsoleMutex::mutex_t; - // 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(~(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(end - start); - ::WriteConsoleA(out_handle_, formatted.data() + start, size, nullptr, nullptr); - } - + using mutex_t = typename ConsoleMutex::mutex_t; HANDLE out_handle_; mutex_t &mutex_; std::unordered_map 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; diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 83299175..319956a4 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -56,12 +56,22 @@ template class spdlog::sinks::rotating_file_sink; #include "spdlog/details/thread_pool-inl.h" template class spdlog::details::mpmc_blocking_queue; +#ifndef _WIN32 #include "spdlog/sinks/ansicolor_sink.h" #include "spdlog/sinks/ansicolor_sink-inl.h" template class spdlog::sinks::ansicolor_sink; template class spdlog::sinks::ansicolor_sink; template class spdlog::sinks::ansicolor_sink; template class spdlog::sinks::ansicolor_sink; +#else +#include "spdlog/sinks/wincolor_sink.h" +#include "spdlog/sinks/wincolor_sink-inl.h" +template class spdlog::sinks::wincolor_sink; +template class spdlog::sinks::wincolor_sink; +template class spdlog::sinks::wincolor_sink; +template class spdlog::sinks::wincolor_sink; +#endif + // fmt_helper templates #include "spdlog/details/fmt_helper.h" From 8b4eedb594b2034c39e1eb66f40453d2c7b070ac Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 16:11:35 +0300 Subject: [PATCH 116/157] More template instantiations for static lib --- include/spdlog/sinks/stdout_color_sinks-inl.h | 34 +++++++++++++++++++ include/spdlog/sinks/stdout_color_sinks.h | 25 +++++--------- include/spdlog/sinks/wincolor_sink-inl.h | 6 ++-- include/spdlog/sinks/wincolor_sink.h | 4 +++ 4 files changed, 51 insertions(+), 18 deletions(-) create mode 100644 include/spdlog/sinks/stdout_color_sinks-inl.h diff --git a/include/spdlog/sinks/stdout_color_sinks-inl.h b/include/spdlog/sinks/stdout_color_sinks-inl.h new file mode 100644 index 00000000..018aaf5e --- /dev/null +++ b/include/spdlog/sinks/stdout_color_sinks-inl.h @@ -0,0 +1,34 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + +#include "spdlog/logger.h" +#include "spdlog/common.h" + +namespace spdlog { + +template +SPDLOG_INLINE std::shared_ptr stdout_color_mt(const std::string &logger_name) +{ + return Factory::template create(logger_name); +} + +template +SPDLOG_INLINE std::shared_ptr stdout_color_st(const std::string &logger_name) +{ + return Factory::template create(logger_name); +} + +template +SPDLOG_INLINE std::shared_ptr stderr_color_mt(const std::string &logger_name) +{ + return Factory::template create(logger_name); +} + +template +SPDLOG_INLINE std::shared_ptr stderr_color_st(const std::string &logger_name) +{ + return Factory::template create(logger_name); +} +} // namespace spdlog \ No newline at end of file diff --git a/include/spdlog/sinks/stdout_color_sinks.h b/include/spdlog/sinks/stdout_color_sinks.h index bc8fcbab..fe1452e5 100644 --- a/include/spdlog/sinks/stdout_color_sinks.h +++ b/include/spdlog/sinks/stdout_color_sinks.h @@ -29,26 +29,19 @@ using stderr_color_sink_st = ansicolor_stderr_sink_st; } // namespace sinks template -inline std::shared_ptr stdout_color_mt(const std::string &logger_name) -{ - return Factory::template create(logger_name); -} +std::shared_ptr stdout_color_mt(const std::string &logger_name); template -inline std::shared_ptr stdout_color_st(const std::string &logger_name) -{ - return Factory::template create(logger_name); -} +std::shared_ptr stdout_color_st(const std::string &logger_name); template -inline std::shared_ptr stderr_color_mt(const std::string &logger_name) -{ - return Factory::template create(logger_name); -} +std::shared_ptr stderr_color_mt(const std::string &logger_name); template -inline std::shared_ptr stderr_color_st(const std::string &logger_name) -{ - return Factory::template create(logger_name); -} +std::shared_ptr stderr_color_st(const std::string &logger_name); + } // namespace spdlog + +#ifdef SPDLOG_HEADER_ONLY +#include "stdout_color_sinks-inl.h" +#endif \ No newline at end of file diff --git a/include/spdlog/sinks/wincolor_sink-inl.h b/include/spdlog/sinks/wincolor_sink-inl.h index e778496f..8600e0ad 100644 --- a/include/spdlog/sinks/wincolor_sink-inl.h +++ b/include/spdlog/sinks/wincolor_sink-inl.h @@ -1,5 +1,7 @@ -#pragma once +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +#pragma once namespace spdlog { namespace sinks { @@ -18,7 +20,7 @@ SPDLOG_INLINE wincolor_sink::wincolor_sink() } template -SPDLOG_INLINE SPDLOG_INLINE wincolor_sink::~wincolor_sink() +SPDLOG_INLINE wincolor_sink::~wincolor_sink() { this->flush(); } diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index fd17b3d6..7645819c 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -69,3 +69,7 @@ using wincolor_stderr_sink_st = wincolor_sink Date: Sun, 12 May 2019 16:13:13 +0300 Subject: [PATCH 117/157] Minore cmake fix --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1a82606d..017db67e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -63,7 +63,7 @@ if(SPDLOG_STATIC_LIB) set(SRC_FILES "${SRC_BASE}/spdlog.cpp") add_library(spdlog STATIC ${SRC_FILES}) target_include_directories(spdlog PUBLIC "$") - target_link_libraries(spdlog -Wl,--as-needed) + target_link_libraries(spdlog) else() add_library(spdlog INTERFACE) target_include_directories(spdlog INTERFACE "$") From 5220ac4a9ef1c2fa015e7651e1e3b888fd2c46d9 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 17:05:14 +0300 Subject: [PATCH 118/157] Added missing header --- example/example.cpp | 8 +++----- src/spdlog.cpp | 31 ++++++++++++++++++++++--------- 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 345f8bd1..e6508156 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -1,11 +1,9 @@ // // Copyright(c) 2015 Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// -// + + // spdlog usage example -// -// #include @@ -26,7 +24,7 @@ void clone_example(); 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::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); diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 319956a4..d4e78ffc 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -8,8 +8,10 @@ #include #include -#include "spdlog/common.h" +#include "spdlog/spdlog.h" +#include "spdlog/async.h" +#include "spdlog/common.h" #include "spdlog/common-inl.h" #include "spdlog/details/null_mutex.h" @@ -56,22 +58,33 @@ template class spdlog::sinks::rotating_file_sink; #include "spdlog/details/thread_pool-inl.h" template class spdlog::details::mpmc_blocking_queue; -#ifndef _WIN32 -#include "spdlog/sinks/ansicolor_sink.h" -#include "spdlog/sinks/ansicolor_sink-inl.h" -template class spdlog::sinks::ansicolor_sink; -template class spdlog::sinks::ansicolor_sink; -template class spdlog::sinks::ansicolor_sink; -template class spdlog::sinks::ansicolor_sink; -#else +#ifdef _WIN32 #include "spdlog/sinks/wincolor_sink.h" #include "spdlog/sinks/wincolor_sink-inl.h" template class spdlog::sinks::wincolor_sink; template class spdlog::sinks::wincolor_sink; template class spdlog::sinks::wincolor_sink; template class spdlog::sinks::wincolor_sink; +#else +#include "spdlog/sinks/ansicolor_sink.h" +#include "spdlog/sinks/ansicolor_sink-inl.h" +template class spdlog::sinks::ansicolor_sink; +template class spdlog::sinks::ansicolor_sink; +template class spdlog::sinks::ansicolor_sink; +template class spdlog::sinks::ansicolor_sink; #endif +#include "spdlog/sinks/stdout_color_sinks.h" +#include "spdlog/sinks/stdout_color_sinks-inl.h" +template std::shared_ptr spdlog::stdout_color_mt(const std::string &logger_name); +template std::shared_ptr spdlog::stdout_color_st(const std::string &logger_name); +template std::shared_ptr spdlog::stderr_color_mt(const std::string &logger_name); +template std::shared_ptr spdlog::stderr_color_st(const std::string &logger_name); + +template std::shared_ptr spdlog::stdout_color_mt(const std::string &logger_name); +template std::shared_ptr spdlog::stdout_color_st(const std::string &logger_name); +template std::shared_ptr spdlog::stderr_color_mt(const std::string &logger_name); +template std::shared_ptr spdlog::stderr_color_st(const std::string &logger_name); // fmt_helper templates #include "spdlog/details/fmt_helper.h" From 1665006401cd81a834c1660cb73430f4ddfe3fb1 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 17:12:08 +0300 Subject: [PATCH 119/157] Minor fix in example --- example/example.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/example.cpp b/example/example.cpp index e6508156..80da45bb 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -24,7 +24,7 @@ void clone_example(); 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::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); From d5c9bac3c79f0a9ec656a2f7ec27f5e29e75181a Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 23:08:14 +0300 Subject: [PATCH 120/157] wip static-lib --- example/example.cpp | 1 - include/spdlog/sinks/daily_file_sink.h | 1 + include/spdlog/sinks/stdout_sinks.h | 1 + include/spdlog/sinks/wincolor_sink-inl.h | 10 +-- include/spdlog/sinks/wincolor_sink.h | 15 ++-- include/spdlog/spdlog-inl.h | 96 ++++++++++++++++++++++++ include/spdlog/spdlog.h | 90 ++++++---------------- src/spdlog.cpp | 2 + 8 files changed, 133 insertions(+), 83 deletions(-) create mode 100644 include/spdlog/spdlog-inl.h diff --git a/example/example.cpp b/example/example.cpp index e6508156..9647fddd 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -2,7 +2,6 @@ // Copyright(c) 2015 Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) - // spdlog usage example #include diff --git a/include/spdlog/sinks/daily_file_sink.h b/include/spdlog/sinks/daily_file_sink.h index a240294c..23ca6f0b 100644 --- a/include/spdlog/sinks/daily_file_sink.h +++ b/include/spdlog/sinks/daily_file_sink.h @@ -11,6 +11,7 @@ #include "spdlog/details/null_mutex.h" #include "spdlog/fmt/fmt.h" #include "spdlog/sinks/base_sink.h" +#include "spdlog/details/os.h" #include #include diff --git a/include/spdlog/sinks/stdout_sinks.h b/include/spdlog/sinks/stdout_sinks.h index 91274c11..91bed987 100644 --- a/include/spdlog/sinks/stdout_sinks.h +++ b/include/spdlog/sinks/stdout_sinks.h @@ -9,6 +9,7 @@ #include "spdlog/details/console_globals.h" #include "spdlog/details/null_mutex.h" +#include "spdlog/details/pattern_formatter.h" #include #include diff --git a/include/spdlog/sinks/wincolor_sink-inl.h b/include/spdlog/sinks/wincolor_sink-inl.h index 8600e0ad..da5262b3 100644 --- a/include/spdlog/sinks/wincolor_sink-inl.h +++ b/include/spdlog/sinks/wincolor_sink-inl.h @@ -7,8 +7,8 @@ namespace spdlog { namespace sinks { template SPDLOG_INLINE wincolor_sink::wincolor_sink() - : out_handle_(TargetStream::handle()) - , mutex_(ConsoleMutex::mutex()) + : out_handle_(TargetStream::handle()) + , mutex_(ConsoleMutex::mutex()) { colors_[level::trace] = WHITE; colors_[level::debug] = CYAN; @@ -49,7 +49,7 @@ void SPDLOG_INLINE wincolor_sink::log(const details: print_range_(formatted, msg.color_range_start, msg.color_range_end); ::SetConsoleTextAttribute(out_handle_, orig_attribs); // reset to orig colors - // after color range + // after color range print_range_(formatted, msg.color_range_end, formatted.size()); } else // print without colors if color range is invalid @@ -77,7 +77,7 @@ void SPDLOG_INLINE wincolor_sink::set_formatter(std: std::lock_guard lock(mutex_); formatter_ = std::move(sink_formatter); } - + // set color and return the orig console attributes (for resetting later) template WORD SPDLOG_INLINE wincolor_sink::set_console_attribs(WORD attribs) @@ -100,5 +100,5 @@ void SPDLOG_INLINE wincolor_sink::print_range_(const ::WriteConsoleA(out_handle_, formatted.data() + start, size, nullptr, nullptr); } -} +} // namespace sinks } // namespace spdlog \ No newline at end of file diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index 7645819c..29319fd9 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -35,27 +35,26 @@ public: const WORD WHITE = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; const WORD YELLOW = FOREGROUND_RED | FOREGROUND_GREEN; - wincolor_sink(); + wincolor_sink(); ~wincolor_sink() override; wincolor_sink(const wincolor_sink &other) = delete; wincolor_sink &operator=(const wincolor_sink &other) = delete; // change the color for the given level - void set_color(level::level_enum level, WORD color); - void log(const details::log_msg &msg) final override; - void flush() final override; - void set_pattern(const std::string &pattern) override final; + void set_color(level::level_enum level, WORD color); + void log(const details::log_msg &msg) final override; + void flush() final override; + void set_pattern(const std::string &pattern) override final; void set_formatter(std::unique_ptr sink_formatter) override final; - private: - using mutex_t = typename ConsoleMutex::mutex_t; + using mutex_t = typename ConsoleMutex::mutex_t; HANDLE out_handle_; mutex_t &mutex_; std::unordered_map colors_; - // set color and return the orig console attributes (for resetting later) + // 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); diff --git a/include/spdlog/spdlog-inl.h b/include/spdlog/spdlog-inl.h new file mode 100644 index 00000000..e2cd60ac --- /dev/null +++ b/include/spdlog/spdlog-inl.h @@ -0,0 +1,96 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + +#include "spdlog/common.h" +#include "spdlog/details/pattern_formatter.h" + +namespace spdlog { + +SPDLOG_INLINE void initialize_logger(std::shared_ptr logger) +{ + details::registry::instance().initialize_logger(std::move(logger)); +} + +SPDLOG_INLINE std::shared_ptr get(const std::string &name) +{ + return details::registry::instance().get(name); +} + +SPDLOG_INLINE void set_formatter(std::unique_ptr 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(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) +{ + details::registry::instance().register_logger(std::move(logger)); +} + +SPDLOG_INLINE void apply_all(const std::function)> &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 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 default_logger) +{ + details::registry::instance().set_default_logger(std::move(default_logger)); +} + +} // namespace spdlog \ No newline at end of file diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index db67dba6..56a69e4c 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -11,7 +11,6 @@ #include "spdlog/common.h" #include "spdlog/details/registry.h" -#include "spdlog/details/pattern_formatter.h" #include "spdlog/logger.h" #include "spdlog/version.h" @@ -58,94 +57,52 @@ inline std::shared_ptr create(std::string logger_name, SinkArgs // auto console_sink = std::make_shared(); // auto console_logger = std::make_shared("console_logger", console_sink); // spdlog::initialize_logger(console_logger); -inline void initialize_logger(std::shared_ptr logger) -{ - details::registry::instance().initialize_logger(std::move(logger)); -} +void initialize_logger(std::shared_ptr logger); // Return an existing logger or nullptr if a logger with such name doesn't // exist. // example: spdlog::get("my_logger")->info("hello {}", "world"); -inline std::shared_ptr get(const std::string &name) -{ - return details::registry::instance().get(name); -} +std::shared_ptr get(const std::string &name); // Set global formatter. Each sink in each logger will get a clone of this object -inline void set_formatter(std::unique_ptr formatter) -{ - details::registry::instance().set_formatter(std::move(formatter)); -} +void set_formatter(std::unique_ptr formatter); // Set global format string. // 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) -{ - set_formatter(std::unique_ptr(new pattern_formatter(std::move(pattern), time_type))); -} +void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local); // Set global logging level -inline void set_level(level::level_enum log_level) -{ - details::registry::instance().set_level(log_level); -} +void set_level(level::level_enum log_level); // Set global flush level -inline void flush_on(level::level_enum log_level) -{ - details::registry::instance().flush_on(log_level); -} +void flush_on(level::level_enum log_level); // Start/Restart a periodic flusher thread // Warning: Use only if all your loggers are thread safe! -inline void flush_every(std::chrono::seconds interval) -{ - details::registry::instance().flush_every(interval); -} +void flush_every(std::chrono::seconds interval); // Set global error handler -inline void set_error_handler(void (*handler)(const std::string &msg)) -{ - details::registry::instance().set_error_handler(handler); -} +void set_error_handler(void (*handler)(const std::string &msg)); // Register the given logger with the given name -inline void register_logger(std::shared_ptr logger) -{ - details::registry::instance().register_logger(std::move(logger)); -} +void register_logger(std::shared_ptr logger); // Apply a user defined function on all registered loggers // Example: // spdlog::apply_all([&](std::shared_ptr l) {l->flush();}); -inline void apply_all(const std::function)> &fun) -{ - details::registry::instance().apply_all(fun); -} +void apply_all(const std::function)> &fun); // Drop the reference to the given logger -inline void drop(const std::string &name) -{ - details::registry::instance().drop(name); -} +void drop(const std::string &name); // Drop all references from the registry -inline void drop_all() -{ - details::registry::instance().drop_all(); -} +void drop_all(); // stop any running threads started by spdlog and clean registry loggers -inline void shutdown() -{ - details::registry::instance().shutdown(); -} +void shutdown(); // Automatic registration of loggers when using spdlog::create() or spdlog::create_async -inline void set_automatic_registration(bool automatic_registation) -{ - details::registry::instance().set_automatic_registration(automatic_registation); -} +void set_automatic_registration(bool automatic_registation); // API for using default logger (stdout_color_mt), // e.g: spdlog::info("Message {}", 1); @@ -162,20 +119,11 @@ inline void set_automatic_registration(bool automatic_registation) // 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. -inline std::shared_ptr default_logger() -{ - return details::registry::instance().default_logger(); -} +std::shared_ptr default_logger(); -inline spdlog::logger *default_logger_raw() -{ - return details::registry::instance().get_default_raw(); -} +spdlog::logger *default_logger_raw(); -inline void set_default_logger(std::shared_ptr default_logger) -{ - details::registry::instance().set_default_logger(std::move(default_logger)); -} +void set_default_logger(std::shared_ptr default_logger); template inline void log(source_loc source, level::level_enum lvl, const char *fmt, const Args &... args) @@ -382,4 +330,8 @@ inline void critical(const wchar_t *fmt, const Args &... args) #define SPDLOG_CRITICAL(...) (void)0 #endif +#ifdef SPDLOG_HEADER_ONLY +#include "spdlog-inl.h" +#endif + #endif // SPDLOG_H diff --git a/src/spdlog.cpp b/src/spdlog.cpp index d4e78ffc..fd321535 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -9,6 +9,8 @@ #include #include "spdlog/spdlog.h" +#include "spdlog/spdlog-inl.h" + #include "spdlog/async.h" #include "spdlog/common.h" From 26a064ed2d696f8632cd24a76487548f810f512c Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 12 May 2019 23:36:48 +0300 Subject: [PATCH 121/157] wip static-lib --- include/spdlog/sinks/basic_file_sink-inl.h | 39 ++++++++++++++++++++++ include/spdlog/sinks/basic_file_sink.h | 28 +++++----------- src/spdlog.cpp | 5 +++ tests/includes.h | 1 + 4 files changed, 53 insertions(+), 20 deletions(-) create mode 100644 include/spdlog/sinks/basic_file_sink-inl.h diff --git a/include/spdlog/sinks/basic_file_sink-inl.h b/include/spdlog/sinks/basic_file_sink-inl.h new file mode 100644 index 00000000..edcee4fa --- /dev/null +++ b/include/spdlog/sinks/basic_file_sink-inl.h @@ -0,0 +1,39 @@ +// Copyright(c) 2015-present Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + +#include "spdlog/common.h" +#include "spdlog/details/os.h" + +namespace spdlog { +namespace sinks { + +template +SPDLOG_INLINE basic_file_sink::basic_file_sink(const filename_t &filename, bool truncate) +{ + file_helper_.open(filename, truncate); +} + +template +SPDLOG_INLINE const filename_t &basic_file_sink::filename() const +{ + return file_helper_.filename(); +} + +template +SPDLOG_INLINE void basic_file_sink::sink_it_(const details::log_msg &msg) +{ + fmt::memory_buffer formatted; + sink::formatter_->format(msg, formatted); + file_helper_.write(formatted); +} + +template +SPDLOG_INLINE void basic_file_sink::flush_() +{ + file_helper_.flush(); +} + +} // namespace sinks +} // namespace spdlog diff --git a/include/spdlog/sinks/basic_file_sink.h b/include/spdlog/sinks/basic_file_sink.h index 249a6f31..95a7a336 100644 --- a/include/spdlog/sinks/basic_file_sink.h +++ b/include/spdlog/sinks/basic_file_sink.h @@ -23,28 +23,12 @@ template class basic_file_sink final : public base_sink { public: - explicit basic_file_sink(const filename_t &filename, bool truncate = false) - { - file_helper_.open(filename, truncate); - } - - const filename_t &filename() const - { - return file_helper_.filename(); - } + explicit basic_file_sink(const filename_t &filename, bool truncate = false); + const filename_t &filename() const; protected: - void sink_it_(const details::log_msg &msg) override - { - fmt::memory_buffer formatted; - sink::formatter_->format(msg, formatted); - file_helper_.write(formatted); - } - - void flush_() override - { - file_helper_.flush(); - } + void sink_it_(const details::log_msg &msg) override; + void flush_() override; private: details::file_helper file_helper_; @@ -71,3 +55,7 @@ inline std::shared_ptr basic_logger_st(const std::string &logger_name, c } } // namespace spdlog + +#ifdef SPDLOG_HEADER_ONLY +#include "basic_file_sink-inl.h" +#endif \ No newline at end of file diff --git a/src/spdlog.cpp b/src/spdlog.cpp index fd321535..ebe2fc9f 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -36,6 +36,11 @@ template spdlog::logger::logger(std::string name, sinks_init_list::iterator begi template class spdlog::sinks::base_sink; template class spdlog::sinks::base_sink; +#include "spdlog/sinks/basic_file_sink.h" +#include "spdlog/sinks/basic_file_sink-inl.h" +template class spdlog::sinks::basic_file_sink; +template class spdlog::sinks::basic_file_sink; + #include "spdlog/sinks/rotating_file_sink.h" #include "spdlog/sinks/rotating_file_sink-inl.h" template class spdlog::sinks::rotating_file_sink; diff --git a/tests/includes.h b/tests/includes.h index 26517922..85d4a1bd 100644 --- a/tests/includes.h +++ b/tests/includes.h @@ -20,3 +20,4 @@ #include "spdlog/sinks/ostream_sink.h" #include "spdlog/sinks/rotating_file_sink.h" #include "spdlog/sinks/stdout_color_sinks.h" +#include "spdlog/details/pattern_formatter.h" From 61e45974889afeace0ae4f705b6f14c304633966 Mon Sep 17 00:00:00 2001 From: gabime Date: Mon, 13 May 2019 00:02:55 +0300 Subject: [PATCH 122/157] Removed include of fmt_helper from thrad_pool.h --- include/spdlog/details/thread_pool.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/include/spdlog/details/thread_pool.h b/include/spdlog/details/thread_pool.h index 42761d7a..bf1b61e8 100644 --- a/include/spdlog/details/thread_pool.h +++ b/include/spdlog/details/thread_pool.h @@ -3,7 +3,6 @@ #pragma once -#include "spdlog/details/fmt_helper.h" #include "spdlog/details/log_msg.h" #include "spdlog/details/mpmc_blocking_q.h" #include "spdlog/details/os.h" @@ -86,7 +85,7 @@ struct async_msg , source(m.source) , 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) From ce637440bb51972284189fc894b958aedd61dd87 Mon Sep 17 00:00:00 2001 From: gabime Date: Mon, 13 May 2019 00:09:00 +0300 Subject: [PATCH 123/157] wip static-lib --- include/spdlog/async_logger-inl.h | 4 +++ include/spdlog/common-inl.h | 4 +++ include/spdlog/details/file_helper-inl.h | 4 +++ include/spdlog/details/log_msg-inl.h | 4 +++ include/spdlog/details/os-inl.h | 5 +++ .../spdlog/details/pattern_formatter-inl.h | 4 +++ include/spdlog/details/periodic_worker-inl.h | 6 ++++ include/spdlog/details/registry-inl.h | 4 +++ include/spdlog/details/thread_pool-inl.h | 4 +++ include/spdlog/logger-inl.h | 4 +++ include/spdlog/sinks/ansicolor_sink-inl.h | 4 +++ include/spdlog/sinks/base_sink-inl.h | 4 +++ include/spdlog/sinks/basic_file_sink-inl.h | 4 +++ include/spdlog/sinks/rotating_file_sink-inl.h | 4 +++ include/spdlog/sinks/sink-inl.h | 4 +++ include/spdlog/sinks/stdout_color_sinks-inl.h | 4 +++ include/spdlog/sinks/wincolor_sink-inl.h | 7 ++++ include/spdlog/spdlog-inl.h | 4 +++ src/spdlog.cpp | 34 ++----------------- tests/includes.h | 2 +- tests/test_fmt_helper.cpp | 1 + 21 files changed, 82 insertions(+), 33 deletions(-) diff --git a/include/spdlog/async_logger-inl.h b/include/spdlog/async_logger-inl.h index 027366c8..ce2e8d2b 100644 --- a/include/spdlog/async_logger-inl.h +++ b/include/spdlog/async_logger-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/async_logger.h" +#endif + #include "spdlog/sinks/sink.h" #include "spdlog/details/thread_pool.h" diff --git a/include/spdlog/common-inl.h b/include/spdlog/common-inl.h index dd619a57..6076b8cb 100644 --- a/include/spdlog/common-inl.h +++ b/include/spdlog/common-inl.h @@ -3,6 +3,10 @@ #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; diff --git a/include/spdlog/details/file_helper-inl.h b/include/spdlog/details/file_helper-inl.h index fef3be01..1460fc2b 100644 --- a/include/spdlog/details/file_helper-inl.h +++ b/include/spdlog/details/file_helper-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/details/file_helper.h" +#endif + #include "spdlog/details/os.h" #include diff --git a/include/spdlog/details/log_msg-inl.h b/include/spdlog/details/log_msg-inl.h index b619f7ce..0df717f9 100644 --- a/include/spdlog/details/log_msg-inl.h +++ b/include/spdlog/details/log_msg-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/details/log_msg.h" +#endif + #include "spdlog/details/os.h" #include "spdlog/sinks/sink.h" diff --git a/include/spdlog/details/os-inl.h b/include/spdlog/details/os-inl.h index cc4690d6..e96d1d38 100644 --- a/include/spdlog/details/os-inl.h +++ b/include/spdlog/details/os-inl.h @@ -2,6 +2,11 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once + +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/details/os.h" +#endif + #include #include #include diff --git a/include/spdlog/details/pattern_formatter-inl.h b/include/spdlog/details/pattern_formatter-inl.h index 9275d8ef..a6951e47 100644 --- a/include/spdlog/details/pattern_formatter-inl.h +++ b/include/spdlog/details/pattern_formatter-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/details/pattern_formatter.h" +#endif + #include "spdlog/details/fmt_helper.h" #include "spdlog/details/log_msg.h" #include "spdlog/details/os.h" diff --git a/include/spdlog/details/periodic_worker-inl.h b/include/spdlog/details/periodic_worker-inl.h index cfc9af72..f97ed4d1 100644 --- a/include/spdlog/details/periodic_worker-inl.h +++ b/include/spdlog/details/periodic_worker-inl.h @@ -2,8 +2,14 @@ // 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 &callback_fun, std::chrono::seconds interval) { active_ = (interval > std::chrono::seconds::zero()); diff --git a/include/spdlog/details/registry-inl.h b/include/spdlog/details/registry-inl.h index 168c4c54..9ea46237 100644 --- a/include/spdlog/details/registry-inl.h +++ b/include/spdlog/details/registry-inl.h @@ -3,6 +3,10 @@ #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" diff --git a/include/spdlog/details/thread_pool-inl.h b/include/spdlog/details/thread_pool-inl.h index a7b77437..61b94380 100644 --- a/include/spdlog/details/thread_pool-inl.h +++ b/include/spdlog/details/thread_pool-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/details/thread_pool.h" +#endif + #include "spdlog/common.h" namespace spdlog { diff --git a/include/spdlog/logger-inl.h b/include/spdlog/logger-inl.h index 4d0c5e24..374376be 100644 --- a/include/spdlog/logger-inl.h +++ b/include/spdlog/logger-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/logger.h" +#endif + #include "spdlog/sinks/sink.h" #include "spdlog/details/pattern_formatter.h" diff --git a/include/spdlog/sinks/ansicolor_sink-inl.h b/include/spdlog/sinks/ansicolor_sink-inl.h index 63da482e..7f7cd751 100644 --- a/include/spdlog/sinks/ansicolor_sink-inl.h +++ b/include/spdlog/sinks/ansicolor_sink-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/sinks/ansicolor_sink.h" +#endif + #include "spdlog/details/os.h" template diff --git a/include/spdlog/sinks/base_sink-inl.h b/include/spdlog/sinks/base_sink-inl.h index 177bbb69..4ee23439 100644 --- a/include/spdlog/sinks/base_sink-inl.h +++ b/include/spdlog/sinks/base_sink-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/sinks/base_sink.h" +#endif + #include "spdlog/common.h" #include "spdlog/details/pattern_formatter.h" diff --git a/include/spdlog/sinks/basic_file_sink-inl.h b/include/spdlog/sinks/basic_file_sink-inl.h index edcee4fa..254e5085 100644 --- a/include/spdlog/sinks/basic_file_sink-inl.h +++ b/include/spdlog/sinks/basic_file_sink-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/sinks/basic_file_sink.h" +#endif + #include "spdlog/common.h" #include "spdlog/details/os.h" diff --git a/include/spdlog/sinks/rotating_file_sink-inl.h b/include/spdlog/sinks/rotating_file_sink-inl.h index db13a738..f871c820 100644 --- a/include/spdlog/sinks/rotating_file_sink-inl.h +++ b/include/spdlog/sinks/rotating_file_sink-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/sinks/rotating_file_sink.h" +#endif + #include "spdlog/common.h" #include "spdlog/details/file_helper.h" diff --git a/include/spdlog/sinks/sink-inl.h b/include/spdlog/sinks/sink-inl.h index 8599795c..52227696 100644 --- a/include/spdlog/sinks/sink-inl.h +++ b/include/spdlog/sinks/sink-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/sinks/sink.h" +#endif + #include "spdlog/common.h" #include "spdlog/details/pattern_formatter.h" diff --git a/include/spdlog/sinks/stdout_color_sinks-inl.h b/include/spdlog/sinks/stdout_color_sinks-inl.h index 018aaf5e..d001a5fd 100644 --- a/include/spdlog/sinks/stdout_color_sinks-inl.h +++ b/include/spdlog/sinks/stdout_color_sinks-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/sinks/stdout_color_sinks.h" +#endif + #include "spdlog/logger.h" #include "spdlog/common.h" diff --git a/include/spdlog/sinks/wincolor_sink-inl.h b/include/spdlog/sinks/wincolor_sink-inl.h index da5262b3..912f2a6f 100644 --- a/include/spdlog/sinks/wincolor_sink-inl.h +++ b/include/spdlog/sinks/wincolor_sink-inl.h @@ -3,8 +3,15 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/sinks/wincolor_sink.h" +#endif + +#include "spdlog/common.h" + namespace spdlog { namespace sinks { + template SPDLOG_INLINE wincolor_sink::wincolor_sink() : out_handle_(TargetStream::handle()) diff --git a/include/spdlog/spdlog-inl.h b/include/spdlog/spdlog-inl.h index e2cd60ac..c8aa1c8e 100644 --- a/include/spdlog/spdlog-inl.h +++ b/include/spdlog/spdlog-inl.h @@ -3,6 +3,10 @@ #pragma once +#ifndef SPDLOG_HEADER_ONLY +#include "spdlog/spdlog.h" +#endif + #include "spdlog/common.h" #include "spdlog/details/pattern_formatter.h" diff --git a/src/spdlog.cpp b/src/spdlog.cpp index ebe2fc9f..d98458ca 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -8,72 +8,48 @@ #include #include -#include "spdlog/spdlog.h" -#include "spdlog/spdlog-inl.h" - +#include "spdlog/details/null_mutex.h" #include "spdlog/async.h" -#include "spdlog/common.h" +#include "spdlog/spdlog-inl.h" #include "spdlog/common-inl.h" -#include "spdlog/details/null_mutex.h" - -#include "spdlog/logger.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.h" #include "spdlog/async_logger-inl.h" - -#include "spdlog/details/log_msg.h" #include "spdlog/details/log_msg-inl.h" - -#include "spdlog/sinks/sink.h" #include "spdlog/sinks/sink-inl.h" -#include "spdlog/sinks/base_sink.h" #include "spdlog/sinks/base_sink-inl.h" template class spdlog::sinks::base_sink; template class spdlog::sinks::base_sink; -#include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/basic_file_sink-inl.h" template class spdlog::sinks::basic_file_sink; template class spdlog::sinks::basic_file_sink; -#include "spdlog/sinks/rotating_file_sink.h" #include "spdlog/sinks/rotating_file_sink-inl.h" template class spdlog::sinks::rotating_file_sink; template class spdlog::sinks::rotating_file_sink; -#include "spdlog/details/registry.h" #include "spdlog/details/registry-inl.h" -#include "spdlog/details/os.h" #include "spdlog/details/os-inl.h" - -#include "spdlog/details/periodic_worker.h" #include "spdlog/details/periodic_worker-inl.h" - -#include "spdlog/details/file_helper.h" #include "spdlog/details/file_helper-inl.h" - -#include "spdlog/details/pattern_formatter.h" #include "spdlog/details/pattern_formatter-inl.h" -#include "spdlog/details/thread_pool.h" #include "spdlog/details/thread_pool-inl.h" template class spdlog::details::mpmc_blocking_queue; #ifdef _WIN32 -#include "spdlog/sinks/wincolor_sink.h" #include "spdlog/sinks/wincolor_sink-inl.h" template class spdlog::sinks::wincolor_sink; template class spdlog::sinks::wincolor_sink; template class spdlog::sinks::wincolor_sink; template class spdlog::sinks::wincolor_sink; #else -#include "spdlog/sinks/ansicolor_sink.h" #include "spdlog/sinks/ansicolor_sink-inl.h" template class spdlog::sinks::ansicolor_sink; template class spdlog::sinks::ansicolor_sink; @@ -81,7 +57,6 @@ template class spdlog::sinks::ansicolor_sink; #endif -#include "spdlog/sinks/stdout_color_sinks.h" #include "spdlog/sinks/stdout_color_sinks-inl.h" template std::shared_ptr spdlog::stdout_color_mt(const std::string &logger_name); template std::shared_ptr spdlog::stdout_color_st(const std::string &logger_name); @@ -93,11 +68,6 @@ template std::shared_ptr spdlog::stdout_color_st spdlog::stderr_color_mt(const std::string &logger_name); template std::shared_ptr spdlog::stderr_color_st(const std::string &logger_name); -// fmt_helper templates -#include "spdlog/details/fmt_helper.h" -template void spdlog::details::fmt_helper::append_string_view(spdlog::string_view_t view, fmt::memory_buffer &dest); -template spdlog::string_view_t spdlog::details::fmt_helper::to_string_view(const fmt::memory_buffer &buf) SPDLOG_NOEXCEPT; - // Slightly modified version of fmt lib's format.cc source file. // Copyright (c) 2012 - 2016, Victor Zverovich // All rights reserved. diff --git a/tests/includes.h b/tests/includes.h index 85d4a1bd..4e0eaf8a 100644 --- a/tests/includes.h +++ b/tests/includes.h @@ -20,4 +20,4 @@ #include "spdlog/sinks/ostream_sink.h" #include "spdlog/sinks/rotating_file_sink.h" #include "spdlog/sinks/stdout_color_sinks.h" -#include "spdlog/details/pattern_formatter.h" +#include "spdlog/details/pattern_formatter.h" \ No newline at end of file diff --git a/tests/test_fmt_helper.cpp b/tests/test_fmt_helper.cpp index 97a61960..5af6f8a7 100644 --- a/tests/test_fmt_helper.cpp +++ b/tests/test_fmt_helper.cpp @@ -1,5 +1,6 @@ #include "includes.h" +#include "spdlog/details/fmt_helper.h" void test_pad2(int n, const char *expected) { From 32fb9d51b9f0a50216782b963851bd989953161d Mon Sep 17 00:00:00 2001 From: gabime Date: Mon, 13 May 2019 01:06:25 +0300 Subject: [PATCH 124/157] Cmake update to support both header-only and static --- CMakeLists.txt | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 017db67e..73fa9254 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,7 +45,6 @@ else() set(SPDLOG_MASTER_PROJECT OFF) endif() -option(SPDLOG_STATIC_LIB "Build as static lib" ON) 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" ON) @@ -55,29 +54,38 @@ option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include/spdlog") message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) -message(STATUS "Static lib: " ${SPDLOG_STATIC_LIB}) -if(SPDLOG_STATIC_LIB) - add_definitions(-DSPDLOG_STATIC_LIB) - set(SRC_BASE "${CMAKE_CURRENT_SOURCE_DIR}/src") - set(SRC_FILES "${SRC_BASE}/spdlog.cpp") - add_library(spdlog STATIC ${SRC_FILES}) - target_include_directories(spdlog PUBLIC "$") - target_link_libraries(spdlog) +# Build static lib +set(SRC_BASE "${CMAKE_CURRENT_SOURCE_DIR}/src") +set(STATIC_SRC_FILES "${SRC_BASE}/spdlog.cpp") +add_library(spdlog_static STATIC ${STATIC_SRC_FILES}) +add_library(spdlog::static ALIAS spdlog_static) + +if (CMAKE_BUILD_TYPE EQUAL "RELEASE") +set_target_properties(spdlog_static PROPERTIES OUTPUT_NAME "spdlog") else() - add_library(spdlog INTERFACE) - target_include_directories(spdlog INTERFACE "$") +set_target_properties(spdlog_static PROPERTIES OUTPUT_NAME "spdlog-debug") endif() -add_library(spdlog::spdlog ALIAS spdlog) + +target_compile_definitions(spdlog_static PUBLIC SPDLOG_STATIC_LIB ) +target_include_directories(spdlog_static PUBLIC "$") + +# headr only +add_library(spdlog_header_only INTERFACE) +target_include_directories(spdlog_header_only INTERFACE "$") +add_library(spdlog::spdlog ALIAS spdlog_header_only) if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) find_package(fmt REQUIRED CONFIG) endif() if(SPDLOG_FMT_EXTERNAL) - target_compile_definitions(spdlog INTERFACE SPDLOG_FMT_EXTERNAL) - target_link_libraries(spdlog INTERFACE fmt::fmt) + target_compile_definitions(spdlog_static INTERFACE SPDLOG_FMT_EXTERNAL) + target_link_libraries(spdlog_static INTERFACE fmt::fmt) + + target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_FMT_EXTERNAL) + target_link_libraries(spdlog_header_only INTERFACE fmt::fmt) endif() if(SPDLOG_BUILD_EXAMPLES) @@ -97,10 +105,8 @@ endif() # install #--------------------------------------------------------------------------------------- install(DIRECTORY ${HEADER_BASE} DESTINATION include) +install(TARGETS spdlog_static ARCHIVE DESTINATION lib) -if(SPDLOG_STATIC_LIB) - install(TARGETS spdlog ARCHIVE DESTINATION lib) -endif() #--------------------------------------------------------------------------------------- # register project in CMake user registry From 872ea6bf09eb25f85e32479d4c5f2d8ffe93904a Mon Sep 17 00:00:00 2001 From: gabime Date: Mon, 13 May 2019 01:13:58 +0300 Subject: [PATCH 125/157] Deleted redundant Make files and solutions --- CMakeLists.txt | 2 +- bench/CMakeLists.txt | 8 +- bench/Makefile | 31 ------- example/CMakeLists.txt | 6 +- example/Makefile | 21 ----- example/Makefile-all-warn | 22 ----- example/Makefile.clang | 26 ------ example/Makefile.mingw | 25 ------ example/example.sln | 106 ----------------------- example/example.vcxproj | 167 ------------------------------------ tests/CMakeLists.txt | 2 +- tests/Makefile | 22 ----- tests/tests.sln | 98 --------------------- tests/tests.vcxproj | 148 -------------------------------- tests/tests.vcxproj.filters | 60 ------------- tests/tests.vcxproj.user | 4 - 16 files changed, 9 insertions(+), 739 deletions(-) delete mode 100644 bench/Makefile delete mode 100644 example/Makefile delete mode 100644 example/Makefile-all-warn delete mode 100644 example/Makefile.clang delete mode 100644 example/Makefile.mingw delete mode 100644 example/example.sln delete mode 100644 example/example.vcxproj delete mode 100644 tests/Makefile delete mode 100644 tests/tests.sln delete mode 100644 tests/tests.vcxproj delete mode 100644 tests/tests.vcxproj.filters delete mode 100644 tests/tests.vcxproj.user diff --git a/CMakeLists.txt b/CMakeLists.txt index 73fa9254..7ed17e67 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -74,7 +74,7 @@ target_include_directories(spdlog_static PUBLIC "$") -add_library(spdlog::spdlog ALIAS spdlog_header_only) +add_library(spdlog::header_only ALIAS spdlog_header_only) if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) find_package(fmt REQUIRED CONFIG) diff --git a/bench/CMakeLists.txt b/bench/CMakeLists.txt index 3c4a3f9d..9280ebad 100644 --- a/bench/CMakeLists.txt +++ b/bench/CMakeLists.txt @@ -33,16 +33,16 @@ find_package(Threads REQUIRED) find_package(benchmark CONFIG REQUIRED) add_executable(bench bench.cpp) -target_link_libraries(bench PRIVATE spdlog::spdlog Threads::Threads) +target_link_libraries(bench PRIVATE spdlog::static Threads::Threads) add_executable(async_bench async_bench.cpp) -target_link_libraries(async_bench PRIVATE spdlog::spdlog Threads::Threads) +target_link_libraries(async_bench PRIVATE spdlog::static Threads::Threads) add_executable(latency latency.cpp) -target_link_libraries(latency PRIVATE benchmark::benchmark spdlog::spdlog Threads::Threads) +target_link_libraries(latency PRIVATE benchmark::benchmark spdlog::static Threads::Threads) 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::static Threads::Threads) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") diff --git a/bench/Makefile b/bench/Makefile deleted file mode 100644 index 868a7335..00000000 --- a/bench/Makefile +++ /dev/null @@ -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 diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index a404682a..f0a917f2 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -34,14 +34,14 @@ find_package(Threads REQUIRED) 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) + target_link_libraries(example spdlog::static Threads::Threads log) else() - target_link_libraries(example spdlog::spdlog Threads::Threads) + target_link_libraries(example spdlog::static Threads::Threads) endif() add_executable(multisink multisink.cpp) -target_link_libraries(multisink spdlog::spdlog Threads::Threads) +target_link_libraries(multisink spdlog::static Threads::Threads) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") diff --git a/example/Makefile b/example/Makefile deleted file mode 100644 index bd6b2922..00000000 --- a/example/Makefile +++ /dev/null @@ -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 diff --git a/example/Makefile-all-warn b/example/Makefile-all-warn deleted file mode 100644 index 2ba68e2a..00000000 --- a/example/Makefile-all-warn +++ /dev/null @@ -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 diff --git a/example/Makefile.clang b/example/Makefile.clang deleted file mode 100644 index 475855db..00000000 --- a/example/Makefile.clang +++ /dev/null @@ -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 - - diff --git a/example/Makefile.mingw b/example/Makefile.mingw deleted file mode 100644 index 247a818b..00000000 --- a/example/Makefile.mingw +++ /dev/null @@ -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 - - diff --git a/example/example.sln b/example/example.sln deleted file mode 100644 index b29a9e47..00000000 --- a/example/example.sln +++ /dev/null @@ -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 diff --git a/example/example.vcxproj b/example/example.vcxproj deleted file mode 100644 index c752a8e9..00000000 --- a/example/example.vcxproj +++ /dev/null @@ -1,167 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - - - - {9E5AB93A-0CCE-4BAC-9FCB-0FC9CB5EB8D2} - Win32Proj - . - - - - Application - true - v141 - Unicode - - - Application - true - v141 - Unicode - - - Application - false - v141 - true - Unicode - - - Application - false - v141 - true - Unicode - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) - ..\include;%(AdditionalIncludeDirectories) - - - - - Console - true - - - - - - - Level3 - Disabled - WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) - ..\include;%(AdditionalIncludeDirectories) - - - - - - - Console - true - - - - - Level3 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) - ..\include;%(AdditionalIncludeDirectories) - - - - - Console - true - true - true - %(AdditionalLibraryDirectories) - %(AdditionalDependencies) - - - - - Level3 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) - ..\include;%(AdditionalIncludeDirectories) - - - - - - - Console - true - true - true - %(AdditionalLibraryDirectories) - %(AdditionalDependencies) - - - - - - \ No newline at end of file diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 48f80e0e..2950f99e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -21,7 +21,7 @@ set(SPDLOG_UTESTS_SOURCES add_executable(${PROJECT_NAME} ${SPDLOG_UTESTS_SOURCES}) target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) -target_link_libraries(${PROJECT_NAME} PRIVATE spdlog::spdlog) +target_link_libraries(${PROJECT_NAME} PRIVATE spdlog::static) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") diff --git a/tests/Makefile b/tests/Makefile deleted file mode 100644 index c9ce3c01..00000000 --- a/tests/Makefile +++ /dev/null @@ -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 - - - diff --git a/tests/tests.sln b/tests/tests.sln deleted file mode 100644 index 511c99c8..00000000 --- a/tests/tests.sln +++ /dev/null @@ -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 diff --git a/tests/tests.vcxproj b/tests/tests.vcxproj deleted file mode 100644 index a246fd21..00000000 --- a/tests/tests.vcxproj +++ /dev/null @@ -1,148 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {59A07559-5F38-4DD6-A7FA-DB4153690B42} - tests - 10.0.16299.0 - - - - Application - true - v141 - MultiByte - - - Application - true - v141 - MultiByte - - - Application - false - v141 - true - MultiByte - - - Application - false - v141 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - $(SolutionDir)\..\include;%(AdditionalIncludeDirectories) - - - true - Console - - - - - Level3 - Disabled - true - _MBCS;%(PreprocessorDefinitions) - $(SolutionDir)..\include;%(AdditionalIncludeDirectories) - - - true - Console - - - - - Level3 - MaxSpeed - true - true - true - $(SolutionDir)\..\include;%(AdditionalIncludeDirectories) - - - true - true - true - Console - - - - - Level3 - MaxSpeed - true - true - true - _MBCS;%(PreprocessorDefinitions) - $(SolutionDir)..\include;%(AdditionalIncludeDirectories) - - - true - true - true - Console - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/tests.vcxproj.filters b/tests/tests.vcxproj.filters deleted file mode 100644 index c70cc496..00000000 --- a/tests/tests.vcxproj.filters +++ /dev/null @@ -1,60 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - \ No newline at end of file diff --git a/tests/tests.vcxproj.user b/tests/tests.vcxproj.user deleted file mode 100644 index be250787..00000000 --- a/tests/tests.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file From b3fe4b54c82ca11367789615eca7b2616e6abd58 Mon Sep 17 00:00:00 2001 From: gabime Date: Mon, 13 May 2019 01:28:06 +0300 Subject: [PATCH 126/157] Fixed CMakeLists.txt --- CMakeLists.txt | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7ed17e67..1ed6a21b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,18 +60,12 @@ set(SRC_BASE "${CMAKE_CURRENT_SOURCE_DIR}/src") set(STATIC_SRC_FILES "${SRC_BASE}/spdlog.cpp") add_library(spdlog_static STATIC ${STATIC_SRC_FILES}) add_library(spdlog::static ALIAS spdlog_static) - -if (CMAKE_BUILD_TYPE EQUAL "RELEASE") -set_target_properties(spdlog_static PROPERTIES OUTPUT_NAME "spdlog") -else() -set_target_properties(spdlog_static PROPERTIES OUTPUT_NAME "spdlog-debug") -endif() - - target_compile_definitions(spdlog_static PUBLIC SPDLOG_STATIC_LIB ) target_include_directories(spdlog_static PUBLIC "$") +set_target_properties(spdlog_static PROPERTIES OUTPUT_NAME "spdlog") +set_target_properties(spdlog_static PROPERTIES DEBUG_POSTFIX "-debug") -# headr only +# Headr only add_library(spdlog_header_only INTERFACE) target_include_directories(spdlog_header_only INTERFACE "$") add_library(spdlog::header_only ALIAS spdlog_header_only) @@ -83,7 +77,6 @@ endif() if(SPDLOG_FMT_EXTERNAL) target_compile_definitions(spdlog_static INTERFACE SPDLOG_FMT_EXTERNAL) target_link_libraries(spdlog_static INTERFACE fmt::fmt) - target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_FMT_EXTERNAL) target_link_libraries(spdlog_header_only INTERFACE fmt::fmt) endif() @@ -107,7 +100,6 @@ endif() install(DIRECTORY ${HEADER_BASE} DESTINATION include) install(TARGETS spdlog_static ARCHIVE DESTINATION lib) - #--------------------------------------------------------------------------------------- # register project in CMake user registry #--------------------------------------------------------------------------------------- From a9aee1c5b384e5a3e2a9efbd3b8cec8afbd7bc6f Mon Sep 17 00:00:00 2001 From: David Zemon Date: Fri, 17 May 2019 23:02:39 -0500 Subject: [PATCH 127/157] Disable automatic handling of line endings --- .gitattributes | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..fe505b27 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=false From dbcbeb7a571e50446e7eef5b36e47911b229ac9f Mon Sep 17 00:00:00 2001 From: David Zemon Date: Fri, 17 May 2019 23:05:48 -0500 Subject: [PATCH 128/157] Ignore CLion's default build directories --- .gitignore | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index b1a41919..fafa874a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ # Auto generated files -build/* +build/* *.slo *.lo *.o @@ -65,4 +65,5 @@ install_manifest.txt /tests/logs/* # idea -.idea/ \ No newline at end of file +.idea/ +cmake-build-*/ From 8dd85285e7a87a1a7347f3d6b4d409e4eed44eb6 Mon Sep 17 00:00:00 2001 From: David Zemon Date: Fri, 17 May 2019 23:09:22 -0500 Subject: [PATCH 129/157] Allow user to choose between static or shared library --- CMakeLists.txt | 23 +++++++++++------------ bench/CMakeLists.txt | 8 ++++---- example/CMakeLists.txt | 8 ++++---- include/spdlog/common.h | 4 ++-- include/spdlog/sinks/base_sink.h | 4 ++-- src/spdlog.cpp | 6 +++--- tests/CMakeLists.txt | 2 +- 7 files changed, 27 insertions(+), 28 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1ed6a21b..042ac7a7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,6 +45,7 @@ else() set(SPDLOG_MASTER_PROJECT OFF) endif() +option(BUILD_SHARED_LIBS "Global flag to cause add_library to create shared libraries if on." ON) 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" ON) @@ -55,15 +56,13 @@ set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include/spdlog") message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) -# Build static lib -set(SRC_BASE "${CMAKE_CURRENT_SOURCE_DIR}/src") -set(STATIC_SRC_FILES "${SRC_BASE}/spdlog.cpp") -add_library(spdlog_static STATIC ${STATIC_SRC_FILES}) -add_library(spdlog::static ALIAS spdlog_static) -target_compile_definitions(spdlog_static PUBLIC SPDLOG_STATIC_LIB ) -target_include_directories(spdlog_static PUBLIC "$") -set_target_properties(spdlog_static PROPERTIES OUTPUT_NAME "spdlog") -set_target_properties(spdlog_static PROPERTIES DEBUG_POSTFIX "-debug") +# Build library +add_library(spdlog src/spdlog.cpp) +add_library(spdlog::spdlog ALIAS spdlog) +target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB ) +target_include_directories(spdlog PUBLIC "$") +set_target_properties(spdlog PROPERTIES OUTPUT_NAME "spdlog") +set_target_properties(spdlog PROPERTIES DEBUG_POSTFIX "-debug") # Headr only add_library(spdlog_header_only INTERFACE) @@ -75,8 +74,8 @@ if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) endif() if(SPDLOG_FMT_EXTERNAL) - target_compile_definitions(spdlog_static INTERFACE SPDLOG_FMT_EXTERNAL) - target_link_libraries(spdlog_static INTERFACE fmt::fmt) + target_compile_definitions(spdlog INTERFACE SPDLOG_FMT_EXTERNAL) + target_link_libraries(spdlog INTERFACE fmt::fmt) target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_FMT_EXTERNAL) target_link_libraries(spdlog_header_only INTERFACE fmt::fmt) endif() @@ -98,7 +97,7 @@ endif() # install #--------------------------------------------------------------------------------------- install(DIRECTORY ${HEADER_BASE} DESTINATION include) -install(TARGETS spdlog_static ARCHIVE DESTINATION lib) +install(TARGETS spdlog DESTINATION lib) #--------------------------------------------------------------------------------------- # register project in CMake user registry diff --git a/bench/CMakeLists.txt b/bench/CMakeLists.txt index 9280ebad..3c4a3f9d 100644 --- a/bench/CMakeLists.txt +++ b/bench/CMakeLists.txt @@ -33,16 +33,16 @@ find_package(Threads REQUIRED) find_package(benchmark CONFIG REQUIRED) add_executable(bench bench.cpp) -target_link_libraries(bench PRIVATE spdlog::static Threads::Threads) +target_link_libraries(bench PRIVATE spdlog::spdlog Threads::Threads) add_executable(async_bench async_bench.cpp) -target_link_libraries(async_bench PRIVATE spdlog::static Threads::Threads) +target_link_libraries(async_bench PRIVATE spdlog::spdlog Threads::Threads) add_executable(latency latency.cpp) -target_link_libraries(latency PRIVATE benchmark::benchmark spdlog::static Threads::Threads) +target_link_libraries(latency PRIVATE benchmark::benchmark spdlog::spdlog Threads::Threads) add_executable(formatter-bench formatter-bench.cpp) -target_link_libraries(formatter-bench PRIVATE benchmark::benchmark spdlog::static Threads::Threads) +target_link_libraries(formatter-bench PRIVATE benchmark::benchmark spdlog::spdlog Threads::Threads) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index f0a917f2..98bdca6e 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -24,7 +24,7 @@ cmake_minimum_required(VERSION 3.1) project(SpdlogExamples CXX) -if(NOT TARGET spdlog) +if(NOT TARGET spdlog::spdlog) # Stand-alone build find_package(spdlog CONFIG REQUIRED) endif() @@ -34,14 +34,14 @@ find_package(Threads REQUIRED) add_executable(example example.cpp) if(CMAKE_SYSTEM_NAME STREQUAL "Android") find_library(log-lib log) - target_link_libraries(example spdlog::static Threads::Threads log) + target_link_libraries(example spdlog::spdlog Threads::Threads log) else() - target_link_libraries(example spdlog::static Threads::Threads) + target_link_libraries(example spdlog::spdlog Threads::Threads) endif() add_executable(multisink multisink.cpp) -target_link_libraries(multisink spdlog::static Threads::Threads) +target_link_libraries(multisink spdlog::spdlog Threads::Threads) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 819f3abb..ccc1d990 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -19,7 +19,7 @@ #include #endif -#ifdef SPDLOG_STATIC_LIB +#ifdef SPDLOG_COMPILED_LIB #undef SPDLOG_HEADER_ONLY #define SPDLOG_INLINE #else @@ -216,4 +216,4 @@ std::unique_ptr make_unique(Args &&... args) #ifdef SPDLOG_HEADER_ONLY #include "common-inl.h" -#endif \ No newline at end of file +#endif diff --git a/include/spdlog/sinks/base_sink.h b/include/spdlog/sinks/base_sink.h index 2ecf11b1..c9f5670e 100644 --- a/include/spdlog/sinks/base_sink.h +++ b/include/spdlog/sinks/base_sink.h @@ -37,6 +37,6 @@ protected: } // namespace sinks } // namespace spdlog -#ifndef SPDLOG_STATIC_LIB +#ifndef SPDLOG_COMPILED_LIB #include "base_sink-inl.h" -#endif \ No newline at end of file +#endif diff --git a/src/spdlog.cpp b/src/spdlog.cpp index d98458ca..d51c6186 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -1,8 +1,8 @@ // Copyright(c) 2015-present Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -#ifndef SPDLOG_STATIC_LIB -#error Please define SPDLOG_STATIC_LIB to compile this file. +#ifndef SPDLOG_COMPILED_LIB +#error Please define SPDLOG_COMPILED_LIB to compile this file. #endif #include @@ -100,4 +100,4 @@ template FMT_API int internal::char_traits::format_float(wchar_t *, std template FMT_API std::wstring internal::vformat(wstring_view, basic_format_args); FMT_END_NAMESPACE -#endif \ No newline at end of file +#endif diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2950f99e..48f80e0e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -21,7 +21,7 @@ set(SPDLOG_UTESTS_SOURCES add_executable(${PROJECT_NAME} ${SPDLOG_UTESTS_SOURCES}) target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) -target_link_libraries(${PROJECT_NAME} PRIVATE spdlog::static) +target_link_libraries(${PROJECT_NAME} PRIVATE spdlog::spdlog) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") From 55e7844ca079c31d798aeb77339df404fcc1626a Mon Sep 17 00:00:00 2001 From: David Zemon Date: Fri, 17 May 2019 23:15:08 -0500 Subject: [PATCH 130/157] Remove the namespaced Namespaces are good for avoiding collisions, but since the non-namespaced targets still exist, it does no good to add the namespaced targets on top. --- CMakeLists.txt | 2 -- example/CMakeLists.txt | 11 ++++++++--- tests/CMakeLists.txt | 2 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 042ac7a7..c939248b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,7 +58,6 @@ message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) # Build library add_library(spdlog src/spdlog.cpp) -add_library(spdlog::spdlog ALIAS spdlog) target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB ) target_include_directories(spdlog PUBLIC "$") set_target_properties(spdlog PROPERTIES OUTPUT_NAME "spdlog") @@ -67,7 +66,6 @@ set_target_properties(spdlog PROPERTIES DEBUG_POSTFIX "-debug") # Headr only add_library(spdlog_header_only INTERFACE) target_include_directories(spdlog_header_only INTERFACE "$") -add_library(spdlog::header_only ALIAS spdlog_header_only) if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) find_package(fmt REQUIRED CONFIG) diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index 98bdca6e..9dc977e7 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -24,9 +24,14 @@ cmake_minimum_required(VERSION 3.1) project(SpdlogExamples CXX) -if(NOT TARGET spdlog::spdlog) - # Stand-alone build - find_package(spdlog CONFIG REQUIRED) +if(TARGET spdlog) + # If we're running this example as part of the primary spdlog applciation + # then add an alias. This allows us to use the same "spdlog::spdlog" + # below that a user would use (with the namespace) + add_library(spdlog::spdlog ALIAS spdlog) +else() + # Stand-alone build + find_package(spdlog REQUIRED) endif() find_package(Threads REQUIRED) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 48f80e0e..8679174d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -21,7 +21,7 @@ set(SPDLOG_UTESTS_SOURCES add_executable(${PROJECT_NAME} ${SPDLOG_UTESTS_SOURCES}) target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) -target_link_libraries(${PROJECT_NAME} PRIVATE spdlog::spdlog) +target_link_libraries(${PROJECT_NAME} PRIVATE spdlog) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") From b021be29e56a6b539c067a247904d54d051ca492 Mon Sep 17 00:00:00 2001 From: David Zemon Date: Fri, 17 May 2019 23:17:46 -0500 Subject: [PATCH 131/157] Add support for .tar.gz and .zip packages via CPack --- CMakeLists.txt | 26 ++++++++++++++++++++------ SpdlogCPack.cmake | 26 ++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) create mode 100644 SpdlogCPack.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index c939248b..b1971b26 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -91,13 +91,27 @@ if(SPDLOG_BUILD_BENCH) add_subdirectory(bench) endif() -#--------------------------------------------------------------------------------------- -# install -#--------------------------------------------------------------------------------------- -install(DIRECTORY ${HEADER_BASE} DESTINATION include) -install(TARGETS spdlog DESTINATION lib) +if (SPDLOG_INSTALL) + #--------------------------------------------------------------------------------------- + # install + #--------------------------------------------------------------------------------------- + install(DIRECTORY include/ DESTINATION include) + install(TARGETS spdlog EXPORT ${PROJECT_NAME} DESTINATION lib) + install(EXPORT ${PROJECT_NAME} + DESTINATION lib/${PROJECT_NAME}/cmake + NAMESPACE ${PROJECT_NAME}:: + FILE ${PROJECT_NAME}Config.cmake + ) + + #--------------------------------------------------------------------------------------- + # Support creation of installable packages + #--------------------------------------------------------------------------------------- + include(SpdlogCPack.cmake) +endif () #--------------------------------------------------------------------------------------- -# register project in CMake user registry +# register project in CMake user registry - disabled by default since the +# installed/packaged version of the project is preferred. #--------------------------------------------------------------------------------------- +option(CMAKE_EXPORT_NO_PACKAGE_REGISTRY "Disable registration of CMake's build directory." ON) export(PACKAGE ${PROJECT_NAME}) diff --git a/SpdlogCPack.cmake b/SpdlogCPack.cmake new file mode 100644 index 00000000..432503cb --- /dev/null +++ b/SpdlogCPack.cmake @@ -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 ") +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) From 107fe0a14231587a03921a22300fb988e0a9ebe0 Mon Sep 17 00:00:00 2001 From: David Zemon Date: Fri, 17 May 2019 23:20:30 -0500 Subject: [PATCH 132/157] Ensure header_only library works by adding another example exe --- example/CMakeLists.txt | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index 9dc977e7..b25ca252 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -36,14 +36,22 @@ endif() find_package(Threads REQUIRED) +# Example of using pre-compiled library add_executable(example example.cpp) +target_link_libraries(example spdlog::spdlog Threads::Threads) if(CMAKE_SYSTEM_NAME STREQUAL "Android") find_library(log-lib log) - target_link_libraries(example spdlog::spdlog Threads::Threads log) -else() - target_link_libraries(example spdlog::spdlog Threads::Threads) + target_link_libraries(example log) endif() +# Example of using header-only library +add_executable(example_header_only example.cpp) +get_target_property(SPDLOG_INCLUDE_DIRS spdlog::spdlog INTERFACE_INCLUDE_DIRECTORIES) +target_include_directories(example_header_only PRIVATE ${SPDLOG_INCLUDE_DIRS}) +target_link_libraries(example_header_only Threads::Threads) +if(CMAKE_SYSTEM_NAME STREQUAL "Android") + target_link_libraries(example_header_only log) +endif () add_executable(multisink multisink.cpp) target_link_libraries(multisink spdlog::spdlog Threads::Threads) @@ -52,3 +60,4 @@ file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") enable_testing() add_test(NAME example COMMAND example) +add_test(NAME example_header_only COMMAND example) From 6fe899af104930c381b8bb0498e93b7a09418241 Mon Sep 17 00:00:00 2001 From: David Zemon Date: Fri, 17 May 2019 23:23:51 -0500 Subject: [PATCH 133/157] Set Threads::Threads dependency on spdlog libs - don't make user do it --- CMakeLists.txt | 20 +++++++++++++------- bench/CMakeLists.txt | 8 ++++---- example/CMakeLists.txt | 4 ++-- tests/CMakeLists.txt | 1 - 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b1971b26..2ef3b16f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,24 +56,30 @@ set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include/spdlog") message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) +find_package(Threads REQUIRED) + # Build library add_library(spdlog src/spdlog.cpp) target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB ) target_include_directories(spdlog PUBLIC "$") set_target_properties(spdlog PROPERTIES OUTPUT_NAME "spdlog") set_target_properties(spdlog PROPERTIES DEBUG_POSTFIX "-debug") +target_link_libraries(spdlog PUBLIC Threads::Threads) -# Headr only +# Header only add_library(spdlog_header_only INTERFACE) -target_include_directories(spdlog_header_only INTERFACE "$") +target_include_directories(spdlog_header_only INTERFACE "${CMAKE_CURRENT_LIST_DIR}/include") +target_link_libraries(spdlog_header_only INTERFACE Threads::Threads) -if(SPDLOG_FMT_EXTERNAL AND NOT TARGET fmt::fmt) - find_package(fmt REQUIRED CONFIG) -endif() if(SPDLOG_FMT_EXTERNAL) - target_compile_definitions(spdlog INTERFACE SPDLOG_FMT_EXTERNAL) - target_link_libraries(spdlog INTERFACE fmt::fmt) + 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() diff --git a/bench/CMakeLists.txt b/bench/CMakeLists.txt index 3c4a3f9d..dcb03a9e 100644 --- a/bench/CMakeLists.txt +++ b/bench/CMakeLists.txt @@ -33,16 +33,16 @@ find_package(Threads REQUIRED) find_package(benchmark CONFIG REQUIRED) 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) -target_link_libraries(async_bench PRIVATE spdlog::spdlog Threads::Threads) +target_link_libraries(async_bench PRIVATE spdlog::spdlog) 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) -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") diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index b25ca252..033e7af6 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -38,7 +38,7 @@ find_package(Threads REQUIRED) # Example of using pre-compiled library add_executable(example example.cpp) -target_link_libraries(example spdlog::spdlog Threads::Threads) +target_link_libraries(example spdlog::spdlog) if(CMAKE_SYSTEM_NAME STREQUAL "Android") find_library(log-lib log) target_link_libraries(example log) @@ -54,7 +54,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Android") endif () add_executable(multisink multisink.cpp) -target_link_libraries(multisink spdlog::spdlog Threads::Threads) +target_link_libraries(multisink spdlog::spdlog) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8679174d..f02dea91 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -20,7 +20,6 @@ set(SPDLOG_UTESTS_SOURCES test_fmt_helper.cpp) add_executable(${PROJECT_NAME} ${SPDLOG_UTESTS_SOURCES}) -target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) target_link_libraries(${PROJECT_NAME} PRIVATE spdlog) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") From 24e4f0aa872d1fb600520fcf9f57bb9a9cfcfbb7 Mon Sep 17 00:00:00 2001 From: David Zemon Date: Fri, 17 May 2019 23:31:30 -0500 Subject: [PATCH 134/157] Allowed overriding of `SPDLOG_MASTER_PROJECT` to better support Conan --- CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2ef3b16f..ba146ca1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -38,12 +38,14 @@ include(cmake/sanitizers.cmake) # spdlog target #--------------------------------------------------------------------------------------- -# Check if spdlog is being used directly or via add_subdirectory +# Check if spdlog is being used directly or via add_subdirectory, but allow overriding +if (NOT DEFINED SPDLOG_MASTER_PROJECT) if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) set(SPDLOG_MASTER_PROJECT ON) else() set(SPDLOG_MASTER_PROJECT OFF) endif() +endif () option(BUILD_SHARED_LIBS "Global flag to cause add_library to create shared libraries if on." ON) option(SPDLOG_BUILD_EXAMPLES "Build examples" ${SPDLOG_MASTER_PROJECT}) From dd2f293f339afa0a5a3637c7c4c890b43a76e12b Mon Sep 17 00:00:00 2001 From: David Zemon Date: Fri, 17 May 2019 23:33:44 -0500 Subject: [PATCH 135/157] Clean up CMake a bit more --- CMakeLists.txt | 9 ++++----- tests/CMakeLists.txt | 10 +++------- 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ba146ca1..a8e2f2ea 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,8 +54,6 @@ option(SPDLOG_BUILD_TESTS "Build tests" ON) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) -set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include/spdlog") - message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) find_package(Threads REQUIRED) @@ -63,9 +61,10 @@ find_package(Threads REQUIRED) # Build library add_library(spdlog src/spdlog.cpp) target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB ) -target_include_directories(spdlog PUBLIC "$") -set_target_properties(spdlog PROPERTIES OUTPUT_NAME "spdlog") -set_target_properties(spdlog PROPERTIES DEBUG_POSTFIX "-debug") +target_include_directories(spdlog PUBLIC + "$" + "$" +) target_link_libraries(spdlog PUBLIC Threads::Threads) # Header only diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f02dea91..3275694a 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,7 +1,3 @@ -project(spdlog-utests CXX) - -find_package(Threads REQUIRED) - set(SPDLOG_UTESTS_SOURCES test_errors.cpp test_file_helper.cpp @@ -19,10 +15,10 @@ set(SPDLOG_UTESTS_SOURCES test_sink.h test_fmt_helper.cpp) -add_executable(${PROJECT_NAME} ${SPDLOG_UTESTS_SOURCES}) -target_link_libraries(${PROJECT_NAME} PRIVATE spdlog) +add_executable(spdlog-utests ${SPDLOG_UTESTS_SOURCES}) +target_link_libraries(spdlog-utests spdlog) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") enable_testing() -add_test(NAME ${PROJECT_NAME} COMMAND ${PROJECT_NAME}) +add_test(NAME spdlog-utests COMMAND spdlog-utests) From 87eb569929c2502a7706478b5c7ae642757080b5 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 19 May 2019 15:47:49 +0300 Subject: [PATCH 136/157] More updates to CMake (version support , cmake.in) --- CMakeLists.txt | 71 ++++++++++++++------ cmake/Config.cmake.in | 31 --------- SpdlogCPack.cmake => cmake/SpdlogCPack.cmake | 0 cmake/spdlog.pc.in | 6 -- cmake/spdlogConfig.cmake.in | 15 +++++ example/CMakeLists.txt | 4 +- example/logs/.gitignore | 1 - 7 files changed, 69 insertions(+), 59 deletions(-) delete mode 100644 cmake/Config.cmake.in rename SpdlogCPack.cmake => cmake/SpdlogCPack.cmake (100%) delete mode 100644 cmake/spdlog.pc.in create mode 100644 cmake/spdlogConfig.cmake.in delete mode 100644 example/logs/.gitignore diff --git a/CMakeLists.txt b/CMakeLists.txt index a8e2f2ea..57307b15 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -29,15 +29,13 @@ if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCH add_compile_options("-Wfatal-errors") endif() -#--------------------------------------------------------------------------------------- -# address sanitizers check -#--------------------------------------------------------------------------------------- -include(cmake/sanitizers.cmake) + #--------------------------------------------------------------------------------------- # spdlog target #--------------------------------------------------------------------------------------- + # 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) @@ -47,10 +45,9 @@ else() endif() endif () -option(BUILD_SHARED_LIBS "Global flag to cause add_library to create shared libraries if on." ON) 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" ON) +option(SPDLOG_BUILD_TESTS "Build tests" OFF) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) @@ -60,11 +57,12 @@ find_package(Threads REQUIRED) # Build library add_library(spdlog src/spdlog.cpp) -target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB ) +target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB) target_include_directories(spdlog PUBLIC "$" "$" ) + target_link_libraries(spdlog PUBLIC Threads::Threads) # Header only @@ -73,6 +71,16 @@ target_include_directories(spdlog_header_only INTERFACE "${CMAKE_CURRENT_LIST_DI target_link_libraries(spdlog_header_only INTERFACE Threads::Threads) +#--------------------------------------------------------------------------------------- +# address sanitizers check +#--------------------------------------------------------------------------------------- +if(SPDLOG_MASTER_PROJECT) + include(cmake/sanitizers.cmake) +endif() + +#--------------------------------------------------------------------------------------- +# use fmt package if using exertnal fmt +#--------------------------------------------------------------------------------------- if(SPDLOG_FMT_EXTERNAL) if (NOT TARGET fmt::fmt) find_package(fmt REQUIRED) @@ -85,6 +93,9 @@ if(SPDLOG_FMT_EXTERNAL) target_link_libraries(spdlog_header_only INTERFACE fmt::fmt) endif() +#--------------------------------------------------------------------------------------- +# build binries +#--------------------------------------------------------------------------------------- if(SPDLOG_BUILD_EXAMPLES) add_subdirectory(example) endif() @@ -98,27 +109,49 @@ if(SPDLOG_BUILD_BENCH) add_subdirectory(bench) endif() +#--------------------------------------------------------------------------------------- +# install +#--------------------------------------------------------------------------------------- if (SPDLOG_INSTALL) + set(project_config_in "${CMAKE_CURRENT_LIST_DIR}/cmake/${PROJECT_NAME}Config.cmake.in") + set(project_config_out "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake") + set(config_targets_file "${PROJECT_NAME}ConfigTargets.cmake") + set(version_config_file "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake") + set(dest_dir lib/${PROJECT_NAME}/cmake) + #--------------------------------------------------------------------------------------- - # install + # lib in include files #--------------------------------------------------------------------------------------- install(DIRECTORY include/ DESTINATION include) install(TARGETS spdlog EXPORT ${PROJECT_NAME} DESTINATION lib) + + #--------------------------------------------------------------------------------------- + # package and version files + #--------------------------------------------------------------------------------------- install(EXPORT ${PROJECT_NAME} - DESTINATION lib/${PROJECT_NAME}/cmake - NAMESPACE ${PROJECT_NAME}:: - FILE ${PROJECT_NAME}Config.cmake - ) + DESTINATION ${dest_dir} + NAMESPACE ${PROJECT_NAME}:: + FILE ${config_targets_file}) + + include(CMakePackageConfigHelpers) + configure_file("${project_config_in}" "${project_config_out}" @ONLY) + write_basic_package_version_file("${version_config_file}" COMPATIBILITY SameMajorVersion) + install(FILES + "${project_config_out}" + "${version_config_file}" DESTINATION "${dest_dir}") #--------------------------------------------------------------------------------------- # Support creation of installable packages #--------------------------------------------------------------------------------------- - include(SpdlogCPack.cmake) + include(cmake/SpdlogCPack.cmake) + + #--------------------------------------------------------------------------------------- + # register project in CMake user registry - disabled by default since the + # installed/packaged version of the project is preferred. + #--------------------------------------------------------------------------------------- + option(CMAKE_EXPORT_NO_PACKAGE_REGISTRY "Disable registration of CMake's build directory." ON) + export(PACKAGE ${PROJECT_NAME}) + endif () -#--------------------------------------------------------------------------------------- -# register project in CMake user registry - disabled by default since the -# installed/packaged version of the project is preferred. -#--------------------------------------------------------------------------------------- -option(CMAKE_EXPORT_NO_PACKAGE_REGISTRY "Disable registration of CMake's build directory." ON) -export(PACKAGE ${PROJECT_NAME}) + diff --git a/cmake/Config.cmake.in b/cmake/Config.cmake.in deleted file mode 100644 index 0b0fd119..00000000 --- a/cmake/Config.cmake.in +++ /dev/null @@ -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() diff --git a/SpdlogCPack.cmake b/cmake/SpdlogCPack.cmake similarity index 100% rename from SpdlogCPack.cmake rename to cmake/SpdlogCPack.cmake diff --git a/cmake/spdlog.pc.in b/cmake/spdlog.pc.in deleted file mode 100644 index 262248a7..00000000 --- a/cmake/spdlog.pc.in +++ /dev/null @@ -1,6 +0,0 @@ -prefix=@CMAKE_INSTALL_PREFIX@ -includedir=${prefix}/include - -Name: @PROJECT_NAME@ -Description: Super fast C++ logging library. -Version: @PROJECT_VERSION@ diff --git a/cmake/spdlogConfig.cmake.in b/cmake/spdlogConfig.cmake.in new file mode 100644 index 00000000..43ffcf7e --- /dev/null +++ b/cmake/spdlogConfig.cmake.in @@ -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}") diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index 033e7af6..6907b7ae 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -29,12 +29,12 @@ if(TARGET spdlog) # then add an alias. This allows us to use the same "spdlog::spdlog" # below that a user would use (with the namespace) add_library(spdlog::spdlog ALIAS spdlog) + find_package(Threads REQUIRED) else() # Stand-alone build find_package(spdlog REQUIRED) endif() -find_package(Threads REQUIRED) # Example of using pre-compiled library add_executable(example example.cpp) @@ -50,7 +50,7 @@ get_target_property(SPDLOG_INCLUDE_DIRS spdlog::spdlog INTERFACE_INCLUDE_DIRECTO target_include_directories(example_header_only PRIVATE ${SPDLOG_INCLUDE_DIRS}) target_link_libraries(example_header_only Threads::Threads) if(CMAKE_SYSTEM_NAME STREQUAL "Android") - target_link_libraries(example_header_only log) + target_link_libraries(example_header_only log Threads::Threads) endif () add_executable(multisink multisink.cpp) diff --git a/example/logs/.gitignore b/example/logs/.gitignore deleted file mode 100644 index 20325135..00000000 --- a/example/logs/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.txt From 18ccd55725b1bc27aaee90db9d442eb614f8a4e3 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 19 May 2019 15:57:22 +0300 Subject: [PATCH 137/157] Removed multisink and test in example --- example/CMakeLists.txt | 7 ------- example/multisink.cpp | 47 ------------------------------------------ 2 files changed, 54 deletions(-) delete mode 100644 example/multisink.cpp diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index 6907b7ae..bd722d45 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -53,11 +53,4 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Android") target_link_libraries(example_header_only log Threads::Threads) endif () -add_executable(multisink multisink.cpp) -target_link_libraries(multisink spdlog::spdlog) - file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") - -enable_testing() -add_test(NAME example COMMAND example) -add_test(NAME example_header_only COMMAND example) diff --git a/example/multisink.cpp b/example/multisink.cpp deleted file mode 100644 index fd79231c..00000000 --- a/example/multisink.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include "spdlog/spdlog.h" -#include "spdlog/sinks/basic_file_sink.h" -#include "spdlog/sinks/stdout_sinks.h" - -#include -#include - -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 sinks; - sinks.push_back(std::make_shared()); - sinks.push_back(std::make_shared("./log_regular_file.txt")); - sinks.push_back(std::make_shared("./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; - } -} From 2cd53c6ff1e057349e8a2c6db2f05ab27f767fdd Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 19 May 2019 16:34:38 +0300 Subject: [PATCH 138/157] Updated cmake example --- example/CMakeLists.txt | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index bd722d45..8efc1eb1 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -29,28 +29,23 @@ if(TARGET spdlog) # then add an alias. This allows us to use the same "spdlog::spdlog" # 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) else() # Stand-alone build find_package(spdlog REQUIRED) endif() - +#--------------------------------------------------------------------------------------- # Example of using pre-compiled library +#--------------------------------------------------------------------------------------- add_executable(example example.cpp) target_link_libraries(example spdlog::spdlog) -if(CMAKE_SYSTEM_NAME STREQUAL "Android") - find_library(log-lib log) - target_link_libraries(example log) -endif() +#--------------------------------------------------------------------------------------- # Example of using header-only library +#--------------------------------------------------------------------------------------- add_executable(example_header_only example.cpp) -get_target_property(SPDLOG_INCLUDE_DIRS spdlog::spdlog INTERFACE_INCLUDE_DIRECTORIES) -target_include_directories(example_header_only PRIVATE ${SPDLOG_INCLUDE_DIRS}) -target_link_libraries(example_header_only Threads::Threads) -if(CMAKE_SYSTEM_NAME STREQUAL "Android") - target_link_libraries(example_header_only log Threads::Threads) -endif () +target_link_libraries(example_header_only spdlog::spdlog_header_only) + file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs") From a532a072cee5841b8fb8bd766c491ae24fa48d13 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sun, 19 May 2019 17:06:22 +0300 Subject: [PATCH 139/157] Update CMakeLists.txt --- CMakeLists.txt | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 57307b15..c55fa191 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,8 +12,6 @@ if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE) endif() - - #--------------------------------------------------------------------------------------- # compiler config #--------------------------------------------------------------------------------------- @@ -29,13 +27,10 @@ if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCH add_compile_options("-Wfatal-errors") endif() - - #--------------------------------------------------------------------------------------- # spdlog target #--------------------------------------------------------------------------------------- - # 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) @@ -55,7 +50,7 @@ message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) find_package(Threads REQUIRED) -# Build library +# Static library version add_library(spdlog src/spdlog.cpp) target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB) target_include_directories(spdlog PUBLIC @@ -65,12 +60,11 @@ target_include_directories(spdlog PUBLIC target_link_libraries(spdlog PUBLIC Threads::Threads) -# Header only +# Header only version add_library(spdlog_header_only INTERFACE) target_include_directories(spdlog_header_only INTERFACE "${CMAKE_CURRENT_LIST_DIR}/include") target_link_libraries(spdlog_header_only INTERFACE Threads::Threads) - #--------------------------------------------------------------------------------------- # address sanitizers check #--------------------------------------------------------------------------------------- @@ -151,7 +145,5 @@ if (SPDLOG_INSTALL) #--------------------------------------------------------------------------------------- option(CMAKE_EXPORT_NO_PACKAGE_REGISTRY "Disable registration of CMake's build directory." ON) export(PACKAGE ${PROJECT_NAME}) - endif () - From 48acafd10da684133a029fb0565ea47afc0caaef Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sun, 19 May 2019 17:16:22 +0300 Subject: [PATCH 140/157] Update CMakeLists.txt --- example/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index 8efc1eb1..9f69ccc8 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -47,5 +47,5 @@ target_link_libraries(example spdlog::spdlog) 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") From 576fec4c3604e5fe68cdc6fb2a23e58f00dc9144 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sun, 19 May 2019 17:17:58 +0300 Subject: [PATCH 141/157] Update CMakeLists.txt --- example/CMakeLists.txt | 24 ++---------------------- 1 file changed, 2 insertions(+), 22 deletions(-) diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index 9f69ccc8..2fbbf1d2 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -1,25 +1,5 @@ -# *************************************************************************/ -# * 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. */ -# *************************************************************************/ +# Copyright(c) 2019 spdlog authors +# Distributed under the MIT License (http://opensource.org/licenses/MIT) cmake_minimum_required(VERSION 3.1) project(SpdlogExamples CXX) From 84f25b9f18a00641e013753325e81e145ae1a964 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sun, 19 May 2019 17:19:35 +0300 Subject: [PATCH 142/157] Update CMakeLists.txt --- bench/CMakeLists.txt | 24 ++---------------------- 1 file changed, 2 insertions(+), 22 deletions(-) diff --git a/bench/CMakeLists.txt b/bench/CMakeLists.txt index dcb03a9e..5b88d41a 100644 --- a/bench/CMakeLists.txt +++ b/bench/CMakeLists.txt @@ -1,25 +1,5 @@ -# *************************************************************************/ -# * 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. */ -# *************************************************************************/ +# Copyright(c) 2019 spdlog authors +# Distributed under the MIT License (http://opensource.org/licenses/MIT) cmake_minimum_required(VERSION 3.1) project(SpdlogBench CXX) From d21bcd2f876a0e310889e37551130c2b07a687fc Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sun, 19 May 2019 17:57:18 +0300 Subject: [PATCH 143/157] Delete utils.h --- example/utils.h | 34 ---------------------------------- 1 file changed, 34 deletions(-) delete mode 100644 example/utils.h diff --git a/example/utils.h b/example/utils.h deleted file mode 100644 index 91610128..00000000 --- a/example/utils.h +++ /dev/null @@ -1,34 +0,0 @@ -// -// Copyright(c) 2015 Gabi Melman. -// Distributed under the MIT License (http://opensource.org/licenses/MIT) -// - -#pragma once - -#include -#include -#include - -namespace utils { - -template -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 From c264c3e2dddf7c98885094001cde80b9e3588292 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sun, 19 May 2019 17:58:44 +0300 Subject: [PATCH 144/157] Delete Android.mk --- example/jni/Android.mk | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 example/jni/Android.mk diff --git a/example/jni/Android.mk b/example/jni/Android.mk deleted file mode 100644 index 7accbad3..00000000 --- a/example/jni/Android.mk +++ /dev/null @@ -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) From cfa6d12691c10c0df2c74f1c15bba5731a7ff5ee Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sun, 19 May 2019 17:58:52 +0300 Subject: [PATCH 145/157] Delete Application.mk --- example/jni/Application.mk | 2 -- 1 file changed, 2 deletions(-) delete mode 100644 example/jni/Application.mk diff --git a/example/jni/Application.mk b/example/jni/Application.mk deleted file mode 100644 index dccd2a5a..00000000 --- a/example/jni/Application.mk +++ /dev/null @@ -1,2 +0,0 @@ -# Exceptions are used in spdlog. Link to an exception-ready C++ runtime. -APP_STL = gnustl_static From 322665a22f8b60a1d5497ec57879bfcbe9593b06 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sun, 19 May 2019 17:59:00 +0300 Subject: [PATCH 146/157] Delete example.cpp --- example/jni/example.cpp | 157 ---------------------------------------- 1 file changed, 157 deletions(-) delete mode 100644 example/jni/example.cpp diff --git a/example/jni/example.cpp b/example/jni/example.cpp deleted file mode 100644 index 48c4b19e..00000000 --- a/example/jni/example.cpp +++ /dev/null @@ -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 -#include - -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 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 - 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); -} From 1ef80d63304c19015164c1e7fafd99385eac4deb Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 19 May 2019 19:39:38 +0300 Subject: [PATCH 147/157] Updated CMakeLists.txt --- CMakeLists.txt | 65 ++++++++++++++++++++++++++++---------------------- 1 file changed, 36 insertions(+), 29 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c55fa191..169b229a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,18 +19,9 @@ set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) -if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") - add_compile_options("-Wall") - add_compile_options("-Wextra") - add_compile_options("-Wconversion") - add_compile_options("-pedantic") - add_compile_options("-Wfatal-errors") -endif() - #--------------------------------------------------------------------------------------- -# spdlog target +# Set SPDLOG_MASTER_PROJECT to ON if we are building spdlog #--------------------------------------------------------------------------------------- - # Check if spdlog is being used directly or via add_subdirectory, but allow overriding if (NOT DEFINED SPDLOG_MASTER_PROJECT) if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) @@ -40,29 +31,46 @@ else() endif() 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" OFF) +option(BUILD_SHARED_LIBS "Build as shared library" OFF) option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) +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)" ${SPDLOG_MASTER_PROJECT}) +option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) +option(CMAKE_EXPORT_NO_PACKAGE_REGISTRY "Disable registration of CMake's build directory." ON) + message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) find_package(Threads REQUIRED) +if(SPDLOG_MASTER_PROJECT AND ("${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() + + +#--------------------------------------------------------------------------------------- # Static library version +#--------------------------------------------------------------------------------------- add_library(spdlog src/spdlog.cpp) target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB) target_include_directories(spdlog PUBLIC "$" - "$" -) - + "$") target_link_libraries(spdlog PUBLIC Threads::Threads) +#--------------------------------------------------------------------------------------- # Header only version +#--------------------------------------------------------------------------------------- add_library(spdlog_header_only INTERFACE) -target_include_directories(spdlog_header_only INTERFACE "${CMAKE_CURRENT_LIST_DIR}/include") + +target_include_directories(spdlog_header_only INTERFACE + "$" + "$") target_link_libraries(spdlog_header_only INTERFACE Threads::Threads) #--------------------------------------------------------------------------------------- @@ -107,24 +115,24 @@ endif() # install #--------------------------------------------------------------------------------------- if (SPDLOG_INSTALL) - set(project_config_in "${CMAKE_CURRENT_LIST_DIR}/cmake/${PROJECT_NAME}Config.cmake.in") - set(project_config_out "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake") - set(config_targets_file "${PROJECT_NAME}ConfigTargets.cmake") - set(version_config_file "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake") - set(dest_dir lib/${PROJECT_NAME}/cmake) + set(project_config_in "${CMAKE_CURRENT_LIST_DIR}/cmake/spdlogConfig.cmake.in") + set(project_config_out "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfig.cmake") + set(config_targets_file "spdlogConfigTargets.cmake") + set(version_config_file "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfigVersion.cmake") + set(export_dest_dir lib/spdlog/cmake) #--------------------------------------------------------------------------------------- # lib in include files #--------------------------------------------------------------------------------------- install(DIRECTORY include/ DESTINATION include) - install(TARGETS spdlog EXPORT ${PROJECT_NAME} DESTINATION lib) + install(TARGETS spdlog spdlog_header_only EXPORT spdlog DESTINATION lib) #--------------------------------------------------------------------------------------- # package and version files #--------------------------------------------------------------------------------------- - install(EXPORT ${PROJECT_NAME} - DESTINATION ${dest_dir} - NAMESPACE ${PROJECT_NAME}:: + install(EXPORT spdlog + DESTINATION ${export_dest_dir} + NAMESPACE spdlog:: FILE ${config_targets_file}) include(CMakePackageConfigHelpers) @@ -132,7 +140,7 @@ if (SPDLOG_INSTALL) write_basic_package_version_file("${version_config_file}" COMPATIBILITY SameMajorVersion) install(FILES "${project_config_out}" - "${version_config_file}" DESTINATION "${dest_dir}") + "${version_config_file}" DESTINATION "${export_dest_dir}") #--------------------------------------------------------------------------------------- # Support creation of installable packages @@ -143,7 +151,6 @@ if (SPDLOG_INSTALL) # register project in CMake user registry - disabled by default since the # installed/packaged version of the project is preferred. #--------------------------------------------------------------------------------------- - option(CMAKE_EXPORT_NO_PACKAGE_REGISTRY "Disable registration of CMake's build directory." ON) - export(PACKAGE ${PROJECT_NAME}) + export(PACKAGE spdlog) endif () From 6ec8a06a098ad797a5a3ace581a7149091d91dc2 Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 22 May 2019 12:32:59 +0300 Subject: [PATCH 148/157] Fixed Cmake under windows and disable bench build from default config --- CMakeLists.txt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 169b229a..35bb7de5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -31,10 +31,12 @@ else() endif() endif () -option(BUILD_SHARED_LIBS "Build as shared library" OFF) +if(NOT WIN32) #spdlog does not yet contain __declspec( dllexport ) under windows. + option(BUILD_SHARED_LIBS "Build as shared library" OFF) +endif() option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) 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)" ${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_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) option(CMAKE_EXPORT_NO_PACKAGE_REGISTRY "Disable registration of CMake's build directory." ON) From 65576707bfe7fdcde52d8711eb326a665934e5b1 Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 23 May 2019 18:26:47 +0300 Subject: [PATCH 149/157] Removed shared_lib option (not supported by windwos) and remove example and test from default build --- CMakeLists.txt | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 35bb7de5..7e42aab8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -31,16 +31,11 @@ else() endif() endif () -if(NOT WIN32) #spdlog does not yet contain __declspec( dllexport ) under windows. - option(BUILD_SHARED_LIBS "Build as shared library" OFF) -endif() option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) -option(SPDLOG_BUILD_EXAMPLES "Build examples" ${SPDLOG_MASTER_PROJECT}) +option(SPDLOG_BUILD_EXAMPLES "Build examples" OFF) 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_BUILD_TESTS "Build tests" OFF) option(SPDLOG_INSTALL "Generate the install target." ${SPDLOG_MASTER_PROJECT}) -option(CMAKE_EXPORT_NO_PACKAGE_REGISTRY "Disable registration of CMake's build directory." ON) - message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) @@ -58,7 +53,7 @@ endif() #--------------------------------------------------------------------------------------- # Static library version #--------------------------------------------------------------------------------------- -add_library(spdlog src/spdlog.cpp) +add_library(spdlog STATIC src/spdlog.cpp) target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB) target_include_directories(spdlog PUBLIC "$" @@ -149,10 +144,5 @@ if (SPDLOG_INSTALL) #--------------------------------------------------------------------------------------- include(cmake/SpdlogCPack.cmake) - #--------------------------------------------------------------------------------------- - # register project in CMake user registry - disabled by default since the - # installed/packaged version of the project is preferred. - #--------------------------------------------------------------------------------------- - export(PACKAGE spdlog) endif () From c9547f383a3872adcb1b6d760969fe0fa47d7290 Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 23 May 2019 18:33:02 +0300 Subject: [PATCH 150/157] Fixed appveyor cmake --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 98ce69ba..6aeee9a8 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -26,7 +26,7 @@ build_script: 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% From 2e75f42c691498229bdc0dbe7631cc5acdb2c76b Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 23 May 2019 19:17:52 +0300 Subject: [PATCH 151/157] Install using GNUInstallDirs in cmake --- CMakeLists.txt | 297 +++++++++++++++++++++++++------------------------ 1 file changed, 149 insertions(+), 148 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7e42aab8..b3fa77a3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,148 +1,149 @@ -# Copyright(c) 2019 spdlog authors -# Distributed under the MIT License (http://opensource.org/licenses/MIT) - -cmake_minimum_required(VERSION 3.1) -project(spdlog VERSION 1.3.1 LANGUAGES CXX) -include(CMakeDependentOption) - -#--------------------------------------------------------------------------------------- -# set default build to release -#--------------------------------------------------------------------------------------- -if(NOT CMAKE_BUILD_TYPE) - set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE) -endif() - -#--------------------------------------------------------------------------------------- -# compiler config -#--------------------------------------------------------------------------------------- -set(CMAKE_CXX_STANDARD 11) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -#--------------------------------------------------------------------------------------- -# Set SPDLOG_MASTER_PROJECT to ON if we are building spdlog -#--------------------------------------------------------------------------------------- -# Check if spdlog is being used directly or via add_subdirectory, but allow overriding -if (NOT DEFINED SPDLOG_MASTER_PROJECT) -if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) - set(SPDLOG_MASTER_PROJECT ON) -else() - set(SPDLOG_MASTER_PROJECT OFF) -endif() -endif () - -option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) -option(SPDLOG_BUILD_EXAMPLES "Build examples" OFF) -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}) - -message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) - -find_package(Threads REQUIRED) - -if(SPDLOG_MASTER_PROJECT AND ("${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() - - -#--------------------------------------------------------------------------------------- -# Static library version -#--------------------------------------------------------------------------------------- -add_library(spdlog STATIC src/spdlog.cpp) -target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB) -target_include_directories(spdlog PUBLIC - "$" - "$") -target_link_libraries(spdlog PUBLIC Threads::Threads) - -#--------------------------------------------------------------------------------------- -# Header only version -#--------------------------------------------------------------------------------------- -add_library(spdlog_header_only INTERFACE) - -target_include_directories(spdlog_header_only INTERFACE - "$" - "$") -target_link_libraries(spdlog_header_only INTERFACE Threads::Threads) - -#--------------------------------------------------------------------------------------- -# address sanitizers check -#--------------------------------------------------------------------------------------- -if(SPDLOG_MASTER_PROJECT) - include(cmake/sanitizers.cmake) -endif() - -#--------------------------------------------------------------------------------------- -# 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) - add_subdirectory(example) -endif() - -if(SPDLOG_BUILD_TESTS) - include(CTest) - add_subdirectory(tests) -endif() - -if(SPDLOG_BUILD_BENCH) - add_subdirectory(bench) -endif() - -#--------------------------------------------------------------------------------------- -# install -#--------------------------------------------------------------------------------------- -if (SPDLOG_INSTALL) - set(project_config_in "${CMAKE_CURRENT_LIST_DIR}/cmake/spdlogConfig.cmake.in") - set(project_config_out "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfig.cmake") - set(config_targets_file "spdlogConfigTargets.cmake") - set(version_config_file "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfigVersion.cmake") - set(export_dest_dir lib/spdlog/cmake) - - #--------------------------------------------------------------------------------------- - # lib in include files - #--------------------------------------------------------------------------------------- - install(DIRECTORY include/ DESTINATION include) - install(TARGETS spdlog spdlog_header_only EXPORT spdlog DESTINATION lib) - - #--------------------------------------------------------------------------------------- - # package and version files - #--------------------------------------------------------------------------------------- - install(EXPORT spdlog - DESTINATION ${export_dest_dir} - NAMESPACE spdlog:: - FILE ${config_targets_file}) - - include(CMakePackageConfigHelpers) - configure_file("${project_config_in}" "${project_config_out}" @ONLY) - write_basic_package_version_file("${version_config_file}" COMPATIBILITY SameMajorVersion) - install(FILES - "${project_config_out}" - "${version_config_file}" DESTINATION "${export_dest_dir}") - - #--------------------------------------------------------------------------------------- - # Support creation of installable packages - #--------------------------------------------------------------------------------------- - include(cmake/SpdlogCPack.cmake) - -endif () - +# Copyright(c) 2019 spdlog authors +# Distributed under the MIT License (http://opensource.org/licenses/MIT) + +cmake_minimum_required(VERSION 3.1) +project(spdlog VERSION 1.3.1 LANGUAGES CXX) +include(CMakeDependentOption) +include(GNUInstallDirs) + +#--------------------------------------------------------------------------------------- +# set default build to release +#--------------------------------------------------------------------------------------- +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE) +endif() + +#--------------------------------------------------------------------------------------- +# compiler config +#--------------------------------------------------------------------------------------- +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +#--------------------------------------------------------------------------------------- +# Set SPDLOG_MASTER_PROJECT to ON if we are building spdlog +#--------------------------------------------------------------------------------------- +# Check if spdlog is being used directly or via add_subdirectory, but allow overriding +if (NOT DEFINED SPDLOG_MASTER_PROJECT) +if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) + set(SPDLOG_MASTER_PROJECT ON) +else() + set(SPDLOG_MASTER_PROJECT OFF) +endif() +endif () + +option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) +option(SPDLOG_BUILD_EXAMPLES "Build examples" OFF) +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}) + +message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) + +find_package(Threads REQUIRED) + +if(SPDLOG_MASTER_PROJECT AND ("${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() + + +#--------------------------------------------------------------------------------------- +# Static library version +#--------------------------------------------------------------------------------------- +add_library(spdlog STATIC src/spdlog.cpp) +target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB) +target_include_directories(spdlog PUBLIC + "$" + "$") +target_link_libraries(spdlog PUBLIC Threads::Threads) + +#--------------------------------------------------------------------------------------- +# Header only version +#--------------------------------------------------------------------------------------- +add_library(spdlog_header_only INTERFACE) + +target_include_directories(spdlog_header_only INTERFACE + "$" + "$") +target_link_libraries(spdlog_header_only INTERFACE Threads::Threads) + +#--------------------------------------------------------------------------------------- +# address sanitizers check +#--------------------------------------------------------------------------------------- +if(SPDLOG_MASTER_PROJECT) + include(cmake/sanitizers.cmake) +endif() + +#--------------------------------------------------------------------------------------- +# 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) + add_subdirectory(example) +endif() + +if(SPDLOG_BUILD_TESTS) + include(CTest) + add_subdirectory(tests) +endif() + +if(SPDLOG_BUILD_BENCH) + add_subdirectory(bench) +endif() + +#--------------------------------------------------------------------------------------- +# install +#--------------------------------------------------------------------------------------- +if (SPDLOG_INSTALL) + set(project_config_in "${CMAKE_CURRENT_LIST_DIR}/cmake/spdlogConfig.cmake.in") + set(project_config_out "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfig.cmake") + set(config_targets_file "spdlogConfigTargets.cmake") + set(version_config_file "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfigVersion.cmake") + set(export_dest_dir "${CMAKE_INSTALL_LIBDIR}/spdlog/cmake") + + #--------------------------------------------------------------------------------------- + # include files + #--------------------------------------------------------------------------------------- + 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}) + + include(CMakePackageConfigHelpers) + configure_file("${project_config_in}" "${project_config_out}" @ONLY) + write_basic_package_version_file("${version_config_file}" COMPATIBILITY SameMajorVersion) + install(FILES + "${project_config_out}" + "${version_config_file}" DESTINATION "${export_dest_dir}") + + #--------------------------------------------------------------------------------------- + # Support creation of installable packages + #--------------------------------------------------------------------------------------- + include(cmake/SpdlogCPack.cmake) + +endif () + From 6636ae6e633b3f888ab5504db09f91091fdab9a5 Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 23 May 2019 23:35:30 +0300 Subject: [PATCH 152/157] CmakeLists.txt compiler warnings --- CMakeLists.txt | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b3fa77a3..ea4b3167 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -25,32 +25,23 @@ set(CMAKE_CXX_EXTENSIONS OFF) #--------------------------------------------------------------------------------------- # Check if spdlog is being used directly or via add_subdirectory, but allow overriding if (NOT DEFINED SPDLOG_MASTER_PROJECT) -if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) - set(SPDLOG_MASTER_PROJECT ON) -else() - set(SPDLOG_MASTER_PROJECT OFF) -endif() + if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) + set(SPDLOG_MASTER_PROJECT ON) + else() + set(SPDLOG_MASTER_PROJECT OFF) + endif() endif () -option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) -option(SPDLOG_BUILD_EXAMPLES "Build examples" OFF) +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) -if(SPDLOG_MASTER_PROJECT AND ("${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() - - #--------------------------------------------------------------------------------------- # Static library version #--------------------------------------------------------------------------------------- @@ -71,10 +62,20 @@ target_include_directories(spdlog_header_only INTERFACE "$") target_link_libraries(spdlog_header_only INTERFACE Threads::Threads) + #--------------------------------------------------------------------------------------- -# address sanitizers check +# 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 PRIVATE -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 PRIVATE /W3 /WX ) + target_compile_options( spdlog_header_only INTERFACE /W3 /WX) + endif() + include(cmake/sanitizers.cmake) endif() From ca14ae19db47b53721384d3addea5fd3b5cb1675 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 24 May 2019 01:38:26 +0300 Subject: [PATCH 153/157] Turn off tsan in travis - gives false positives --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2a0a35b7..523d1a97 100644 --- a/.travis.yml +++ b/.travis.yml @@ -70,11 +70,11 @@ matrix: 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 + - env: CLANG_VERSION=6.0 BUILD_TYPE=Debug CPP=11 ASAN=Off TSAN=Off os: linux addons: *clang6 - - env: CLANG_VERSION=6.0 BUILD_TYPE=Release CPP=11 ASAN=Off TSAN=On + - env: CLANG_VERSION=6.0 BUILD_TYPE=Release CPP=11 ASAN=Off TSAN=Off os: linux addons: *clang6 From 54f1941691ac0f8b51d8122a98c259c87cf8026b Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 24 May 2019 01:39:02 +0300 Subject: [PATCH 154/157] Fixed target_compile_options in cmake --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ea4b3167..2e336521 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -68,11 +68,11 @@ target_link_libraries(spdlog_header_only INTERFACE Threads::Threads) #--------------------------------------------------------------------------------------- if(SPDLOG_MASTER_PROJECT) if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|AppleClang") - target_compile_options( spdlog PRIVATE -Wall -Wextra -Wconversion -pedantic -Wfatal-errors) + 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 PRIVATE /W3 /WX ) + target_compile_options( spdlog PUBLIC /W3 /WX ) target_compile_options( spdlog_header_only INTERFACE /W3 /WX) endif() From 2963da13929b44d2183103573dd3eb82507b05f1 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 24 May 2019 08:47:29 +0300 Subject: [PATCH 155/157] Updated travis --- .travis.yml | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/.travis.yml b/.travis.yml index 523d1a97..bb4f9f86 100644 --- a/.travis.yml +++ b/.travis.yml @@ -46,7 +46,7 @@ matrix: - env: GCC_VERSION=4.8 BUILD_TYPE=Release CPP=11 os: linux addons: *gcc48 - + - env: GCC_VERSION=7 BUILD_TYPE=Release CPP=11 os: linux addons: *gcc7 @@ -64,24 +64,15 @@ matrix: - env: CLANG_VERSION=6.0 BUILD_TYPE=Debug CPP=11 ASAN=On TSAN=Off os: linux addons: *clang6 - + - env: CLANG_VERSION=6.0 BUILD_TYPE=Release CPP=11 ASAN=On TSAN=Off os: linux addons: *clang6 - - # Test clang-6.0: C++11, Build=Debug, TSAN=On - - env: CLANG_VERSION=6.0 BUILD_TYPE=Debug CPP=11 ASAN=Off TSAN=Off - os: linux - addons: *clang6 - - - env: CLANG_VERSION=6.0 BUILD_TYPE=Release CPP=11 ASAN=Off TSAN=Off - os: linux - addons: *clang6 # osx - env: BUILD_TYPE=Release CPP=11 ASAN=Off TSAN=Off os: osx - + From 884c23a9c95185d250c55151dae303b65ddce7c7 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 24 May 2019 12:44:51 +0300 Subject: [PATCH 156/157] Merge v1.x --- include/spdlog/details/os-inl.h | 4 +- .../spdlog/details/pattern_formatter-inl.h | 42 +++++++++---------- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/include/spdlog/details/os-inl.h b/include/spdlog/details/os-inl.h index e96d1d38..d6af8048 100644 --- a/include/spdlog/details/os-inl.h +++ b/include/spdlog/details/os-inl.h @@ -178,7 +178,7 @@ SPDLOG_INLINE bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT 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); + return (::stat(filename.c_str(), &buffer) == 0); #endif } @@ -218,7 +218,7 @@ SPDLOG_INLINE size_t filesize(FILE *f) #else // unix 32 bits or cygwin struct stat st; - if (fstat(fd, &st) == 0) + if (::fstat(fd, &st) == 0) { return static_cast(st.st_size); } diff --git a/include/spdlog/details/pattern_formatter-inl.h b/include/spdlog/details/pattern_formatter-inl.h index a6951e47..6c5e1c0d 100644 --- a/include/spdlog/details/pattern_formatter-inl.h +++ b/include/spdlog/details/pattern_formatter-inl.h @@ -304,7 +304,7 @@ class Y_formatter final : public flag_formatter { public: explicit Y_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -367,7 +367,7 @@ class I_formatter final : public flag_formatter { public: explicit I_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -382,7 +382,7 @@ class M_formatter final : public flag_formatter { public: explicit M_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -397,7 +397,7 @@ class S_formatter final : public flag_formatter { public: explicit S_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -412,7 +412,7 @@ class e_formatter final : public flag_formatter { public: explicit e_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -435,7 +435,7 @@ class f_formatter final : public flag_formatter { public: explicit f_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -458,7 +458,7 @@ class F_formatter final : public flag_formatter { public: explicit F_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -481,7 +481,7 @@ class E_formatter final : public flag_formatter { public: explicit E_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -498,7 +498,7 @@ class p_formatter final : public flag_formatter { public: explicit p_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -513,7 +513,7 @@ class r_formatter final : public flag_formatter { public: explicit r_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -535,7 +535,7 @@ class R_formatter final : public flag_formatter { public: explicit R_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -553,7 +553,7 @@ class T_formatter final : public flag_formatter { public: explicit T_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { @@ -573,7 +573,7 @@ class z_formatter final : public flag_formatter { public: explicit z_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} const std::chrono::seconds cache_refresh = std::chrono::seconds(5); @@ -632,7 +632,7 @@ class t_formatter final : public flag_formatter { public: explicit t_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -654,7 +654,7 @@ class pid_formatter final : public flag_formatter { public: explicit pid_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override { @@ -676,7 +676,7 @@ class v_formatter final : public flag_formatter { public: explicit v_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -760,7 +760,7 @@ class source_location_formatter final : public flag_formatter { public: explicit source_location_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -789,7 +789,7 @@ class source_filename_formatter final : public flag_formatter { public: explicit source_filename_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -806,7 +806,7 @@ class source_linenum_formatter final : public flag_formatter { public: explicit source_linenum_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -831,7 +831,7 @@ class source_funcname_formatter final : public flag_formatter { public: explicit source_funcname_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){} void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -1169,7 +1169,7 @@ SPDLOG_INLINE details::padding_info pattern_formatter::handle_padspec_(std::stri const size_t max_width = 128; if (it == end) { - return padding_info{}; + return padding_info{} } padding_info::pad_side side; From 9329f8d3cdfb8af05e8dbbd3db2dbef482a2119d Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 24 May 2019 12:46:20 +0300 Subject: [PATCH 157/157] Merge v1.x --- include/spdlog/details/pattern_formatter-inl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/details/pattern_formatter-inl.h b/include/spdlog/details/pattern_formatter-inl.h index 6c5e1c0d..b798dc0d 100644 --- a/include/spdlog/details/pattern_formatter-inl.h +++ b/include/spdlog/details/pattern_formatter-inl.h @@ -1169,7 +1169,7 @@ SPDLOG_INLINE details::padding_info pattern_formatter::handle_padspec_(std::stri const size_t max_width = 128; if (it == end) { - return padding_info{} + return padding_info{}; } padding_info::pad_side side;