diff --git a/bench/async_bench.cpp b/bench/async_bench.cpp index cf4d9754..8d4d8106 100644 --- a/bench/async_bench.cpp +++ b/bench/async_bench.cpp @@ -11,11 +11,11 @@ #include "spdlog/sinks/basic_file_sink.h" #if defined(SPDLOG_USE_STD_FORMAT) -# include + #include #elif defined(SPDLOG_FMT_EXTERNAL) -# include + #include #else -# include "spdlog/fmt/bundled/format.h" + #include "spdlog/fmt/bundled/format.h" #endif #include "utils.h" @@ -34,17 +34,15 @@ using namespace utils; void bench_mt(int howmany, std::shared_ptr log, int thread_count); #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable : 4996) // disable fopen warning under msvc + #pragma warning(push) + #pragma warning(disable : 4996) // disable fopen warning under msvc #endif // _MSC_VER -int count_lines(const char *filename) -{ +int count_lines(const char *filename) { int counter = 0; auto *infile = fopen(filename, "r"); int ch; - while (EOF != (ch = getc(infile))) - { + while (EOF != (ch = getc(infile))) { if ('\n' == ch) counter++; } @@ -53,35 +51,31 @@ int count_lines(const char *filename) return counter; } -void verify_file(const char *filename, int expected_count) -{ +void verify_file(const char *filename, int expected_count) { spdlog::info("Verifying {} to contain {} line..", filename, expected_count); auto count = count_lines(filename); - if (count != expected_count) - { - spdlog::error("Test failed. {} has {} lines instead of {}", filename, count, expected_count); + if (count != expected_count) { + spdlog::error("Test failed. {} has {} lines instead of {}", filename, count, + expected_count); exit(1); } spdlog::info("Line count OK ({})\n", count); } #ifdef _MSC_VER -# pragma warning(pop) + #pragma warning(pop) #endif -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { int howmany = 1000000; int queue_size = std::min(howmany + 2, 8192); int threads = 10; int iters = 3; - try - { + try { spdlog::set_pattern("[%^%l%$] %v"); - if (argc == 1) - { + if (argc == 1) { spdlog::info("Usage: {} ", argv[0]); return 0; } @@ -90,11 +84,9 @@ int main(int argc, char *argv[]) howmany = atoi(argv[1]); if (argc > 2) threads = atoi(argv[2]); - if (argc > 3) - { + if (argc > 3) { queue_size = atoi(argv[3]); - if (queue_size > 500000) - { + if (queue_size > 500000) { spdlog::error("Max queue size allowed: 500,000"); exit(1); } @@ -108,7 +100,8 @@ int main(int argc, char *argv[]) spdlog::info("Messages : {:L}", howmany); spdlog::info("Threads : {:L}", threads); spdlog::info("Queue : {:L} slots", queue_size); - spdlog::info("Queue memory : {:L} x {:L} = {:L} KB ", queue_size, slot_size, (queue_size * slot_size) / 1024); + spdlog::info("Queue memory : {:L} x {:L} = {:L} KB ", queue_size, slot_size, + (queue_size * slot_size) / 1024); spdlog::info("Total iters : {:L}", iters); spdlog::info("-------------------------------------------------"); @@ -117,11 +110,11 @@ int main(int argc, char *argv[]) spdlog::info("*********************************"); spdlog::info("Queue Overflow Policy: block"); spdlog::info("*********************************"); - for (int i = 0; i < iters; i++) - { + for (int i = 0; i < iters; i++) { auto tp = std::make_shared(queue_size, 1); auto file_sink = std::make_shared(filename, true); - auto logger = std::make_shared("async_logger", std::move(file_sink), std::move(tp), async_overflow_policy::block); + auto logger = std::make_shared( + "async_logger", std::move(file_sink), std::move(tp), async_overflow_policy::block); bench_mt(howmany, std::move(logger), threads); // verify_file(filename, howmany); } @@ -132,18 +125,16 @@ int main(int argc, char *argv[]) spdlog::info("*********************************"); // do same test but discard oldest if queue is full instead of blocking filename = "logs/basic_async-overrun.log"; - for (int i = 0; i < iters; i++) - { + for (int i = 0; i < iters; i++) { auto tp = std::make_shared(queue_size, 1); auto file_sink = std::make_shared(filename, true); auto logger = - std::make_shared("async_logger", std::move(file_sink), std::move(tp), async_overflow_policy::overrun_oldest); + std::make_shared("async_logger", std::move(file_sink), std::move(tp), + async_overflow_policy::overrun_oldest); bench_mt(howmany, std::move(logger), threads); } spdlog::shutdown(); - } - catch (std::exception &ex) - { + } catch (std::exception &ex) { std::cerr << "Error: " << ex.what() << std::endl; perror("Last error"); return 1; @@ -151,32 +142,28 @@ int main(int argc, char *argv[]) return 0; } -void thread_fun(std::shared_ptr logger, int howmany) -{ - for (int i = 0; i < howmany; i++) - { +void thread_fun(std::shared_ptr logger, int howmany) { + for (int i = 0; i < howmany; i++) { logger->info("Hello logger: msg number {}", i); } } -void bench_mt(int howmany, std::shared_ptr logger, int thread_count) -{ +void bench_mt(int howmany, std::shared_ptr logger, int thread_count) { using std::chrono::high_resolution_clock; vector threads; auto start = high_resolution_clock::now(); int msgs_per_thread = howmany / thread_count; int msgs_per_thread_mod = howmany % thread_count; - for (int t = 0; t < thread_count; ++t) - { + for (int t = 0; t < thread_count; ++t) { if (t == 0 && msgs_per_thread_mod) - threads.push_back(std::thread(thread_fun, logger, msgs_per_thread + msgs_per_thread_mod)); + threads.push_back( + std::thread(thread_fun, logger, msgs_per_thread + msgs_per_thread_mod)); else threads.push_back(std::thread(thread_fun, logger, msgs_per_thread)); } - for (auto &t : threads) - { + for (auto &t : threads) { t.join(); }; diff --git a/bench/bench.cpp b/bench/bench.cpp index 3b73554a..c69471d3 100644 --- a/bench/bench.cpp +++ b/bench/bench.cpp @@ -13,11 +13,11 @@ #include "spdlog/sinks/rotating_file_sink.h" #if defined(SPDLOG_USE_STD_FORMAT) -# include + #include #elif defined(SPDLOG_FMT_EXTERNAL) -# include + #include #else -# include "spdlog/fmt/bundled/format.h" + #include "spdlog/fmt/bundled/format.h" #endif #include "utils.h" @@ -37,22 +37,25 @@ static const size_t file_size = 30 * 1024 * 1024; static const size_t rotating_files = 5; static const int max_threads = 1000; -void bench_threaded_logging(size_t threads, int iters) -{ +void bench_threaded_logging(size_t threads, int iters) { spdlog::info("**************************************************************"); - spdlog::info(spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), "Multi threaded: {:L} threads, {:L} messages", threads, iters)); + spdlog::info(spdlog::fmt_lib::format( + std::locale("en_US.UTF-8"), "Multi threaded: {:L} threads, {:L} messages", threads, iters)); spdlog::info("**************************************************************"); auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true); bench_mt(iters, std::move(basic_mt), threads); - auto basic_mt_tracing = spdlog::basic_logger_mt("basic_mt/backtrace-on", "logs/basic_mt.log", true); + auto basic_mt_tracing = + spdlog::basic_logger_mt("basic_mt/backtrace-on", "logs/basic_mt.log", true); basic_mt_tracing->enable_backtrace(32); bench_mt(iters, std::move(basic_mt_tracing), threads); spdlog::info(""); - auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files); + auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, + rotating_files); bench_mt(iters, std::move(rotating_mt), threads); - auto rotating_mt_tracing = spdlog::rotating_logger_mt("rotating_mt/backtrace-on", "logs/rotating_mt.log", file_size, rotating_files); + auto rotating_mt_tracing = spdlog::rotating_logger_mt( + "rotating_mt/backtrace-on", "logs/rotating_mt.log", file_size, rotating_files); rotating_mt_tracing->enable_backtrace(32); bench_mt(iters, std::move(rotating_mt_tracing), threads); @@ -73,22 +76,25 @@ void bench_threaded_logging(size_t threads, int iters) bench(iters, empty_logger_tracing); } -void bench_single_threaded(int iters) -{ +void bench_single_threaded(int iters) { spdlog::info("**************************************************************"); - spdlog::info(spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), "Single threaded: {} messages", iters)); + spdlog::info( + spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), "Single threaded: {} messages", iters)); spdlog::info("**************************************************************"); auto basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true); bench(iters, std::move(basic_st)); - auto basic_st_tracing = spdlog::basic_logger_st("basic_st/backtrace-on", "logs/basic_st.log", true); + auto basic_st_tracing = + spdlog::basic_logger_st("basic_st/backtrace-on", "logs/basic_st.log", true); bench(iters, std::move(basic_st_tracing)); spdlog::info(""); - auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files); + auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, + rotating_files); bench(iters, std::move(rotating_st)); - auto rotating_st_tracing = spdlog::rotating_logger_st("rotating_st/backtrace-on", "logs/rotating_st.log", file_size, rotating_files); + auto rotating_st_tracing = spdlog::rotating_logger_st( + "rotating_st/backtrace-on", "logs/rotating_st.log", file_size, rotating_files); rotating_st_tracing->enable_backtrace(32); bench(iters, std::move(rotating_st_tracing)); @@ -110,63 +116,55 @@ void bench_single_threaded(int iters) bench(iters, empty_logger_tracing); } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { spdlog::set_automatic_registration(false); spdlog::default_logger()->set_pattern("[%^%l%$] %v"); int iters = 250000; size_t threads = 4; - try - { + try { - if (argc > 1) - { + if (argc > 1) { iters = std::stoi(argv[1]); } - if (argc > 2) - { + if (argc > 2) { threads = std::stoul(argv[2]); } - if (threads > max_threads) - { - throw std::runtime_error(spdlog::fmt_lib::format("Number of threads exceeds maximum({})", max_threads)); + if (threads > max_threads) { + throw std::runtime_error( + spdlog::fmt_lib::format("Number of threads exceeds maximum({})", max_threads)); } bench_single_threaded(iters); bench_threaded_logging(1, iters); bench_threaded_logging(threads, iters); - } - catch (std::exception &ex) - { + } catch (std::exception &ex) { spdlog::error(ex.what()); return EXIT_FAILURE; } return EXIT_SUCCESS; } -void bench(int howmany, std::shared_ptr log) -{ +void bench(int howmany, std::shared_ptr log) { using std::chrono::duration; using std::chrono::duration_cast; using std::chrono::high_resolution_clock; auto start = high_resolution_clock::now(); - for (auto i = 0; i < howmany; ++i) - { + for (auto i = 0; i < howmany; ++i) { log->info("Hello logger: msg number {}", i); } auto delta = high_resolution_clock::now() - start; auto delta_d = duration_cast>(delta).count(); - spdlog::info(spdlog::fmt_lib::format( - std::locale("en_US.UTF-8"), "{:<30} Elapsed: {:0.2f} secs {:>16L}/sec", log->name(), delta_d, size_t(howmany / delta_d))); + spdlog::info(spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), + "{:<30} Elapsed: {:0.2f} secs {:>16L}/sec", log->name(), + delta_d, size_t(howmany / delta_d))); spdlog::drop(log->name()); } -void bench_mt(int howmany, std::shared_ptr log, size_t thread_count) -{ +void bench_mt(int howmany, std::shared_ptr log, size_t thread_count) { using std::chrono::duration; using std::chrono::duration_cast; using std::chrono::high_resolution_clock; @@ -174,25 +172,23 @@ void bench_mt(int howmany, std::shared_ptr log, size_t thread_co std::vector threads; threads.reserve(thread_count); auto start = high_resolution_clock::now(); - for (size_t t = 0; t < thread_count; ++t) - { + for (size_t t = 0; t < thread_count; ++t) { threads.emplace_back([&]() { - for (int j = 0; j < howmany / static_cast(thread_count); j++) - { + for (int j = 0; j < howmany / static_cast(thread_count); j++) { log->info("Hello logger: msg number {}", j); } }); } - for (auto &t : threads) - { + for (auto &t : threads) { t.join(); }; auto delta = high_resolution_clock::now() - start; auto delta_d = duration_cast>(delta).count(); - spdlog::info(spdlog::fmt_lib::format( - std::locale("en_US.UTF-8"), "{:<30} Elapsed: {:0.2f} secs {:>16L}/sec", log->name(), delta_d, size_t(howmany / delta_d))); + spdlog::info(spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), + "{:<30} Elapsed: {:0.2f} secs {:>16L}/sec", log->name(), + delta_d, size_t(howmany / delta_d))); spdlog::drop(log->name()); } @@ -215,7 +211,8 @@ void bench_default_api(int howmany, std::shared_ptr log) auto delta_d = duration_cast>(delta).count(); spdlog::drop(log->name()); spdlog::set_default_logger(std::move(orig_default)); - spdlog::info("{:<30} Elapsed: {:0.2f} secs {:>16}/sec", log->name(), delta_d, int(howmany / delta_d)); + spdlog::info("{:<30} Elapsed: {:0.2f} secs {:>16}/sec", log->name(), delta_d, int(howmany / +delta_d)); } void bench_c_string(int howmany, std::shared_ptr log) @@ -224,11 +221,12 @@ void bench_c_string(int howmany, std::shared_ptr log) using std::chrono::duration; using std::chrono::duration_cast; - const char *msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus " - "lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, eu consequat sem " - "libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec fringilla dui sed " - "augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, nisi turpis ornare " - "nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis."; + const char *msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra +metus cursus " "lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus +volutpat mi, eu consequat sem " "libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam +non dapibus eros. Donec fringilla dui sed " "augue pretium, nec scelerisque est maximus. Nullam +convallis, sem nec blandit maximus, nisi turpis ornare " "nisl, sit amet volutpat neque massa eu +odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis."; auto orig_default = spdlog::default_logger(); spdlog::set_default_logger(log); @@ -242,7 +240,8 @@ void bench_c_string(int howmany, std::shared_ptr log) auto delta_d = duration_cast>(delta).count(); spdlog::drop(log->name()); spdlog::set_default_logger(std::move(orig_default)); - spdlog::info("{:<30} Elapsed: {:0.2f} secs {:>16}/sec", log->name(), delta_d, int(howmany / delta_d)); + spdlog::info("{:<30} Elapsed: {:0.2f} secs {:>16}/sec", log->name(), delta_d, int(howmany / +delta_d)); } */ \ No newline at end of file diff --git a/bench/formatter-bench.cpp b/bench/formatter-bench.cpp index 1454c6bb..7c5c1843 100644 --- a/bench/formatter-bench.cpp +++ b/bench/formatter-bench.cpp @@ -8,31 +8,28 @@ #include "spdlog/spdlog.h" #include "spdlog/pattern_formatter.h" -void bench_formatter(benchmark::State &state, std::string pattern) -{ +void bench_formatter(benchmark::State &state, std::string pattern) { auto formatter = spdlog::details::make_unique(pattern); spdlog::memory_buf_t dest; std::string logger_name = "logger-name"; - const char *text = "Hello. This is some message with length of 80 "; + const char *text = + "Hello. This is some message with length of 80 "; spdlog::source_loc source_loc{"a/b/c/d/myfile.cpp", 123, "some_func()"}; spdlog::details::log_msg msg(source_loc, logger_name, spdlog::level::info, text); - for (auto _ : state) - { + for (auto _ : state) { dest.clear(); formatter->format(msg, dest); benchmark::DoNotOptimize(dest); } } -void bench_formatters() -{ +void bench_formatters() { // basic patterns(single flag) std::string all_flags = "+vtPnlLaAbBcCYDmdHIMSefFprRTXzEisg@luioO%"; std::vector basic_patterns; - for (auto &flag : all_flags) - { + for (auto &flag : all_flags) { auto pattern = std::string("%") + flag; benchmark::RegisterBenchmark(pattern.c_str(), &bench_formatter, pattern); @@ -50,29 +47,24 @@ void bench_formatters() "[%Y-%m-%d %H:%M:%S.%e] [%l] [%n] %v", "[%Y-%m-%d %H:%M:%S.%e] [%l] [%n] [%t] %v", }; - for (auto &pattern : patterns) - { - benchmark::RegisterBenchmark(pattern.c_str(), &bench_formatter, pattern)->Iterations(2500000); + for (auto &pattern : patterns) { + benchmark::RegisterBenchmark(pattern.c_str(), &bench_formatter, pattern) + ->Iterations(2500000); } } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { spdlog::set_pattern("[%^%l%$] %v"); - if (argc != 2) - { + if (argc != 2) { spdlog::error("Usage: {} (or \"all\" to bench all)", argv[0]); exit(1); } std::string pattern = argv[1]; - if (pattern == "all") - { + if (pattern == "all") { bench_formatters(); - } - else - { + } else { benchmark::RegisterBenchmark(pattern.c_str(), &bench_formatter, pattern); } benchmark::Initialize(&argc, argv); diff --git a/bench/latency.cpp b/bench/latency.cpp index 8f002ee1..cdb51359 100644 --- a/bench/latency.cpp +++ b/bench/latency.cpp @@ -16,76 +16,72 @@ #include "spdlog/sinks/null_sink.h" #include "spdlog/sinks/rotating_file_sink.h" -void bench_c_string(benchmark::State &state, std::shared_ptr logger) -{ - const char *msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus " - "lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, eu consequat sem " - "libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec fringilla dui sed " - "augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, nisi turpis ornare " - "nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis."; +void bench_c_string(benchmark::State &state, std::shared_ptr logger) { + const char *msg = + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus " + "lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, " + "eu consequat sem " + "libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec " + "fringilla dui sed " + "augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, " + "nisi turpis ornare " + "nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue " + "nibh turpis duis."; - for (auto _ : state) - { + for (auto _ : state) { logger->info(msg); } } -void bench_logger(benchmark::State &state, std::shared_ptr logger) -{ +void bench_logger(benchmark::State &state, std::shared_ptr logger) { int i = 0; - for (auto _ : state) - { + for (auto _ : state) { logger->info("Hello logger: msg number {}...............", ++i); } } -void bench_global_logger(benchmark::State &state, std::shared_ptr logger) -{ +void bench_global_logger(benchmark::State &state, std::shared_ptr logger) { spdlog::set_default_logger(std::move(logger)); int i = 0; - for (auto _ : state) - { + for (auto _ : state) { spdlog::info("Hello logger: msg number {}...............", ++i); } } -void bench_disabled_macro(benchmark::State &state, std::shared_ptr logger) -{ +void bench_disabled_macro(benchmark::State &state, std::shared_ptr logger) { int i = 0; benchmark::DoNotOptimize(i); // prevent unused warnings benchmark::DoNotOptimize(logger); // prevent unused warnings - for (auto _ : state) - { + for (auto _ : state) { SPDLOG_LOGGER_DEBUG(logger, "Hello logger: msg number {}...............", i++); } } -void bench_disabled_macro_global_logger(benchmark::State &state, std::shared_ptr logger) -{ +void bench_disabled_macro_global_logger(benchmark::State &state, + std::shared_ptr logger) { spdlog::set_default_logger(std::move(logger)); int i = 0; benchmark::DoNotOptimize(i); // prevent unused warnings benchmark::DoNotOptimize(logger); // prevent unused warnings - for (auto _ : state) - { + for (auto _ : state) { SPDLOG_DEBUG("Hello logger: msg number {}...............", i++); } } #ifdef __linux__ -void bench_dev_null() -{ +void bench_dev_null() { auto dev_null_st = spdlog::basic_logger_st("/dev/null_st", "/dev/null"); - benchmark::RegisterBenchmark("/dev/null_st", bench_logger, std::move(dev_null_st))->UseRealTime(); + benchmark::RegisterBenchmark("/dev/null_st", bench_logger, std::move(dev_null_st)) + ->UseRealTime(); spdlog::drop("/dev/null_st"); auto dev_null_mt = spdlog::basic_logger_mt("/dev/null_mt", "/dev/null"); - benchmark::RegisterBenchmark("/dev/null_mt", bench_logger, std::move(dev_null_mt))->UseRealTime(); + benchmark::RegisterBenchmark("/dev/null_mt", bench_logger, std::move(dev_null_mt)) + ->UseRealTime(); spdlog::drop("/dev/null_mt"); } #endif // __linux__ -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { using spdlog::sinks::null_sink_mt; using spdlog::sinks::null_sink_st; @@ -96,23 +92,32 @@ int main(int argc, char *argv[]) auto full_bench = argc > 1 && std::string(argv[1]) == "full"; // disabled loggers - auto disabled_logger = std::make_shared("bench", std::make_shared()); + auto disabled_logger = + std::make_shared("bench", std::make_shared()); disabled_logger->set_level(spdlog::level::off); benchmark::RegisterBenchmark("disabled-at-compile-time", bench_disabled_macro, disabled_logger); - benchmark::RegisterBenchmark("disabled-at-compile-time (global logger)", bench_disabled_macro_global_logger, disabled_logger); + benchmark::RegisterBenchmark("disabled-at-compile-time (global logger)", + bench_disabled_macro_global_logger, disabled_logger); benchmark::RegisterBenchmark("disabled-at-runtime", bench_logger, disabled_logger); - benchmark::RegisterBenchmark("disabled-at-runtime (global logger)", bench_global_logger, disabled_logger); + benchmark::RegisterBenchmark("disabled-at-runtime (global logger)", bench_global_logger, + disabled_logger); // with backtrace of 64 - auto tracing_disabled_logger = std::make_shared("bench", std::make_shared()); + auto tracing_disabled_logger = + std::make_shared("bench", std::make_shared()); tracing_disabled_logger->enable_backtrace(64); - benchmark::RegisterBenchmark("disabled-at-runtime/backtrace", bench_logger, tracing_disabled_logger); + benchmark::RegisterBenchmark("disabled-at-runtime/backtrace", bench_logger, + tracing_disabled_logger); - auto null_logger_st = std::make_shared("bench", std::make_shared()); - benchmark::RegisterBenchmark("null_sink_st (500_bytes c_str)", bench_c_string, std::move(null_logger_st)); + auto null_logger_st = + std::make_shared("bench", std::make_shared()); + benchmark::RegisterBenchmark("null_sink_st (500_bytes c_str)", bench_c_string, + std::move(null_logger_st)); benchmark::RegisterBenchmark("null_sink_st", bench_logger, null_logger_st); - benchmark::RegisterBenchmark("null_sink_st (global logger)", bench_global_logger, null_logger_st); + benchmark::RegisterBenchmark("null_sink_st (global logger)", bench_global_logger, + null_logger_st); // with backtrace of 64 - auto tracing_null_logger_st = std::make_shared("bench", std::make_shared()); + auto tracing_null_logger_st = + std::make_shared("bench", std::make_shared()); tracing_null_logger_st->enable_backtrace(64); benchmark::RegisterBenchmark("null_sink_st/backtrace", bench_logger, tracing_null_logger_st); @@ -120,55 +125,75 @@ int main(int argc, char *argv[]) bench_dev_null(); #endif // __linux__ - if (full_bench) - { + if (full_bench) { // basic_st auto basic_st = spdlog::basic_logger_st("basic_st", "latency_logs/basic_st.log", true); benchmark::RegisterBenchmark("basic_st", bench_logger, std::move(basic_st))->UseRealTime(); spdlog::drop("basic_st"); // with backtrace of 64 - auto tracing_basic_st = spdlog::basic_logger_st("tracing_basic_st", "latency_logs/tracing_basic_st.log", true); + auto tracing_basic_st = + spdlog::basic_logger_st("tracing_basic_st", "latency_logs/tracing_basic_st.log", true); tracing_basic_st->enable_backtrace(64); - benchmark::RegisterBenchmark("basic_st/backtrace", bench_logger, std::move(tracing_basic_st))->UseRealTime(); + benchmark::RegisterBenchmark("basic_st/backtrace", bench_logger, + std::move(tracing_basic_st)) + ->UseRealTime(); spdlog::drop("tracing_basic_st"); // rotating st - auto rotating_st = spdlog::rotating_logger_st("rotating_st", "latency_logs/rotating_st.log", file_size, rotating_files); - benchmark::RegisterBenchmark("rotating_st", bench_logger, std::move(rotating_st))->UseRealTime(); + auto rotating_st = spdlog::rotating_logger_st("rotating_st", "latency_logs/rotating_st.log", + file_size, rotating_files); + benchmark::RegisterBenchmark("rotating_st", bench_logger, std::move(rotating_st)) + ->UseRealTime(); spdlog::drop("rotating_st"); // with backtrace of 64 - auto tracing_rotating_st = - spdlog::rotating_logger_st("tracing_rotating_st", "latency_logs/tracing_rotating_st.log", file_size, rotating_files); - benchmark::RegisterBenchmark("rotating_st/backtrace", bench_logger, std::move(tracing_rotating_st))->UseRealTime(); + auto tracing_rotating_st = spdlog::rotating_logger_st( + "tracing_rotating_st", "latency_logs/tracing_rotating_st.log", file_size, + rotating_files); + benchmark::RegisterBenchmark("rotating_st/backtrace", bench_logger, + std::move(tracing_rotating_st)) + ->UseRealTime(); spdlog::drop("tracing_rotating_st"); // daily st auto daily_st = spdlog::daily_logger_mt("daily_st", "latency_logs/daily_st.log"); benchmark::RegisterBenchmark("daily_st", bench_logger, std::move(daily_st))->UseRealTime(); spdlog::drop("daily_st"); - auto tracing_daily_st = spdlog::daily_logger_mt("tracing_daily_st", "latency_logs/daily_st.log"); - benchmark::RegisterBenchmark("daily_st/backtrace", bench_logger, std::move(tracing_daily_st))->UseRealTime(); + auto tracing_daily_st = + spdlog::daily_logger_mt("tracing_daily_st", "latency_logs/daily_st.log"); + benchmark::RegisterBenchmark("daily_st/backtrace", bench_logger, + std::move(tracing_daily_st)) + ->UseRealTime(); spdlog::drop("tracing_daily_st"); // // Multi threaded bench, 10 loggers using same logger concurrently // - auto null_logger_mt = std::make_shared("bench", std::make_shared()); - benchmark::RegisterBenchmark("null_sink_mt", bench_logger, null_logger_mt)->Threads(n_threads)->UseRealTime(); + auto null_logger_mt = + std::make_shared("bench", std::make_shared()); + benchmark::RegisterBenchmark("null_sink_mt", bench_logger, null_logger_mt) + ->Threads(n_threads) + ->UseRealTime(); // basic_mt auto basic_mt = spdlog::basic_logger_mt("basic_mt", "latency_logs/basic_mt.log", true); - benchmark::RegisterBenchmark("basic_mt", bench_logger, std::move(basic_mt))->Threads(n_threads)->UseRealTime(); + benchmark::RegisterBenchmark("basic_mt", bench_logger, std::move(basic_mt)) + ->Threads(n_threads) + ->UseRealTime(); spdlog::drop("basic_mt"); // rotating mt - auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "latency_logs/rotating_mt.log", file_size, rotating_files); - benchmark::RegisterBenchmark("rotating_mt", bench_logger, std::move(rotating_mt))->Threads(n_threads)->UseRealTime(); + auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "latency_logs/rotating_mt.log", + file_size, rotating_files); + benchmark::RegisterBenchmark("rotating_mt", bench_logger, std::move(rotating_mt)) + ->Threads(n_threads) + ->UseRealTime(); spdlog::drop("rotating_mt"); // daily mt auto daily_mt = spdlog::daily_logger_mt("daily_mt", "latency_logs/daily_mt.log"); - benchmark::RegisterBenchmark("daily_mt", bench_logger, std::move(daily_mt))->Threads(n_threads)->UseRealTime(); + benchmark::RegisterBenchmark("daily_mt", bench_logger, std::move(daily_mt)) + ->Threads(n_threads) + ->UseRealTime(); spdlog::drop("daily_mt"); } @@ -176,13 +201,19 @@ int main(int argc, char *argv[]) auto queue_size = 1024 * 1024 * 3; auto tp = std::make_shared(queue_size, 1); auto async_logger = std::make_shared( - "async_logger", std::make_shared(), std::move(tp), spdlog::async_overflow_policy::overrun_oldest); - benchmark::RegisterBenchmark("async_logger", bench_logger, async_logger)->Threads(n_threads)->UseRealTime(); + "async_logger", std::make_shared(), std::move(tp), + spdlog::async_overflow_policy::overrun_oldest); + benchmark::RegisterBenchmark("async_logger", bench_logger, async_logger) + ->Threads(n_threads) + ->UseRealTime(); auto async_logger_tracing = std::make_shared( - "async_logger_tracing", std::make_shared(), std::move(tp), spdlog::async_overflow_policy::overrun_oldest); + "async_logger_tracing", std::make_shared(), std::move(tp), + spdlog::async_overflow_policy::overrun_oldest); async_logger_tracing->enable_backtrace(32); - benchmark::RegisterBenchmark("async_logger/tracing", bench_logger, async_logger_tracing)->Threads(n_threads)->UseRealTime(); + benchmark::RegisterBenchmark("async_logger/tracing", bench_logger, async_logger_tracing) + ->Threads(n_threads) + ->UseRealTime(); benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); diff --git a/bench/utils.h b/bench/utils.h index 91610128..0f52e700 100644 --- a/bench/utils.h +++ b/bench/utils.h @@ -11,9 +11,8 @@ namespace utils { -template -inline std::string format(const T &value) -{ +template +inline std::string format(const T &value) { static std::locale loc(""); std::stringstream ss; ss.imbue(loc); @@ -21,9 +20,8 @@ inline std::string format(const T &value) return ss.str(); } -template<> -inline std::string format(const double &value) -{ +template <> +inline std::string format(const double &value) { static std::locale loc(""); std::stringstream ss; ss.imbue(loc); diff --git a/example/example.cpp b/example/example.cpp index ba6a1fc3..d491a4da 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -31,12 +31,12 @@ void replace_default_logger_example(); #include "spdlog/cfg/env.h" // support for loading levels from the environment variable #include "spdlog/fmt/ostr.h" // support for user defined types -int main(int, char *[]) -{ +int main(int, char *[]) { // Log levels can be loaded from argv/env using "SPDLOG_LEVEL" load_levels_example(); - 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); @@ -60,15 +60,13 @@ int main(int, char *[]) // Loggers can store in a ring buffer all messages (including debug/trace) for later inspection. // When needed, call dump_backtrace() to see what happened: spdlog::enable_backtrace(10); // create ring buffer with capacity of 10 messages - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { spdlog::debug("Backtrace message {}", i); // not logged.. } // e.g. if some error happened: spdlog::dump_backtrace(); // log them now! - try - { + try { stdout_logger_example(); basic_example(); rotating_example(); @@ -100,8 +98,7 @@ int main(int, char *[]) } // Exceptions will only be thrown upon failed logger or sink construction (not during logging). - catch (const spdlog::spdlog_ex &ex) - { + catch (const spdlog::spdlog_ex &ex) { std::printf("Log initialization failed: %s\n", ex.what()); return 1; } @@ -109,8 +106,7 @@ int main(int, char *[]) #include "spdlog/sinks/stdout_color_sinks.h" // or #include "spdlog/sinks/stdout_sinks.h" if no colors needed. -void stdout_logger_example() -{ +void stdout_logger_example() { // Create color multi threaded logger. auto console = spdlog::stdout_color_mt("console"); // or for stderr: @@ -118,38 +114,35 @@ void stdout_logger_example() } #include "spdlog/sinks/basic_file_sink.h" -void basic_example() -{ +void basic_example() { // Create basic file logger (not rotated). auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt", true); } #include "spdlog/sinks/rotating_file_sink.h" -void rotating_example() -{ +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); + 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() -{ +void daily_example() { // Create a daily logger - a new file is created every day on 2:30am. auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); } #include "spdlog/sinks/callback_sink.h" -void callback_example() -{ +void callback_example() { // Create the logger - auto logger = spdlog::callback_logger_mt("custom_callback_logger", [](const spdlog::details::log_msg & /*msg*/) { - // do what you need to do with msg - }); + auto logger = spdlog::callback_logger_mt("custom_callback_logger", + [](const spdlog::details::log_msg & /*msg*/) { + // do what you need to do with msg + }); } #include "spdlog/cfg/env.h" -void load_levels_example() -{ +void load_levels_example() { // Set the log level to "info" and mylogger to "trace": // SPDLOG_LEVEL=info,mylogger=trace && ./example spdlog::cfg::load_env_levels(); @@ -160,16 +153,17 @@ void load_levels_example() } #include "spdlog/async.h" -void async_example() -{ +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"); + 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"); + // auto async_file = + // spdlog::create_async("async_file_logger", + // "logs/async_log.txt"); - for (int i = 1; i < 101; ++i) - { + for (int i = 1; i < 101; ++i) { async_file->info("Async message #{}", i); } } @@ -184,16 +178,15 @@ void async_example() // {:n} - don't split the output to lines. #if !defined SPDLOG_USE_STD_FORMAT || defined(_MSC_VER) -# include "spdlog/fmt/bin_to_hex.h" -void binary_example() -{ + #include "spdlog/fmt/bin_to_hex.h" +void binary_example() { std::vector buf(80); - for (int i = 0; i < 80; i++) - { + 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)); + 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)); @@ -202,17 +195,15 @@ void binary_example() // logger->info("hexdump style, 20 chars per line {:a}", spdlog::to_hex(buf, 20)); } #else -void binary_example() -{ +void binary_example() { // not supported with std::format yet } #endif // Log a vector of numbers #ifndef SPDLOG_USE_STD_FORMAT -# include "spdlog/fmt/ranges.h" -void vector_example() -{ + #include "spdlog/fmt/ranges.h" +void vector_example() { std::vector vec = {1, 2, 3}; spdlog::info("Vector example: {}", vec); } @@ -225,8 +216,7 @@ void vector_example() {} // Compile time log levels. // define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE) -void trace_example() -{ +void trace_example() { // trace from default logger SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23); // debug from default logger @@ -240,16 +230,14 @@ void trace_example() // stopwatch example #include "spdlog/stopwatch.h" #include -void stopwatch_example() -{ +void stopwatch_example() { spdlog::stopwatch sw; std::this_thread::sleep_for(std::chrono::milliseconds(123)); spdlog::info("Stopwatch: {} seconds", sw); } #include "spdlog/sinks/udp_sink.h" -void udp_example() -{ +void udp_example() { spdlog::sinks::udp_sink_config cfg("127.0.0.1", 11091); auto my_logger = spdlog::udp_logger_mt("udplog", cfg); my_logger->set_level(spdlog::level::debug); @@ -257,13 +245,13 @@ void udp_example() } // A logger with multiple sinks (stdout and file) - each with a different format and log level. -void multi_sink_example() -{ +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); + 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}); @@ -273,51 +261,43 @@ void multi_sink_example() } // User defined types logging -struct my_type -{ +struct my_type { int i = 0; explicit my_type(int i) : i(i){}; }; #ifndef SPDLOG_USE_STD_FORMAT // when using fmtlib -template<> -struct fmt::formatter : fmt::formatter -{ - auto format(my_type my, format_context &ctx) -> decltype(ctx.out()) - { +template <> +struct fmt::formatter : fmt::formatter { + auto format(my_type my, format_context &ctx) -> decltype(ctx.out()) { return fmt::format_to(ctx.out(), "[my_type i={}]", my.i); } }; #else // when using std::format -template<> -struct std::formatter : std::formatter -{ - auto format(my_type my, format_context &ctx) const -> decltype(ctx.out()) - { +template <> +struct std::formatter : std::formatter { + auto format(my_type my, format_context &ctx) const -> decltype(ctx.out()) { return format_to(ctx.out(), "[my_type i={}]", my.i); } }; #endif -void user_defined_example() -{ - spdlog::info("user defined type: {}", my_type(14)); -} +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() -{ +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()); }); + 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() -{ + #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."); @@ -326,9 +306,8 @@ void syslog_example() // Android example. #if defined(__ANDROID__) -# include "spdlog/sinks/android_sink.h" -void android_example() -{ + #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."); @@ -338,36 +317,34 @@ void android_example() // Log patterns can contain custom flags. // this will add custom flag '%*' which will be bound to a instance #include "spdlog/pattern_formatter.h" -class my_formatter_flag : public spdlog::custom_flag_formatter -{ +class my_formatter_flag : public spdlog::custom_flag_formatter { public: - void format(const spdlog::details::log_msg &, const std::tm &, spdlog::memory_buf_t &dest) override - { + void + format(const spdlog::details::log_msg &, const std::tm &, spdlog::memory_buf_t &dest) override { std::string some_txt = "custom-flag"; dest.append(some_txt.data(), some_txt.data() + some_txt.size()); } - std::unique_ptr clone() const override - { + std::unique_ptr clone() const override { return spdlog::details::make_unique(); } }; -void custom_flags_example() -{ +void custom_flags_example() { using spdlog::details::make_unique; // for pre c++14 auto formatter = make_unique(); formatter->add_flag('*').set_pattern("[%n] [%*] [%^%l%$] %v"); - // set the new formatter using spdlog::set_formatter(formatter) or logger->set_formatter(formatter) - // spdlog::set_formatter(std::move(formatter)); + // set the new formatter using spdlog::set_formatter(formatter) or + // logger->set_formatter(formatter) spdlog::set_formatter(std::move(formatter)); } -void file_events_example() -{ +void file_events_example() { // pass the spdlog::file_event_handlers to file sinks for open/close log file notifications spdlog::file_event_handlers handlers; - handlers.before_open = [](spdlog::filename_t filename) { spdlog::info("Before opening {}", filename); }; + handlers.before_open = [](spdlog::filename_t filename) { + spdlog::info("Before opening {}", filename); + }; handlers.after_open = [](spdlog::filename_t filename, std::FILE *fstream) { spdlog::info("After opening {}", filename); fputs("After opening\n", fstream); @@ -376,18 +353,21 @@ void file_events_example() spdlog::info("Before closing {}", filename); fputs("Before closing\n", fstream); }; - handlers.after_close = [](spdlog::filename_t filename) { spdlog::info("After closing {}", filename); }; - auto file_sink = std::make_shared("logs/events-sample.txt", true, handlers); + handlers.after_close = [](spdlog::filename_t filename) { + spdlog::info("After closing {}", filename); + }; + auto file_sink = std::make_shared("logs/events-sample.txt", + true, handlers); spdlog::logger my_logger("some_logger", file_sink); my_logger.info("Some log line"); } -void replace_default_logger_example() -{ +void replace_default_logger_example() { // store the old logger so we don't break other examples. auto old_logger = spdlog::default_logger(); - auto new_logger = spdlog::basic_logger_mt("new_default_logger", "logs/new-default-log.txt", true); + auto new_logger = + spdlog::basic_logger_mt("new_default_logger", "logs/new-default-log.txt", true); spdlog::set_default_logger(new_logger); spdlog::set_level(spdlog::level::info); spdlog::debug("This message should not be displayed!"); diff --git a/include/spdlog/async.h b/include/spdlog/async.h index cdbbfc43..76b93ed9 100644 --- a/include/spdlog/async.h +++ b/include/spdlog/async.h @@ -48,8 +48,8 @@ struct async_factory_impl { } auto sink = std::make_shared(std::forward(args)...); - auto new_logger = - std::make_shared(std::move(logger_name), std::move(sink), std::move(tp), OverflowPolicy); + auto new_logger = std::make_shared(std::move(logger_name), std::move(sink), + std::move(tp), OverflowPolicy); registry_inst.initialize_logger(new_logger); return new_logger; } @@ -59,13 +59,17 @@ using async_factory = async_factory_impl; using async_factory_nonblock = async_factory_impl; template -inline std::shared_ptr create_async(std::string logger_name, SinkArgs &&...sink_args) { - return async_factory::create(std::move(logger_name), std::forward(sink_args)...); +inline std::shared_ptr create_async(std::string logger_name, + SinkArgs &&...sink_args) { + return async_factory::create(std::move(logger_name), + std::forward(sink_args)...); } template -inline std::shared_ptr create_async_nb(std::string logger_name, SinkArgs &&...sink_args) { - return async_factory_nonblock::create(std::move(logger_name), std::forward(sink_args)...); +inline std::shared_ptr create_async_nb(std::string logger_name, + SinkArgs &&...sink_args) { + return async_factory_nonblock::create(std::move(logger_name), + std::forward(sink_args)...); } // set global thread pool. @@ -73,11 +77,13 @@ inline void init_thread_pool(size_t q_size, size_t thread_count, std::function on_thread_start, std::function on_thread_stop) { - auto tp = std::make_shared(q_size, thread_count, on_thread_start, on_thread_stop); + auto tp = std::make_shared(q_size, thread_count, on_thread_start, + on_thread_stop); details::registry::instance().set_tp(std::move(tp)); } -inline void init_thread_pool(size_t q_size, size_t thread_count, std::function on_thread_start) { +inline void +init_thread_pool(size_t q_size, size_t thread_count, std::function on_thread_start) { init_thread_pool(q_size, thread_count, on_thread_start, [] {}); } @@ -87,5 +93,7 @@ inline void init_thread_pool(size_t q_size, size_t thread_count) { } // get the global thread pool. -inline std::shared_ptr thread_pool() { return details::registry::instance().get_tp(); } +inline std::shared_ptr thread_pool() { + return details::registry::instance().get_tp(); +} } // namespace spdlog diff --git a/include/spdlog/async_logger-inl.h b/include/spdlog/async_logger-inl.h index edce9d68..1e794798 100644 --- a/include/spdlog/async_logger-inl.h +++ b/include/spdlog/async_logger-inl.h @@ -17,17 +17,23 @@ 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) {} + : 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) {} + : async_logger( + std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy) {} // send the log message to the thread pool SPDLOG_INLINE void spdlog::async_logger::sink_it_(const details::log_msg &msg){ - SPDLOG_TRY{if (auto pool_ptr = thread_pool_.lock()){pool_ptr->post_log(shared_from_this(), msg, overflow_policy_); + SPDLOG_TRY{if (auto pool_ptr = thread_pool_.lock()){ + pool_ptr->post_log(shared_from_this(), msg, overflow_policy_); } else { throw_spdlog_ex("async log: thread pool doesn't exist anymore"); @@ -38,7 +44,8 @@ SPDLOG_LOGGER_CATCH(msg.source) // send flush request to the thread pool SPDLOG_INLINE void spdlog::async_logger::flush_(){ - SPDLOG_TRY{if (auto pool_ptr = thread_pool_.lock()){pool_ptr->post_flush(shared_from_this(), overflow_policy_); + SPDLOG_TRY{if (auto pool_ptr = thread_pool_.lock()){ + pool_ptr->post_flush(shared_from_this(), overflow_policy_); } else { throw_spdlog_ex("async flush: thread pool doesn't exist anymore"); diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index 2e4f2706..c162f071 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -30,7 +30,8 @@ namespace details { class thread_pool; } -class SPDLOG_API async_logger final : public std::enable_shared_from_this, public logger { +class SPDLOG_API async_logger final : public std::enable_shared_from_this, + public logger { friend class details::thread_pool; public: @@ -40,9 +41,9 @@ public: It end, std::weak_ptr tp, async_overflow_policy overflow_policy = async_overflow_policy::block) - : logger(std::move(logger_name), begin, end), - thread_pool_(std::move(tp)), - overflow_policy_(overflow_policy) {} + : logger(std::move(logger_name), begin, end) + , thread_pool_(std::move(tp)) + , overflow_policy_(overflow_policy) {} async_logger(std::string logger_name, sinks_init_list sinks_list, diff --git a/include/spdlog/cfg/argv.h b/include/spdlog/cfg/argv.h index 4c3bac19..8610e3ab 100644 --- a/include/spdlog/cfg/argv.h +++ b/include/spdlog/cfg/argv.h @@ -32,7 +32,9 @@ inline void load_argv_levels(int argc, const char **argv) { } } -inline void load_argv_levels(int argc, char **argv) { load_argv_levels(argc, const_cast(argv)); } +inline void load_argv_levels(int argc, char **argv) { + load_argv_levels(argc, const_cast(argv)); +} } // namespace cfg } // namespace spdlog diff --git a/include/spdlog/cfg/helpers-inl.h b/include/spdlog/cfg/helpers-inl.h index 95dce058..9ee5e66e 100644 --- a/include/spdlog/cfg/helpers-inl.h +++ b/include/spdlog/cfg/helpers-inl.h @@ -22,8 +22,9 @@ namespace helpers { // inplace convert to lowercase inline std::string &to_lower_(std::string &str) { - std::transform(str.begin(), str.end(), str.begin(), - [](char ch) { return static_cast((ch >= 'A' && ch <= 'Z') ? ch + ('a' - 'A') : ch); }); + std::transform(str.begin(), str.end(), str.begin(), [](char ch) { + return static_cast((ch >= 'A' && ch <= 'Z') ? ch + ('a' - 'A') : ch); + }); return str; } @@ -97,7 +98,8 @@ SPDLOG_INLINE void load_levels(const std::string &input) { } } - details::registry::instance().set_levels(std::move(levels), global_level_found ? &global_level : nullptr); + details::registry::instance().set_levels(std::move(levels), + global_level_found ? &global_level : nullptr); } } // namespace helpers diff --git a/include/spdlog/common-inl.h b/include/spdlog/common-inl.h index 8c9b255e..3865245b 100644 --- a/include/spdlog/common-inl.h +++ b/include/spdlog/common-inl.h @@ -24,7 +24,9 @@ SPDLOG_INLINE const string_view_t &to_string_view(spdlog::level::level_enum l) S return level_string_views[l]; } -SPDLOG_INLINE const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT { return short_level_names[l]; } +SPDLOG_INLINE const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT { + return short_level_names[l]; +} SPDLOG_INLINE spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT { auto it = std::find(std::begin(level_string_views), std::end(level_string_views), name); @@ -57,7 +59,9 @@ SPDLOG_INLINE spdlog_ex::spdlog_ex(const std::string &msg, int last_errno) { SPDLOG_INLINE const char *spdlog_ex::what() const SPDLOG_NOEXCEPT { return msg_.c_str(); } -SPDLOG_INLINE void throw_spdlog_ex(const std::string &msg, int last_errno) { SPDLOG_THROW(spdlog_ex(msg, last_errno)); } +SPDLOG_INLINE void throw_spdlog_ex(const std::string &msg, int last_errno) { + SPDLOG_THROW(spdlog_ex(msg, last_errno)); +} SPDLOG_INLINE void throw_spdlog_ex(std::string msg) { SPDLOG_THROW(spdlog_ex(std::move(msg))); } diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 6dd6311a..76b012cd 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -49,7 +49,8 @@ #include -#if !defined(SPDLOG_USE_STD_FORMAT) && FMT_VERSION >= 80000 // backward compatibility with fmt versions older than 8 +#if !defined(SPDLOG_USE_STD_FORMAT) && \ + FMT_VERSION >= 80000 // backward compatibility with fmt versions older than 8 #define SPDLOG_FMT_RUNTIME(format_string) fmt::runtime(format_string) #define SPDLOG_FMT_STRING(format_string) FMT_STRING(format_string) #if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) @@ -180,14 +181,15 @@ using fmt_runtime_string = fmt::runtime_format_string; using fmt_runtime_string = fmt::basic_runtime; #endif -// clang doesn't like SFINAE disabled constructor in std::is_convertible<> so have to repeat the condition from -// basic_format_string here, in addition, fmt::basic_runtime is only convertible to basic_format_string but -// not basic_string_view +// clang doesn't like SFINAE disabled constructor in std::is_convertible<> so have to repeat the +// condition from basic_format_string here, in addition, fmt::basic_runtime is only +// convertible to basic_format_string but not basic_string_view template struct is_convertible_to_basic_format_string : std::integral_constant>::value || - std::is_same, fmt_runtime_string>::value> {}; + std::is_same, fmt_runtime_string>::value> { +}; #if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) using wstring_view_t = fmt::basic_string_view; @@ -251,10 +253,11 @@ enum level_enum : int { #define SPDLOG_LEVEL_NAME_OFF spdlog::string_view_t("off", 3) #if !defined(SPDLOG_LEVEL_NAMES) - #define SPDLOG_LEVEL_NAMES \ - { \ - SPDLOG_LEVEL_NAME_TRACE, SPDLOG_LEVEL_NAME_DEBUG, SPDLOG_LEVEL_NAME_INFO, SPDLOG_LEVEL_NAME_WARNING, \ - SPDLOG_LEVEL_NAME_ERROR, SPDLOG_LEVEL_NAME_CRITICAL, SPDLOG_LEVEL_NAME_OFF \ + #define SPDLOG_LEVEL_NAMES \ + { \ + SPDLOG_LEVEL_NAME_TRACE, SPDLOG_LEVEL_NAME_DEBUG, SPDLOG_LEVEL_NAME_INFO, \ + SPDLOG_LEVEL_NAME_WARNING, SPDLOG_LEVEL_NAME_ERROR, SPDLOG_LEVEL_NAME_CRITICAL, \ + SPDLOG_LEVEL_NAME_OFF \ } #endif @@ -303,9 +306,9 @@ private: struct source_loc { SPDLOG_CONSTEXPR source_loc() = default; SPDLOG_CONSTEXPR source_loc(const char *filename_in, int line_in, const char *funcname_in) - : filename{filename_in}, - line{line_in}, - funcname{funcname_in} {} + : filename{filename_in} + , line{line_in} + , funcname{funcname_in} {} SPDLOG_CONSTEXPR bool empty() const SPDLOG_NOEXCEPT { return line == 0; } const char *filename{nullptr}; @@ -315,10 +318,10 @@ struct source_loc { struct file_event_handlers { file_event_handlers() - : before_open(nullptr), - after_open(nullptr), - before_close(nullptr), - after_close(nullptr) {} + : before_open(nullptr) + , after_open(nullptr) + , before_close(nullptr) + , after_close(nullptr) {} std::function before_open; std::function after_open; @@ -330,18 +333,26 @@ namespace details { // to_string_view -SPDLOG_CONSTEXPR_FUNC spdlog::string_view_t to_string_view(const memory_buf_t &buf) SPDLOG_NOEXCEPT { +SPDLOG_CONSTEXPR_FUNC spdlog::string_view_t +to_string_view(const memory_buf_t &buf) SPDLOG_NOEXCEPT { return spdlog::string_view_t{buf.data(), buf.size()}; } -SPDLOG_CONSTEXPR_FUNC spdlog::string_view_t to_string_view(spdlog::string_view_t str) SPDLOG_NOEXCEPT { return str; } +SPDLOG_CONSTEXPR_FUNC spdlog::string_view_t +to_string_view(spdlog::string_view_t str) SPDLOG_NOEXCEPT { + return str; +} #if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) -SPDLOG_CONSTEXPR_FUNC spdlog::wstring_view_t to_string_view(const wmemory_buf_t &buf) SPDLOG_NOEXCEPT { +SPDLOG_CONSTEXPR_FUNC spdlog::wstring_view_t +to_string_view(const wmemory_buf_t &buf) SPDLOG_NOEXCEPT { return spdlog::wstring_view_t{buf.data(), buf.size()}; } -SPDLOG_CONSTEXPR_FUNC spdlog::wstring_view_t to_string_view(spdlog::wstring_view_t str) SPDLOG_NOEXCEPT { return str; } +SPDLOG_CONSTEXPR_FUNC spdlog::wstring_view_t +to_string_view(spdlog::wstring_view_t str) SPDLOG_NOEXCEPT { + return str; +} #endif #ifndef SPDLOG_USE_STD_FORMAT diff --git a/include/spdlog/details/circular_q.h b/include/spdlog/details/circular_q.h index 76ac1f1c..e7d68652 100644 --- a/include/spdlog/details/circular_q.h +++ b/include/spdlog/details/circular_q.h @@ -25,8 +25,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_) {} + , v_(max_items_) {} circular_q(const circular_q &) = default; circular_q &operator=(const circular_q &) = default; diff --git a/include/spdlog/details/file_helper-inl.h b/include/spdlog/details/file_helper-inl.h index d1e15751..b3474e5e 100644 --- a/include/spdlog/details/file_helper-inl.h +++ b/include/spdlog/details/file_helper-inl.h @@ -59,7 +59,8 @@ SPDLOG_INLINE void file_helper::open(const filename_t &fname, bool truncate) { details::os::sleep_for_millis(open_interval_); } - throw_spdlog_ex("Failed opening file " + os::filename_to_str(filename_) + " for writing", errno); + throw_spdlog_ex("Failed opening file " + os::filename_to_str(filename_) + " for writing", + errno); } SPDLOG_INLINE void file_helper::reopen(bool truncate) { @@ -126,7 +127,8 @@ SPDLOG_INLINE const filename_t &file_helper::filename() const { return filename_ // ".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) { +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 diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index 1d2fcedb..5dd62e14 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -68,7 +68,8 @@ SPDLOG_CONSTEXPR_FUNC unsigned int count_digits_fallback(T n) { template inline unsigned int count_digits(T n) { - using count_type = typename std::conditional<(sizeof(T) > sizeof(uint32_t)), uint64_t, uint32_t>::type; + using count_type = + typename std::conditional<(sizeof(T) > sizeof(uint32_t)), uint64_t, uint32_t>::type; #ifdef SPDLOG_USE_STD_FORMAT return count_digits_fallback(static_cast(n)); #else diff --git a/include/spdlog/details/log_msg-inl.h b/include/spdlog/details/log_msg-inl.h index c301b1fa..7e446395 100644 --- a/include/spdlog/details/log_msg-inl.h +++ b/include/spdlog/details/log_msg-inl.h @@ -17,16 +17,14 @@ SPDLOG_INLINE log_msg::log_msg(spdlog::log_clock::time_point log_time, string_view_t a_logger_name, spdlog::level::level_enum lvl, spdlog::string_view_t msg) - : logger_name(a_logger_name), - level(lvl), - time(log_time) + : logger_name(a_logger_name) + , level(lvl) + , time(log_time) #ifndef SPDLOG_NO_THREAD_ID - , - thread_id(os::thread_id()) + , thread_id(os::thread_id()) #endif - , - source(loc), - payload(msg) { + , source(loc) + , payload(msg) { } SPDLOG_INLINE log_msg::log_msg(spdlog::source_loc loc, @@ -35,7 +33,9 @@ SPDLOG_INLINE log_msg::log_msg(spdlog::source_loc loc, spdlog::string_view_t msg) : log_msg(os::now(), loc, a_logger_name, lvl, msg) {} -SPDLOG_INLINE log_msg::log_msg(string_view_t a_logger_name, spdlog::level::level_enum lvl, spdlog::string_view_t msg) +SPDLOG_INLINE log_msg::log_msg(string_view_t a_logger_name, + spdlog::level::level_enum lvl, + spdlog::string_view_t msg) : log_msg(os::now(), source_loc{}, a_logger_name, lvl, msg) {} } // namespace details diff --git a/include/spdlog/details/log_msg_buffer-inl.h b/include/spdlog/details/log_msg_buffer-inl.h index fe39b638..0441391c 100644 --- a/include/spdlog/details/log_msg_buffer-inl.h +++ b/include/spdlog/details/log_msg_buffer-inl.h @@ -24,8 +24,9 @@ SPDLOG_INLINE log_msg_buffer::log_msg_buffer(const log_msg_buffer &other) update_string_views(); } -SPDLOG_INLINE log_msg_buffer::log_msg_buffer(log_msg_buffer &&other) SPDLOG_NOEXCEPT : log_msg{other}, - buffer{std::move(other.buffer)} { +SPDLOG_INLINE log_msg_buffer::log_msg_buffer(log_msg_buffer &&other) SPDLOG_NOEXCEPT + : log_msg{other}, + buffer{std::move(other.buffer)} { update_string_views(); } diff --git a/include/spdlog/details/os-inl.h b/include/spdlog/details/os-inl.h index 9500536e..76b8414b 100644 --- a/include/spdlog/details/os-inl.h +++ b/include/spdlog/details/os-inl.h @@ -79,8 +79,8 @@ SPDLOG_INLINE spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT { 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::chrono::duration_cast( + std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec))); #else return log_clock::now(); @@ -140,7 +140,8 @@ SPDLOG_INLINE bool fopen_s(FILE **fp, const filename_t &filename, const filename #else // unix #if defined(SPDLOG_PREVENT_CHILD_FD) const int mode_flag = mode == SPDLOG_FILENAME_T("ab") ? O_APPEND : O_TRUNC; - const int fd = ::open((filename.c_str()), O_CREAT | O_WRONLY | O_CLOEXEC | mode_flag, mode_t(0644)); + const int fd = + ::open((filename.c_str()), O_CREAT | O_WRONLY | O_CLOEXEC | mode_flag, mode_t(0644)); if (fd == -1) { return true; } @@ -269,7 +270,8 @@ SPDLOG_INLINE int utc_minutes_offset(const std::tm &tm) { return offset; #else - #if defined(sun) || defined(__sun) || defined(_AIX) || (defined(__NEWLIB__) && !defined(__TM_GMTOFF)) || \ + #if defined(sun) || defined(__sun) || defined(_AIX) || \ + (defined(__NEWLIB__) && !defined(__TM_GMTOFF)) || \ (!defined(_BSD_SOURCE) && !defined(_GNU_SOURCE)) // 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris struct helper { @@ -407,17 +409,18 @@ SPDLOG_INLINE bool is_color_terminal() SPDLOG_NOEXCEPT { return true; } - static constexpr std::array terms = {{"ansi", "color", "console", "cygwin", "gnome", - "konsole", "kterm", "linux", "msys", "putty", "rxvt", - "screen", "vt100", "xterm", "alacritty", "vt102"}}; + static constexpr std::array terms = { + {"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", + "putty", "rxvt", "screen", "vt100", "xterm", "alacritty", "vt102"}}; const char *env_term_p = std::getenv("TERM"); if (env_term_p == nullptr) { return false; } - return std::any_of(terms.begin(), terms.end(), - [&](const char *term) { return std::strstr(env_term_p, term) != nullptr; }); + return std::any_of(terms.begin(), terms.end(), [&](const char *term) { + return std::strstr(env_term_p, term) != nullptr; + }); }(); return result; @@ -449,12 +452,14 @@ SPDLOG_INLINE void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target) { int result_size = static_cast(target.capacity()); if ((wstr_size + 1) * 2 > result_size) { - result_size = ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, NULL, 0, NULL, NULL); + result_size = + ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, NULL, 0, NULL, NULL); } if (result_size > 0) { target.resize(result_size); - result_size = ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, target.data(), result_size, NULL, NULL); + result_size = ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, target.data(), + result_size, NULL, NULL); if (result_size > 0) { target.resize(result_size); @@ -462,7 +467,8 @@ SPDLOG_INLINE void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target) { } } - throw_spdlog_ex(fmt_lib::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError())); + throw_spdlog_ex( + fmt_lib::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError())); } SPDLOG_INLINE void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target) { @@ -477,21 +483,24 @@ SPDLOG_INLINE void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target) { } // find the size to allocate for the result buffer - int result_size = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.data(), str_size, NULL, 0); + int result_size = + ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.data(), str_size, NULL, 0); if (result_size > 0) { target.resize(result_size); - result_size = - ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.data(), str_size, target.data(), result_size); + result_size = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.data(), str_size, + target.data(), result_size); if (result_size > 0) { assert(result_size == target.size()); return; } } - throw_spdlog_ex(fmt_lib::format("MultiByteToWideChar failed. Last error: {}", ::GetLastError())); + throw_spdlog_ex( + fmt_lib::format("MultiByteToWideChar failed. Last error: {}", ::GetLastError())); } -#endif // (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32) +#endif // (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && + // defined(_WIN32) // return true on success static SPDLOG_INLINE bool mkdir_(const filename_t &path) { diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 52a2a053..898b5464 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -41,7 +41,8 @@ SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL; #endif SPDLOG_CONSTEXPR static const char folder_seps[] = SPDLOG_FOLDER_SEPS; -SPDLOG_CONSTEXPR static const filename_t::value_type folder_seps_filename[] = SPDLOG_FILENAME_T(SPDLOG_FOLDER_SEPS); +SPDLOG_CONSTEXPR static const filename_t::value_type folder_seps_filename[] = + SPDLOG_FILENAME_T(SPDLOG_FOLDER_SEPS); // fopen_s on non windows for writing SPDLOG_API bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode); diff --git a/include/spdlog/details/periodic_worker.h b/include/spdlog/details/periodic_worker.h index c59e156f..10ba93c6 100644 --- a/include/spdlog/details/periodic_worker.h +++ b/include/spdlog/details/periodic_worker.h @@ -7,7 +7,8 @@ // // RAII over the owned thread: // creates the thread on construction. -// stops and joins the thread on destruction (if the thread is executing a callback, wait for it to finish first). +// stops and joins the thread on destruction (if the thread is executing a callback, wait for it +// to finish first). #include #include @@ -20,7 +21,8 @@ namespace details { class SPDLOG_API periodic_worker { public: template - periodic_worker(const std::function &callback_fun, std::chrono::duration interval) { + periodic_worker(const std::function &callback_fun, + std::chrono::duration interval) { active_ = (interval > std::chrono::duration::zero()); if (!active_) { return; diff --git a/include/spdlog/details/registry-inl.h b/include/spdlog/details/registry-inl.h index ad14d636..a0a56e13 100644 --- a/include/spdlog/details/registry-inl.h +++ b/include/spdlog/details/registry-inl.h @@ -170,7 +170,8 @@ SPDLOG_INLINE void registry::set_error_handler(err_handler handler) { err_handler_ = std::move(handler); } -SPDLOG_INLINE 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_) { fun(l.second); diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 4b8e012d..17cc7218 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -38,7 +38,8 @@ public: // 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. + // e.g do not call set_default_logger() from one thread while calling spdlog::info() from + // another. logger *get_default_raw(); // set default logger. diff --git a/include/spdlog/details/tcp_client-windows.h b/include/spdlog/details/tcp_client-windows.h index 70bae0e4..e74efa09 100644 --- a/include/spdlog/details/tcp_client-windows.h +++ b/include/spdlog/details/tcp_client-windows.h @@ -34,8 +34,9 @@ class tcp_client { static void throw_winsock_error_(const std::string &msg, int last_error) { char buf[512]; - ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, (sizeof(buf) / sizeof(char)), NULL); + ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, + last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, + (sizeof(buf) / sizeof(char)), NULL); throw_spdlog_ex(fmt_lib::format("tcp_sink - {}: {}", msg, buf)); } @@ -104,7 +105,8 @@ public: // set TCP_NODELAY int enable_flag = 1; - ::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&enable_flag), sizeof(enable_flag)); + ::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&enable_flag), + sizeof(enable_flag)); } // Send exactly n_bytes of the given data. @@ -113,7 +115,8 @@ public: size_t bytes_sent = 0; while (bytes_sent < n_bytes) { const int send_flags = 0; - auto write_result = ::send(socket_, data + bytes_sent, (int)(n_bytes - bytes_sent), send_flags); + auto write_result = + ::send(socket_, data + bytes_sent, (int)(n_bytes - bytes_sent), send_flags); if (write_result == SOCKET_ERROR) { int last_error = ::WSAGetLastError(); close(); diff --git a/include/spdlog/details/tcp_client.h b/include/spdlog/details/tcp_client.h index 437bbf18..c323d78e 100644 --- a/include/spdlog/details/tcp_client.h +++ b/include/spdlog/details/tcp_client.h @@ -84,11 +84,13 @@ public: // set TCP_NODELAY int enable_flag = 1; - ::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&enable_flag), sizeof(enable_flag)); + ::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&enable_flag), + sizeof(enable_flag)); // prevent sigpipe on systems where MSG_NOSIGNAL is not available #if defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL) - ::setsockopt(socket_, SOL_SOCKET, SO_NOSIGPIPE, reinterpret_cast(&enable_flag), sizeof(enable_flag)); + ::setsockopt(socket_, SOL_SOCKET, SO_NOSIGPIPE, reinterpret_cast(&enable_flag), + sizeof(enable_flag)); #endif #if !defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL) @@ -106,7 +108,8 @@ public: #else const int send_flags = 0; #endif - auto write_result = ::send(socket_, data + bytes_sent, n_bytes - bytes_sent, send_flags); + auto write_result = + ::send(socket_, data + bytes_sent, n_bytes - bytes_sent, send_flags); if (write_result < 0) { close(); throw_spdlog_ex("write(2) failed", errno); diff --git a/include/spdlog/details/thread_pool-inl.h b/include/spdlog/details/thread_pool-inl.h index afc20eb2..b1c21dbb 100644 --- a/include/spdlog/details/thread_pool-inl.h +++ b/include/spdlog/details/thread_pool-inl.h @@ -31,7 +31,9 @@ SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, } } -SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n, std::function on_thread_start) +SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, + size_t threads_n, + std::function on_thread_start) : thread_pool(q_max_items, threads_n, on_thread_start, [] {}) {} SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n) @@ -59,7 +61,8 @@ void SPDLOG_INLINE thread_pool::post_log(async_logger_ptr &&worker_ptr, post_async_msg_(std::move(async_m), overflow_policy); } -void SPDLOG_INLINE thread_pool::post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy overflow_policy) { +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); } @@ -73,7 +76,8 @@ void SPDLOG_INLINE thread_pool::reset_discard_counter() { q_.reset_discard_count size_t SPDLOG_INLINE thread_pool::queue_size() { return q_.size(); } -void SPDLOG_INLINE thread_pool::post_async_msg_(async_msg &&new_msg, async_overflow_policy overflow_policy) { +void SPDLOG_INLINE thread_pool::post_async_msg_(async_msg &&new_msg, + async_overflow_policy overflow_policy) { if (overflow_policy == async_overflow_policy::block) { q_.enqueue(std::move(new_msg)); } else if (overflow_policy == async_overflow_policy::overrun_oldest) { diff --git a/include/spdlog/details/thread_pool.h b/include/spdlog/details/thread_pool.h index 1c17b4ac..4aac7a86 100644 --- a/include/spdlog/details/thread_pool.h +++ b/include/spdlog/details/thread_pool.h @@ -37,9 +37,9 @@ struct async_msg : log_msg_buffer { // support for vs2013 move #if defined(_MSC_VER) && _MSC_VER <= 1800 async_msg(async_msg &&other) - : log_msg_buffer(std::move(other)), - msg_type(other.msg_type), - worker_ptr(std::move(other.worker_ptr)) {} + : log_msg_buffer(std::move(other)) + , msg_type(other.msg_type) + , worker_ptr(std::move(other.worker_ptr)) {} async_msg &operator=(async_msg &&other) { *static_cast(this) = std::move(other); @@ -54,14 +54,14 @@ struct async_msg : log_msg_buffer { // construct from log_msg with given type async_msg(async_logger_ptr &&worker, async_msg_type the_type, const details::log_msg &m) - : log_msg_buffer{m}, - msg_type{the_type}, - worker_ptr{std::move(worker)} {} + : log_msg_buffer{m} + , msg_type{the_type} + , worker_ptr{std::move(worker)} {} async_msg(async_logger_ptr &&worker, async_msg_type the_type) - : log_msg_buffer{}, - msg_type{the_type}, - worker_ptr{std::move(worker)} {} + : log_msg_buffer{} + , msg_type{the_type} + , worker_ptr{std::move(worker)} {} explicit async_msg(async_msg_type the_type) : async_msg{nullptr, the_type} {} @@ -85,7 +85,9 @@ public: thread_pool(const thread_pool &) = delete; thread_pool &operator=(thread_pool &&) = delete; - void post_log(async_logger_ptr &&worker_ptr, const details::log_msg &msg, async_overflow_policy overflow_policy); + void post_log(async_logger_ptr &&worker_ptr, + const details::log_msg &msg, + async_overflow_policy overflow_policy); void post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy overflow_policy); size_t overrun_counter(); void reset_overrun_counter(); diff --git a/include/spdlog/details/udp_client-windows.h b/include/spdlog/details/udp_client-windows.h index 9def2b46..4d9d96b5 100644 --- a/include/spdlog/details/udp_client-windows.h +++ b/include/spdlog/details/udp_client-windows.h @@ -38,8 +38,9 @@ class udp_client { static void throw_winsock_error_(const std::string &msg, int last_error) { char buf[512]; - ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, (sizeof(buf) / sizeof(char)), NULL); + ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, + last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, + (sizeof(buf) / sizeof(char)), NULL); throw_spdlog_ex(fmt_lib::format("udp_sink - {}: {}", msg, buf)); } @@ -73,8 +74,8 @@ public: } int option_value = TX_BUFFER_SIZE; - if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast(&option_value), - sizeof(option_value)) < 0) { + if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, + reinterpret_cast(&option_value), sizeof(option_value)) < 0) { int last_error = ::WSAGetLastError(); cleanup_(); throw_winsock_error_("error: setsockopt(SO_SNDBUF) Failed!", last_error); @@ -87,7 +88,8 @@ public: void send(const char *data, size_t n_bytes) { socklen_t tolen = sizeof(struct sockaddr); - if (::sendto(socket_, data, static_cast(n_bytes), 0, (struct sockaddr *)&addr_, tolen) == -1) { + if (::sendto(socket_, data, static_cast(n_bytes), 0, (struct sockaddr *)&addr_, + tolen) == -1) { throw_spdlog_ex("sendto(2) failed", errno); } } diff --git a/include/spdlog/details/udp_client.h b/include/spdlog/details/udp_client.h index 6cf4b4a4..39e4b449 100644 --- a/include/spdlog/details/udp_client.h +++ b/include/spdlog/details/udp_client.h @@ -45,8 +45,8 @@ public: } int option_value = TX_BUFFER_SIZE; - if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast(&option_value), - sizeof(option_value)) < 0) { + if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, + reinterpret_cast(&option_value), sizeof(option_value)) < 0) { cleanup_(); throw_spdlog_ex("error: setsockopt(SO_SNDBUF) Failed!"); } @@ -71,7 +71,8 @@ public: void send(const char *data, size_t n_bytes) { ssize_t toslen = 0; socklen_t tolen = sizeof(struct sockaddr); - if ((toslen = ::sendto(socket_, data, n_bytes, 0, (struct sockaddr *)&sockAddr_, tolen)) == -1) { + if ((toslen = ::sendto(socket_, data, n_bytes, 0, (struct sockaddr *)&sockAddr_, tolen)) == + -1) { throw_spdlog_ex("sendto(2) failed", errno); } } diff --git a/include/spdlog/fmt/bin_to_hex.h b/include/spdlog/fmt/bin_to_hex.h index 9345abe3..222d6f7f 100644 --- a/include/spdlog/fmt/bin_to_hex.h +++ b/include/spdlog/fmt/bin_to_hex.h @@ -43,9 +43,9 @@ template class dump_info { public: dump_info(It range_begin, It range_end, size_t size_per_line) - : begin_(range_begin), - end_(range_end), - size_per_line_(size_per_line) {} + : begin_(range_begin) + , end_(range_end) + , size_per_line_(size_per_line) {} // do not use begin() and end() to avoid collision with fmt/ranges It get_begin() const { return begin_; } @@ -62,7 +62,8 @@ private: template inline details::dump_info to_hex(const Container &container, size_t size_per_line = 32) { - static_assert(sizeof(typename Container::value_type) == 1, "sizeof(Container::value_type) != 1"); + static_assert(sizeof(typename Container::value_type) == 1, + "sizeof(Container::value_type) != 1"); using Iter = typename Container::const_iterator; return details::dump_info(std::begin(container), std::end(container), size_per_line); } @@ -70,10 +71,11 @@ inline details::dump_info to_hex(const Conta #if __cpp_lib_span >= 202002L template -inline details::dump_info::iterator> to_hex(const std::span &container, - size_t size_per_line = 32) { +inline details::dump_info::iterator> +to_hex(const std::span &container, size_t size_per_line = 32) { using Container = std::span; - static_assert(sizeof(typename Container::value_type) == 1, "sizeof(Container::value_type) != 1"); + static_assert(sizeof(typename Container::value_type) == 1, + "sizeof(Container::value_type) != 1"); using Iter = typename Container::iterator; return details::dump_info(std::begin(container), std::end(container), size_per_line); } @@ -82,7 +84,8 @@ inline details::dump_info::iterator> to_hex(co // create dump_info from ranges template -inline details::dump_info to_hex(const It range_begin, const It range_end, size_t size_per_line = 32) { +inline details::dump_info +to_hex(const It range_begin, const It range_end, size_t size_per_line = 32) { return details::dump_info(range_begin, range_end, size_per_line); } @@ -155,7 +158,8 @@ struct formatter, char> { for (auto i = the_range.get_begin(); i != the_range.get_end(); i++) { auto ch = static_cast(*i); - if (put_newlines && (i == the_range.get_begin() || i - start_of_line >= size_per_line)) { + if (put_newlines && + (i == the_range.get_begin() || i - start_of_line >= size_per_line)) { if (show_ascii && i != the_range.get_begin()) { *inserter++ = delimiter; *inserter++ = delimiter; diff --git a/include/spdlog/fmt/std.h b/include/spdlog/fmt/std.h index 8891f031..47fc4026 100644 --- a/include/spdlog/fmt/std.h +++ b/include/spdlog/fmt/std.h @@ -5,8 +5,8 @@ #pragma once // -// include bundled or external copy of fmtlib's std support (for formatting e.g. std::filesystem::path, std::thread::id, -// std::monostate, std::variant, ...) +// include bundled or external copy of fmtlib's std support (for formatting e.g. +// std::filesystem::path, std::thread::id, std::monostate, std::variant, ...) // #if !defined(SPDLOG_USE_STD_FORMAT) diff --git a/include/spdlog/logger-inl.h b/include/spdlog/logger-inl.h index 5c796e88..e6ea2f9b 100644 --- a/include/spdlog/logger-inl.h +++ b/include/spdlog/logger-inl.h @@ -17,12 +17,12 @@ namespace spdlog { // public methods SPDLOG_INLINE logger::logger(const logger &other) - : name_(other.name_), - sinks_(other.sinks_), - level_(other.level_.load(std::memory_order_relaxed)), - flush_level_(other.flush_level_.load(std::memory_order_relaxed)), - custom_err_handler_(other.custom_err_handler_), - tracer_(other.tracer_) {} + : name_(other.name_) + , sinks_(other.sinks_) + , level_(other.level_.load(std::memory_order_relaxed)) + , flush_level_(other.flush_level_.load(std::memory_order_relaxed)) + , custom_err_handler_(other.custom_err_handler_) + , tracer_(other.tracer_) {} SPDLOG_INLINE logger::logger(logger &&other) SPDLOG_NOEXCEPT : name_(std::move(other.name_)), @@ -109,7 +109,9 @@ SPDLOG_INLINE const std::vector &logger::sinks() const { return sinks_ SPDLOG_INLINE std::vector &logger::sinks() { return sinks_; } // error handler -SPDLOG_INLINE void logger::set_error_handler(err_handler handler) { custom_err_handler_ = std::move(handler); } +SPDLOG_INLINE void logger::set_error_handler(err_handler handler) { + custom_err_handler_ = std::move(handler); +} // create new logger with same sinks and configuration. SPDLOG_INLINE std::shared_ptr logger::clone(std::string logger_name) { @@ -119,7 +121,8 @@ SPDLOG_INLINE std::shared_ptr logger::clone(std::string logger_name) { } // protected methods -SPDLOG_INLINE void logger::log_it_(const spdlog::details::log_msg &log_msg, bool log_enabled, bool traceback_enabled) { +SPDLOG_INLINE void +logger::log_it_(const spdlog::details::log_msg &log_msg, bool log_enabled, bool traceback_enabled) { if (log_enabled) { sink_it_(log_msg); } @@ -151,9 +154,11 @@ SPDLOG_INLINE void logger::flush_() { SPDLOG_INLINE void logger::dump_backtrace_() { using details::log_msg; if (tracer_.enabled() && !tracer_.empty()) { - sink_it_(log_msg{name(), level::info, "****************** Backtrace Start ******************"}); + sink_it_( + log_msg{name(), level::info, "****************** Backtrace Start ******************"}); tracer_.foreach_pop([this](const log_msg &msg) { this->sink_it_(msg); }); - sink_it_(log_msg{name(), level::info, "****************** Backtrace End ********************"}); + sink_it_( + log_msg{name(), level::info, "****************** Backtrace End ********************"}); } } @@ -181,10 +186,11 @@ SPDLOG_INLINE void logger::err_handler_(const std::string &msg) { char date_buf[64]; std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", &tm_time); #if defined(USING_R) && defined(R_R_H) // if in R environment - REprintf("[*** LOG ERROR #%04zu ***] [%s] [%s] %s\n", err_counter, date_buf, name().c_str(), msg.c_str()); + REprintf("[*** LOG ERROR #%04zu ***] [%s] [%s] %s\n", err_counter, date_buf, name().c_str(), + msg.c_str()); #else - std::fprintf(stderr, "[*** LOG ERROR #%04zu ***] [%s] [%s] %s\n", err_counter, date_buf, name().c_str(), - msg.c_str()); + std::fprintf(stderr, "[*** LOG ERROR #%04zu ***] [%s] [%s] %s\n", err_counter, date_buf, + name().c_str(), msg.c_str()); #endif } } diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index ab6443b4..3df6e321 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -28,18 +28,18 @@ #include #ifndef SPDLOG_NO_EXCEPTIONS - #define SPDLOG_LOGGER_CATCH(location) \ - catch (const std::exception &ex) { \ - if (location.filename) { \ - err_handler_( \ - fmt_lib::format(SPDLOG_FMT_STRING("{} [{}({})]"), ex.what(), location.filename, location.line)); \ - } else { \ - err_handler_(ex.what()); \ - } \ - } \ - catch (...) { \ - err_handler_("Rethrowing unknown exception in logger"); \ - throw; \ + #define SPDLOG_LOGGER_CATCH(location) \ + catch (const std::exception &ex) { \ + if (location.filename) { \ + err_handler_(fmt_lib::format(SPDLOG_FMT_STRING("{} [{}({})]"), ex.what(), \ + location.filename, location.line)); \ + } else { \ + err_handler_(ex.what()); \ + } \ + } \ + catch (...) { \ + err_handler_("Rethrowing unknown exception in logger"); \ + throw; \ } #else #define SPDLOG_LOGGER_CATCH(location) @@ -51,14 +51,14 @@ class SPDLOG_API logger { public: // Empty logger explicit logger(std::string name) - : name_(std::move(name)), - sinks_() {} + : name_(std::move(name)) + , sinks_() {} // Logger with range on sinks template logger(std::string name, It begin, It end) - : name_(std::move(name)), - sinks_(begin, end) {} + : name_(std::move(name)) + , sinks_(begin, end) {} // Logger with single sink logger(std::string name, sink_ptr single_sink) @@ -91,12 +91,15 @@ public: } // T cannot be statically converted to format string (including string_view/wstring_view) - template ::value, int>::type = 0> + template ::value, + int>::type = 0> void log(source_loc loc, level::level_enum lvl, const T &msg) { log(loc, lvl, "{}", msg); } - void log(log_clock::time_point log_time, source_loc loc, level::level_enum lvl, string_view_t msg) { + void + log(log_clock::time_point log_time, source_loc loc, level::level_enum lvl, string_view_t msg) { bool log_enabled = should_log(lvl); bool traceback_enabled = tracer_.enabled(); if (!log_enabled && !traceback_enabled) { @@ -161,7 +164,8 @@ public: log(source_loc{}, lvl, fmt, std::forward(args)...); } - void log(log_clock::time_point log_time, source_loc loc, level::level_enum lvl, wstring_view_t msg) { + void + log(log_clock::time_point log_time, source_loc loc, level::level_enum lvl, wstring_view_t msg) { bool log_enabled = should_log(lvl); bool traceback_enabled = tracer_.enabled(); if (!log_enabled && !traceback_enabled) { @@ -251,7 +255,9 @@ public: } // return true logging is enabled for the given level. - bool should_log(level::level_enum msg_level) const { return msg_level >= level_.load(std::memory_order_relaxed); } + bool should_log(level::level_enum msg_level) const { + return msg_level >= level_.load(std::memory_order_relaxed); + } // return true if backtrace logging is enabled. bool should_backtrace() const { return tracer_.enabled(); } diff --git a/include/spdlog/pattern_formatter-inl.h b/include/spdlog/pattern_formatter-inl.h index c71963dd..44b48617 100644 --- a/include/spdlog/pattern_formatter-inl.h +++ b/include/spdlog/pattern_formatter-inl.h @@ -37,8 +37,8 @@ namespace details { class scoped_padder { public: scoped_padder(size_t wrapped_size, const padding_info &padinfo, memory_buf_t &dest) - : padinfo_(padinfo), - dest_(dest) { + : padinfo_(padinfo) + , dest_(dest) { remaining_pad_ = static_cast(padinfo.width_) - static_cast(wrapped_size); if (remaining_pad_ <= 0) { return; @@ -71,7 +71,8 @@ public: private: void pad_it(long count) { - fmt_helper::append_string_view(string_view_t(spaces_.data(), static_cast(count)), dest_); + fmt_helper::append_string_view(string_view_t(spaces_.data(), static_cast(count)), + dest_); } const padding_info &padinfo_; @@ -81,7 +82,9 @@ private: }; struct null_scoped_padder { - null_scoped_padder(size_t /*wrapped_size*/, const padding_info & /*padinfo*/, memory_buf_t & /*dest*/) {} + null_scoped_padder(size_t /*wrapped_size*/, + const padding_info & /*padinfo*/, + memory_buf_t & /*dest*/) {} template static unsigned int count_digits(T /* number */) { @@ -188,8 +191,9 @@ public: }; // Full month name -static const std::array full_months{{"January", "February", "March", "April", "May", "June", "July", - "August", "September", "October", "November", "December"}}; +static const std::array full_months{{"January", "February", "March", "April", + "May", "June", "July", "August", "September", + "October", "November", "December"}}; template class B_formatter final : public flag_formatter { @@ -586,7 +590,9 @@ public: explicit ch_formatter(char ch) : ch_(ch) {} - void format(const details::log_msg &, const std::tm &, memory_buf_t &dest) override { dest.push_back(ch_); } + void format(const details::log_msg &, const std::tm &, memory_buf_t &dest) override { + dest.push_back(ch_); + } private: char ch_; @@ -643,8 +649,8 @@ public: size_t text_size; if (padinfo_.enabled()) { // calc text size for padding based on "filename:line" - text_size = - std::char_traits::length(msg.source.filename) + ScopedPadder::count_digits(msg.source.line) + 1; + text_size = std::char_traits::length(msg.source.filename) + + ScopedPadder::count_digits(msg.source.line) + 1; } else { text_size = 0; } @@ -668,7 +674,8 @@ public: ScopedPadder p(0, padinfo_, dest); return; } - size_t text_size = padinfo_.enabled() ? std::char_traits::length(msg.source.filename) : 0; + size_t text_size = + padinfo_.enabled() ? std::char_traits::length(msg.source.filename) : 0; ScopedPadder p(text_size, padinfo_, dest); fmt_helper::append_string_view(msg.source.filename, dest); } @@ -694,7 +701,8 @@ public: const std::reverse_iterator begin(filename + std::strlen(filename)); const std::reverse_iterator end(filename); - const auto it = std::find_first_of(begin, end, std::begin(os::folder_seps), std::end(os::folder_seps) - 1); + const auto it = std::find_first_of(begin, end, std::begin(os::folder_seps), + std::end(os::folder_seps) - 1); return it != end ? it.base() : filename; } } @@ -744,7 +752,8 @@ public: ScopedPadder p(0, padinfo_, dest); return; } - size_t text_size = padinfo_.enabled() ? std::char_traits::length(msg.source.funcname) : 0; + size_t text_size = + padinfo_.enabled() ? std::char_traits::length(msg.source.funcname) : 0; ScopedPadder p(text_size, padinfo_, dest); fmt_helper::append_string_view(msg.source.funcname, dest); } @@ -757,8 +766,8 @@ public: using DurationUnits = Units; explicit elapsed_formatter(padding_info padinfo) - : flag_formatter(padinfo), - last_message_time_(log_clock::now()) {} + : flag_formatter(padinfo) + , last_message_time_(log_clock::now()) {} void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override { auto delta = (std::max)(msg.time - last_message_time_, log_clock::duration::zero()); @@ -841,7 +850,8 @@ public: if (!msg.source.empty()) { dest.push_back('['); const char *filename = - details::short_filename_formatter::basename(msg.source.filename); + details::short_filename_formatter::basename( + msg.source.filename); fmt_helper::append_string_view(filename, dest); dest.push_back(':'); fmt_helper::append_int(msg.source.line, dest); @@ -863,23 +873,23 @@ SPDLOG_INLINE pattern_formatter::pattern_formatter(std::string pattern, pattern_time_type time_type, std::string eol, custom_flags custom_user_flags) - : pattern_(std::move(pattern)), - eol_(std::move(eol)), - pattern_time_type_(time_type), - need_localtime_(false), - last_log_secs_(0), - custom_handlers_(std::move(custom_user_flags)) { + : pattern_(std::move(pattern)) + , eol_(std::move(eol)) + , pattern_time_type_(time_type) + , need_localtime_(false) + , last_log_secs_(0) + , custom_handlers_(std::move(custom_user_flags)) { 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), - need_localtime_(true), - last_log_secs_(0) { + : pattern_("%+") + , eol_(std::move(eol)) + , pattern_time_type_(time_type) + , need_localtime_(true) + , last_log_secs_(0) { std::memset(&cached_tm_, 0, sizeof(cached_tm_)); formatters_.push_back(details::make_unique(details::padding_info{})); } @@ -901,7 +911,8 @@ SPDLOG_INLINE std::unique_ptr pattern_formatter::clone() const { SPDLOG_INLINE void pattern_formatter::format(const details::log_msg &msg, memory_buf_t &dest) { if (need_localtime_) { - const auto secs = std::chrono::duration_cast(msg.time.time_since_epoch()); + const 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; @@ -957,7 +968,8 @@ SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_i break; case 'L': // short level - formatters_.push_back(details::make_unique>(padding)); + formatters_.push_back( + details::make_unique>(padding)); break; case ('t'): // thread id @@ -1095,23 +1107,28 @@ SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_i break; case ('@'): // source location (filename:filenumber) - formatters_.push_back(details::make_unique>(padding)); + formatters_.push_back( + details::make_unique>(padding)); break; case ('s'): // short source filename - without directory name - formatters_.push_back(details::make_unique>(padding)); + formatters_.push_back( + details::make_unique>(padding)); break; case ('g'): // full source filename - formatters_.push_back(details::make_unique>(padding)); + formatters_.push_back( + details::make_unique>(padding)); break; case ('#'): // source line number - formatters_.push_back(details::make_unique>(padding)); + formatters_.push_back( + details::make_unique>(padding)); break; case ('!'): // source funcname - formatters_.push_back(details::make_unique>(padding)); + formatters_.push_back( + details::make_unique>(padding)); break; case ('%'): // % char @@ -1120,21 +1137,26 @@ SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_i case ('u'): // elapsed time since last log message in nanos formatters_.push_back( - details::make_unique>(padding)); + details::make_unique>( + padding)); break; case ('i'): // elapsed time since last log message in micros formatters_.push_back( - details::make_unique>(padding)); + details::make_unique>( + padding)); break; case ('o'): // elapsed time since last log message in millis formatters_.push_back( - details::make_unique>(padding)); + details::make_unique>( + padding)); break; case ('O'): // elapsed time since last log message in seconds - formatters_.push_back(details::make_unique>(padding)); + formatters_.push_back( + details::make_unique>( + padding)); break; default: // Unknown flag appears as is @@ -1145,12 +1167,13 @@ SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_i unknown_flag->add_ch(flag); formatters_.push_back((std::move(unknown_flag))); } - // fix issue #1617 (prev char was '!' and should have been treated as funcname flag instead of truncating flag) - // spdlog::set_pattern("[%10!] %v") => "[ main] some message" + // fix issue #1617 (prev char was '!' and should have been treated as funcname flag instead + // of truncating flag) spdlog::set_pattern("[%10!] %v") => "[ main] some message" // spdlog::set_pattern("[%3!!] %v") => "[mai] some message" else { padding.truncate_ = false; - formatters_.push_back(details::make_unique>(padding)); + formatters_.push_back( + details::make_unique>(padding)); unknown_flag->add_ch(flag); formatters_.push_back((std::move(unknown_flag))); } @@ -1162,8 +1185,9 @@ SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_i // Extract given pad spec (e.g. %8X, %=8X, %-8!X, %8!X, %=8!X, %-8!X, %+8!X) // 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) { +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_padder; const size_t max_width = 64; diff --git a/include/spdlog/pattern_formatter.h b/include/spdlog/pattern_formatter.h index fec78b1f..a718b606 100644 --- a/include/spdlog/pattern_formatter.h +++ b/include/spdlog/pattern_formatter.h @@ -25,10 +25,10 @@ struct padding_info { padding_info() = default; padding_info(size_t width, padding_info::pad_side side, bool truncate) - : width_(width), - side_(side), - truncate_(truncate), - enabled_(true) {} + : width_(width) + , side_(side) + , truncate_(truncate) + , enabled_(true) {} bool enabled() const { return enabled_; } size_t width_ = 0; @@ -43,7 +43,8 @@ public: : padinfo_(padinfo) {} flag_formatter() = default; virtual ~flag_formatter() = default; - virtual void format(const details::log_msg &msg, const std::tm &tm_time, memory_buf_t &dest) = 0; + virtual void + format(const details::log_msg &msg, const std::tm &tm_time, memory_buf_t &dest) = 0; protected: padding_info padinfo_; @@ -55,7 +56,9 @@ class SPDLOG_API custom_flag_formatter : public details::flag_formatter { public: virtual std::unique_ptr clone() const = 0; - void set_padding_info(const details::padding_info &padding) { flag_formatter::padinfo_ = padding; } + void set_padding_info(const details::padding_info &padding) { + flag_formatter::padinfo_ = padding; + } }; class SPDLOG_API pattern_formatter final : public formatter { @@ -102,7 +105,8 @@ private: // Extract given pad spec (e.g. %8X) // Advance the given it pass the end of the padding spec found (if any) // Return padding. - static details::padding_info handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end); + static details::padding_info handle_padspec_(std::string::const_iterator &it, + std::string::const_iterator end); void compile_pattern_(const std::string &pattern); }; diff --git a/include/spdlog/sinks/android_sink.h b/include/spdlog/sinks/android_sink.h index 4e1c4c45..7c6ca59b 100644 --- a/include/spdlog/sinks/android_sink.h +++ b/include/spdlog/sinks/android_sink.h @@ -27,14 +27,15 @@ namespace sinks { /* * Android sink - * (logging using __android_log_write or __android_log_buf_write depending on the specified BufferID) + * (logging using __android_log_write or __android_log_buf_write depending on the specified + * BufferID) */ template class android_sink final : public base_sink { public: explicit android_sink(std::string tag = "spdlog", bool use_raw_msg = false) - : tag_(std::move(tag)), - use_raw_msg_(use_raw_msg) {} + : tag_(std::move(tag)) + , use_raw_msg_(use_raw_msg) {} protected: void sink_it_(const details::log_msg &msg) override { @@ -68,10 +69,10 @@ protected: void flush_() override {} private: - // There might be liblog versions used, that do not support __android_log_buf_write. So we only compile and link - // against - // __android_log_buf_write, if user explicitly provides a non-default log buffer. Otherwise, when using the default - // log buffer, always log via __android_log_write. + // There might be liblog versions used, that do not support __android_log_buf_write. So we only + // compile and link against + // __android_log_buf_write, if user explicitly provides a non-default log buffer. Otherwise, + // when using the default log buffer, always log via __android_log_write. template typename std::enable_if(log_id::LOG_ID_MAIN), int>::type android_log(int prio, const char *tag, const char *text) { @@ -120,12 +121,14 @@ using android_sink_buf_st = android_sink; // Create and register android syslog logger template -inline std::shared_ptr android_logger_mt(const std::string &logger_name, const std::string &tag = "spdlog") { +inline std::shared_ptr android_logger_mt(const std::string &logger_name, + const std::string &tag = "spdlog") { return Factory::template create(logger_name, tag); } template -inline std::shared_ptr android_logger_st(const std::string &logger_name, const std::string &tag = "spdlog") { +inline std::shared_ptr android_logger_st(const std::string &logger_name, + const std::string &tag = "spdlog") { return Factory::template create(logger_name, tag); } diff --git a/include/spdlog/sinks/ansicolor_sink-inl.h b/include/spdlog/sinks/ansicolor_sink-inl.h index 6575fecc..ced3bdfb 100644 --- a/include/spdlog/sinks/ansicolor_sink-inl.h +++ b/include/spdlog/sinks/ansicolor_sink-inl.h @@ -15,9 +15,9 @@ namespace sinks { template SPDLOG_INLINE ansicolor_sink::ansicolor_sink(FILE *target_file, color_mode mode) - : target_file_(target_file), - mutex_(ConsoleMutex::mutex()), - formatter_(details::make_unique()) + : target_file_(target_file) + , mutex_(ConsoleMutex::mutex()) + , formatter_(details::make_unique()) { set_color_mode(mode); @@ -31,7 +31,8 @@ SPDLOG_INLINE ansicolor_sink::ansicolor_sink(FILE *target_file, co } template -SPDLOG_INLINE void ansicolor_sink::set_color(level::level_enum color_level, string_view_t color) { +SPDLOG_INLINE void ansicolor_sink::set_color(level::level_enum color_level, + string_view_t color) { std::lock_guard lock(mutex_); colors_.at(static_cast(color_level)) = to_string_(color); } @@ -74,7 +75,8 @@ SPDLOG_INLINE void ansicolor_sink::set_pattern(const std::string & } template -SPDLOG_INLINE void ansicolor_sink::set_formatter(std::unique_ptr sink_formatter) { +SPDLOG_INLINE void +ansicolor_sink::set_formatter(std::unique_ptr sink_formatter) { std::lock_guard lock(mutex_); formatter_ = std::move(sink_formatter); } @@ -91,7 +93,8 @@ SPDLOG_INLINE void ansicolor_sink::set_color_mode(color_mode mode) should_do_colors_ = true; return; case color_mode::automatic: - should_do_colors_ = details::os::in_terminal(target_file_) && details::os::is_color_terminal(); + should_do_colors_ = + details::os::in_terminal(target_file_) && details::os::is_color_terminal(); return; case color_mode::never: should_do_colors_ = false; @@ -107,7 +110,9 @@ SPDLOG_INLINE void ansicolor_sink::print_ccode_(const string_view_ } template -SPDLOG_INLINE void ansicolor_sink::print_range_(const memory_buf_t &formatted, size_t start, size_t end) { +SPDLOG_INLINE void ansicolor_sink::print_range_(const memory_buf_t &formatted, + size_t start, + size_t end) { fwrite(formatted.data() + start, sizeof(char), end - start, target_file_); } diff --git a/include/spdlog/sinks/base_sink-inl.h b/include/spdlog/sinks/base_sink-inl.h index 9cf961e1..4008312e 100644 --- a/include/spdlog/sinks/base_sink-inl.h +++ b/include/spdlog/sinks/base_sink-inl.h @@ -18,7 +18,8 @@ SPDLOG_INLINE spdlog::sinks::base_sink::base_sink() : formatter_{details::make_unique()} {} template -SPDLOG_INLINE spdlog::sinks::base_sink::base_sink(std::unique_ptr formatter) +SPDLOG_INLINE +spdlog::sinks::base_sink::base_sink(std::unique_ptr formatter) : formatter_{std::move(formatter)} {} template @@ -40,7 +41,8 @@ void SPDLOG_INLINE spdlog::sinks::base_sink::set_pattern(const std::strin } template -void SPDLOG_INLINE spdlog::sinks::base_sink::set_formatter(std::unique_ptr sink_formatter) { +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)); } @@ -51,6 +53,7 @@ void SPDLOG_INLINE spdlog::sinks::base_sink::set_pattern_(const std::stri } template -void SPDLOG_INLINE spdlog::sinks::base_sink::set_formatter_(std::unique_ptr sink_formatter) { +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/basic_file_sink.h b/include/spdlog/sinks/basic_file_sink.h index b9132db8..a440b29a 100644 --- a/include/spdlog/sinks/basic_file_sink.h +++ b/include/spdlog/sinks/basic_file_sink.h @@ -45,7 +45,8 @@ inline std::shared_ptr basic_logger_mt(const std::string &logger_name, const filename_t &filename, bool truncate = false, const file_event_handlers &event_handlers = {}) { - return Factory::template create(logger_name, filename, truncate, event_handlers); + return Factory::template create(logger_name, filename, truncate, + event_handlers); } template @@ -53,7 +54,8 @@ inline std::shared_ptr basic_logger_st(const std::string &logger_name, const filename_t &filename, bool truncate = false, const file_event_handlers &event_handlers = {}) { - return Factory::template create(logger_name, filename, truncate, event_handlers); + return Factory::template create(logger_name, filename, truncate, + event_handlers); } } // namespace spdlog diff --git a/include/spdlog/sinks/callback_sink.h b/include/spdlog/sinks/callback_sink.h index a0b7a151..419f84cd 100644 --- a/include/spdlog/sinks/callback_sink.h +++ b/include/spdlog/sinks/callback_sink.h @@ -42,12 +42,14 @@ using callback_sink_st = callback_sink; // factory functions // template -inline std::shared_ptr callback_logger_mt(const std::string &logger_name, const custom_log_callback &callback) { +inline std::shared_ptr callback_logger_mt(const std::string &logger_name, + const custom_log_callback &callback) { return Factory::template create(logger_name, callback); } template -inline std::shared_ptr callback_logger_st(const std::string &logger_name, const custom_log_callback &callback) { +inline std::shared_ptr callback_logger_st(const std::string &logger_name, + const custom_log_callback &callback) { return Factory::template create(logger_name, callback); } diff --git a/include/spdlog/sinks/daily_file_sink.h b/include/spdlog/sinks/daily_file_sink.h index e5189146..14b33a54 100644 --- a/include/spdlog/sinks/daily_file_sink.h +++ b/include/spdlog/sinks/daily_file_sink.h @@ -31,16 +31,19 @@ struct daily_filename_calculator { static filename_t calc_filename(const filename_t &filename, const tm &now_tm) { filename_t basename, ext; std::tie(basename, ext) = details::file_helper::split_by_extension(filename); - return fmt_lib::format(SPDLOG_FMT_STRING(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}{}")), basename, - now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday, ext); + return fmt_lib::format(SPDLOG_FMT_STRING(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}{}")), + basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday, + ext); } }; /* * Generator of daily log file names with strftime format. * Usages: - * auto sink = std::make_shared("myapp-%Y-%m-%d:%H:%M:%S.log", hour, - * minute);" auto logger = spdlog::daily_logger_format_mt("loggername, "myapp-%Y-%m-%d:%X.log", hour, minute)" + * auto sink = + * std::make_shared("myapp-%Y-%m-%d:%H:%M:%S.log", hour, + * minute);" auto logger = spdlog::daily_logger_format_mt("loggername, "myapp-%Y-%m-%d:%X.log", + * hour, minute)" * */ struct daily_filename_format_calculator { @@ -70,14 +73,15 @@ public: bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {}) - : base_filename_(std::move(base_filename)), - rotation_h_(rotation_hour), - rotation_m_(rotation_minute), - file_helper_{event_handlers}, - truncate_(truncate), - max_files_(max_files), - filenames_q_() { - if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59) { + : base_filename_(std::move(base_filename)) + , rotation_h_(rotation_hour) + , rotation_m_(rotation_minute) + , file_helper_{event_handlers} + , truncate_(truncate) + , max_files_(max_files) + , filenames_q_() { + if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || + rotation_minute > 59) { throw_spdlog_ex("daily_file_sink: Invalid rotation time in ctor"); } @@ -168,7 +172,8 @@ private: bool ok = remove_if_exists(old_filename) == 0; if (!ok) { filenames_q_.push_back(std::move(current_file)); - throw_spdlog_ex("Failed removing daily file " + filename_to_str(old_filename), errno); + throw_spdlog_ex("Failed removing daily file " + filename_to_str(old_filename), + errno); } } filenames_q_.push_back(std::move(current_file)); @@ -187,7 +192,8 @@ private: using daily_file_sink_mt = daily_file_sink; using daily_file_sink_st = daily_file_sink; using daily_file_format_sink_mt = daily_file_sink; -using daily_file_format_sink_st = daily_file_sink; +using daily_file_format_sink_st = + daily_file_sink; } // namespace sinks @@ -202,20 +208,21 @@ inline std::shared_ptr daily_logger_mt(const std::string &logger_name, bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {}) { - return Factory::template create(logger_name, filename, hour, minute, truncate, max_files, - event_handlers); + return Factory::template create(logger_name, filename, hour, minute, + truncate, max_files, event_handlers); } template -inline std::shared_ptr daily_logger_format_mt(const std::string &logger_name, - const filename_t &filename, - int hour = 0, - int minute = 0, - bool truncate = false, - uint16_t max_files = 0, - const file_event_handlers &event_handlers = {}) { - return Factory::template create(logger_name, filename, hour, minute, truncate, - max_files, event_handlers); +inline std::shared_ptr +daily_logger_format_mt(const std::string &logger_name, + const filename_t &filename, + int hour = 0, + int minute = 0, + bool truncate = false, + uint16_t max_files = 0, + const file_event_handlers &event_handlers = {}) { + return Factory::template create( + logger_name, filename, hour, minute, truncate, max_files, event_handlers); } template @@ -226,19 +233,20 @@ inline std::shared_ptr daily_logger_st(const std::string &logger_name, bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {}) { - return Factory::template create(logger_name, filename, hour, minute, truncate, max_files, - event_handlers); + return Factory::template create(logger_name, filename, hour, minute, + truncate, max_files, event_handlers); } template -inline std::shared_ptr daily_logger_format_st(const std::string &logger_name, - const filename_t &filename, - int hour = 0, - int minute = 0, - bool truncate = false, - uint16_t max_files = 0, - const file_event_handlers &event_handlers = {}) { - return Factory::template create(logger_name, filename, hour, minute, truncate, - max_files, event_handlers); +inline std::shared_ptr +daily_logger_format_st(const std::string &logger_name, + const filename_t &filename, + int hour = 0, + int minute = 0, + bool truncate = false, + uint16_t max_files = 0, + const file_event_handlers &event_handlers = {}) { + return Factory::template create( + logger_name, filename, hour, minute, truncate, max_files, event_handlers); } } // namespace spdlog diff --git a/include/spdlog/sinks/dup_filter_sink.h b/include/spdlog/sinks/dup_filter_sink.h index 7a30c462..c2bc70c7 100644 --- a/include/spdlog/sinks/dup_filter_sink.h +++ b/include/spdlog/sinks/dup_filter_sink.h @@ -20,8 +20,8 @@ // #include // // int main() { -// auto dup_filter = std::make_shared(std::chrono::seconds(5), level::info); -// dup_filter->add_sink(std::make_shared()); +// auto dup_filter = std::make_shared(std::chrono::seconds(5), +// level::info); dup_filter->add_sink(std::make_shared()); // spdlog::logger l("logger", dup_filter); // l.info("Hello"); // l.info("Hello"); @@ -42,8 +42,8 @@ public: template explicit dup_filter_sink(std::chrono::duration max_skip_duration, level::level_enum notification_level = level::info) - : max_skip_duration_{max_skip_duration}, - log_level_{notification_level} {} + : max_skip_duration_{max_skip_duration} + , log_level_{notification_level} {} protected: std::chrono::microseconds max_skip_duration_; @@ -62,8 +62,8 @@ protected: // log the "skipped.." message if (skip_counter_ > 0) { char buf[64]; - auto msg_size = - ::snprintf(buf, sizeof(buf), "Skipped %u duplicate messages..", static_cast(skip_counter_)); + auto msg_size = ::snprintf(buf, sizeof(buf), "Skipped %u duplicate messages..", + static_cast(skip_counter_)); if (msg_size > 0 && static_cast(msg_size) < sizeof(buf)) { details::log_msg skipped_msg{msg.source, msg.logger_name, log_level_, string_view_t{buf, static_cast(msg_size)}}; diff --git a/include/spdlog/sinks/hourly_file_sink.h b/include/spdlog/sinks/hourly_file_sink.h index 505e6710..81dacc21 100644 --- a/include/spdlog/sinks/hourly_file_sink.h +++ b/include/spdlog/sinks/hourly_file_sink.h @@ -29,8 +29,9 @@ struct hourly_filename_calculator { static filename_t calc_filename(const filename_t &filename, const tm &now_tm) { filename_t basename, ext; std::tie(basename, ext) = details::file_helper::split_by_extension(filename); - return fmt_lib::format(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}{}"), basename, now_tm.tm_year + 1900, - now_tm.tm_mon + 1, now_tm.tm_mday, now_tm.tm_hour, ext); + return fmt_lib::format(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}{}"), basename, + now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday, + now_tm.tm_hour, ext); } }; @@ -47,11 +48,11 @@ public: bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {}) - : base_filename_(std::move(base_filename)), - file_helper_{event_handlers}, - truncate_(truncate), - max_files_(max_files), - filenames_q_() { + : base_filename_(std::move(base_filename)) + , file_helper_{event_handlers} + , truncate_(truncate) + , max_files_(max_files) + , filenames_q_() { auto now = log_clock::now(); auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now)); file_helper_.open(filename, truncate_); @@ -144,7 +145,8 @@ private: bool ok = remove_if_exists(old_filename) == 0; if (!ok) { filenames_q_.push_back(std::move(current_file)); - SPDLOG_THROW(spdlog_ex("Failed removing hourly file " + filename_to_str(old_filename), errno)); + SPDLOG_THROW(spdlog_ex( + "Failed removing hourly file " + filename_to_str(old_filename), errno)); } } filenames_q_.push_back(std::move(current_file)); @@ -173,8 +175,8 @@ inline std::shared_ptr hourly_logger_mt(const std::string &logger_name, bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {}) { - return Factory::template create(logger_name, filename, truncate, max_files, - event_handlers); + return Factory::template create(logger_name, filename, truncate, + max_files, event_handlers); } template @@ -183,7 +185,7 @@ inline std::shared_ptr hourly_logger_st(const std::string &logger_name, bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {}) { - return Factory::template create(logger_name, filename, truncate, max_files, - event_handlers); + return Factory::template create(logger_name, filename, truncate, + max_files, event_handlers); } } // namespace spdlog diff --git a/include/spdlog/sinks/kafka_sink.h b/include/spdlog/sinks/kafka_sink.h index ab21c10d..32ebdc93 100644 --- a/include/spdlog/sinks/kafka_sink.h +++ b/include/spdlog/sinks/kafka_sink.h @@ -30,9 +30,9 @@ struct kafka_sink_config { int32_t flush_timeout_ms = 1000; kafka_sink_config(std::string addr, std::string topic, int flush_timeout_ms = 1000) - : server_addr{std::move(addr)}, - produce_topic{std::move(topic)}, - flush_timeout_ms(flush_timeout_ms) {} + : server_addr{std::move(addr)} + , produce_topic{std::move(topic)} + , flush_timeout_ms(flush_timeout_ms) {} }; template @@ -43,9 +43,11 @@ public: try { std::string errstr; conf_.reset(RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL)); - RdKafka::Conf::ConfResult confRes = conf_->set("bootstrap.servers", config_.server_addr, errstr); + RdKafka::Conf::ConfResult confRes = + conf_->set("bootstrap.servers", config_.server_addr, errstr); if (confRes != RdKafka::Conf::CONF_OK) { - throw_spdlog_ex(fmt_lib::format("conf set bootstrap.servers failed err:{}", errstr)); + throw_spdlog_ex( + fmt_lib::format("conf set bootstrap.servers failed err:{}", errstr)); } tconf_.reset(RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC)); @@ -57,7 +59,8 @@ public: if (producer_ == nullptr) { throw_spdlog_ex(fmt_lib::format("create producer failed err:{}", errstr)); } - topic_.reset(RdKafka::Topic::create(producer_.get(), config_.produce_topic, tconf_.get(), errstr)); + topic_.reset(RdKafka::Topic::create(producer_.get(), config_.produce_topic, + tconf_.get(), errstr)); if (topic_ == nullptr) { throw_spdlog_ex(fmt_lib::format("create topic failed err:{}", errstr)); } @@ -70,8 +73,8 @@ public: protected: void sink_it_(const details::log_msg &msg) override { - producer_->produce(topic_.get(), 0, RdKafka::Producer::RK_MSG_COPY, (void *)msg.payload.data(), - msg.payload.size(), NULL, NULL); + producer_->produce(topic_.get(), 0, RdKafka::Producer::RK_MSG_COPY, + (void *)msg.payload.data(), msg.payload.size(), NULL, NULL); } void flush_() override { producer_->flush(config_.flush_timeout_ms); } @@ -102,14 +105,14 @@ inline std::shared_ptr kafka_logger_st(const std::string &logger_name, } template -inline std::shared_ptr kafka_logger_async_mt(std::string logger_name, - spdlog::sinks::kafka_sink_config config) { +inline std::shared_ptr +kafka_logger_async_mt(std::string logger_name, spdlog::sinks::kafka_sink_config config) { return Factory::template create(logger_name, config); } template -inline std::shared_ptr kafka_logger_async_st(std::string logger_name, - spdlog::sinks::kafka_sink_config config) { +inline std::shared_ptr +kafka_logger_async_st(std::string logger_name, spdlog::sinks::kafka_sink_config config) { return Factory::template create(logger_name, config); } diff --git a/include/spdlog/sinks/mongo_sink.h b/include/spdlog/sinks/mongo_sink.h index 3eaf1c86..85a46952 100644 --- a/include/spdlog/sinks/mongo_sink.h +++ b/include/spdlog/sinks/mongo_sink.h @@ -40,9 +40,9 @@ public: const std::string &db_name, const std::string &collection_name, const std::string &uri = "mongodb://localhost:27017") - : instance_(std::move(instance)), - db_name_(db_name), - coll_name_(collection_name) { + : instance_(std::move(instance)) + , db_name_(db_name) + , coll_name_(collection_name) { try { client_ = spdlog::details::make_unique(mongocxx::uri{uri}); } catch (const std::exception &e) { @@ -59,10 +59,12 @@ protected: if (client_ != nullptr) { auto doc = document{} << "timestamp" << bsoncxx::types::b_date(msg.time) << "level" - << level::to_string_view(msg.level).data() << "level_num" << msg.level << "message" - << std::string(msg.payload.begin(), msg.payload.end()) << "logger_name" - << std::string(msg.logger_name.begin(), msg.logger_name.end()) << "thread_id" - << static_cast(msg.thread_id) << finalize; + << level::to_string_view(msg.level).data() << "level_num" + << msg.level << "message" + << std::string(msg.payload.begin(), msg.payload.end()) + << "logger_name" + << std::string(msg.logger_name.begin(), msg.logger_name.end()) + << "thread_id" << static_cast(msg.thread_id) << finalize; client_->database(db_name_).collection(coll_name_).insert_one(doc.view()); } } @@ -84,19 +86,23 @@ using mongo_sink_st = mongo_sink; } // namespace sinks template -inline std::shared_ptr mongo_logger_mt(const std::string &logger_name, - const std::string &db_name, - const std::string &collection_name, - const std::string &uri = "mongodb://localhost:27017") { - return Factory::template create(logger_name, db_name, collection_name, uri); +inline std::shared_ptr +mongo_logger_mt(const std::string &logger_name, + const std::string &db_name, + const std::string &collection_name, + const std::string &uri = "mongodb://localhost:27017") { + return Factory::template create(logger_name, db_name, collection_name, + uri); } template -inline std::shared_ptr mongo_logger_st(const std::string &logger_name, - const std::string &db_name, - const std::string &collection_name, - const std::string &uri = "mongodb://localhost:27017") { - return Factory::template create(logger_name, db_name, collection_name, uri); +inline std::shared_ptr +mongo_logger_st(const std::string &logger_name, + const std::string &db_name, + const std::string &collection_name, + const std::string &uri = "mongodb://localhost:27017") { + return Factory::template create(logger_name, db_name, collection_name, + uri); } } // namespace spdlog diff --git a/include/spdlog/sinks/ostream_sink.h b/include/spdlog/sinks/ostream_sink.h index 46eadb5f..3c089ecf 100644 --- a/include/spdlog/sinks/ostream_sink.h +++ b/include/spdlog/sinks/ostream_sink.h @@ -15,8 +15,8 @@ template class ostream_sink final : public base_sink { public: explicit ostream_sink(std::ostream &os, bool force_flush = false) - : ostream_(os), - force_flush_(force_flush) {} + : ostream_(os) + , force_flush_(force_flush) {} ostream_sink(const ostream_sink &) = delete; ostream_sink &operator=(const ostream_sink &) = delete; diff --git a/include/spdlog/sinks/qt_sinks.h b/include/spdlog/sinks/qt_sinks.h index 4ccde4f3..d1cb8b6a 100644 --- a/include/spdlog/sinks/qt_sinks.h +++ b/include/spdlog/sinks/qt_sinks.h @@ -8,8 +8,8 @@ // etc) Building and using requires Qt library. // // Warning: the qt_sink won't be notified if the target widget is destroyed. -// If the widget's lifetime can be shorter than the logger's one, you should provide some permanent QObject, -// and then use a standard signal/slot. +// If the widget's lifetime can be shorter than the logger's one, you should provide some permanent +// QObject, and then use a standard signal/slot. // #include "spdlog/common.h" @@ -30,8 +30,8 @@ template class qt_sink : public base_sink { public: qt_sink(QObject *qt_object, std::string meta_method) - : qt_object_(qt_object), - meta_method_(std::move(meta_method)) { + : qt_object_(qt_object) + , meta_method_(std::move(meta_method)) { if (!qt_object_) { throw_spdlog_ex("qt_sink: qt_object is null"); } @@ -59,15 +59,19 @@ private: // QT color sink to QTextEdit. // Color location is determined by the sink log pattern like in the rest of spdlog sinks. // Colors can be modified if needed using sink->set_color(level, qtTextCharFormat). -// max_lines is the maximum number of lines that the sink will hold before removing the oldest lines. -// By default, only ascii (latin1) is supported by this sink. Set is_utf8 to true if utf8 support is needed. +// max_lines is the maximum number of lines that the sink will hold before removing the oldest +// lines. By default, only ascii (latin1) is supported by this sink. Set is_utf8 to true if utf8 +// support is needed. template class qt_color_sink : public base_sink { public: - qt_color_sink(QTextEdit *qt_text_edit, int max_lines, bool dark_colors = false, bool is_utf8 = false) - : qt_text_edit_(qt_text_edit), - max_lines_(max_lines), - is_utf8_(is_utf8) { + qt_color_sink(QTextEdit *qt_text_edit, + int max_lines, + bool dark_colors = false, + bool is_utf8 = false) + : qt_text_edit_(qt_text_edit) + , max_lines_(max_lines) + , is_utf8_(is_utf8) { if (!qt_text_edit_) { throw_spdlog_ex("qt_color_text_sink: text_edit is null"); } @@ -127,13 +131,13 @@ protected: QTextCharFormat level_color, int color_range_start, int color_range_end) - : max_lines(max_lines), - q_text_edit(q_text_edit), - payload(std::move(payload)), - default_color(default_color), - level_color(level_color), - color_range_start(color_range_start), - color_range_end(color_range_end) {} + : max_lines(max_lines) + , q_text_edit(q_text_edit) + , payload(std::move(payload)) + , default_color(default_color) + , level_color(level_color) + , color_range_start(color_range_start) + , color_range_end(color_range_end) {} int max_lines; QTextEdit *q_text_edit; QString payload; @@ -178,8 +182,8 @@ protected: void flush_() override {} // Add colored text to the text edit widget. This method is invoked in the GUI thread. - // It is a static method to ensure that it is handled correctly even if the sink is destroyed prematurely - // before it is invoked. + // It is a static method to ensure that it is handled correctly even if the sink is destroyed + // prematurely before it is invoked. static void invoke_method_(invoke_params params) { auto *document = params.q_text_edit->document(); @@ -206,8 +210,8 @@ protected: // insert the colorized text cursor.setCharFormat(params.level_color); - cursor.insertText( - params.payload.mid(params.color_range_start, params.color_range_end - params.color_range_start)); + cursor.insertText(params.payload.mid(params.color_range_start, + params.color_range_end - params.color_range_start)); // insert the text after the color range with default format cursor.setCharFormat(params.default_color); @@ -236,14 +240,16 @@ using qt_color_sink_st = qt_color_sink; // log to QTextEdit template -inline std::shared_ptr -qt_logger_mt(const std::string &logger_name, QTextEdit *qt_object, const std::string &meta_method = "append") { +inline std::shared_ptr qt_logger_mt(const std::string &logger_name, + QTextEdit *qt_object, + const std::string &meta_method = "append") { return Factory::template create(logger_name, qt_object, meta_method); } template -inline std::shared_ptr -qt_logger_st(const std::string &logger_name, QTextEdit *qt_object, const std::string &meta_method = "append") { +inline std::shared_ptr qt_logger_st(const std::string &logger_name, + QTextEdit *qt_object, + const std::string &meta_method = "append") { return Factory::template create(logger_name, qt_object, meta_method); } @@ -276,15 +282,21 @@ qt_logger_st(const std::string &logger_name, QObject *qt_object, const std::stri // log to QTextEdit with colorize output template -inline std::shared_ptr -qt_color_logger_mt(const std::string &logger_name, QTextEdit *qt_text_edit, int max_lines, bool is_utf8 = false) { - return Factory::template create(logger_name, qt_text_edit, max_lines, false, is_utf8); +inline std::shared_ptr qt_color_logger_mt(const std::string &logger_name, + QTextEdit *qt_text_edit, + int max_lines, + bool is_utf8 = false) { + return Factory::template create(logger_name, qt_text_edit, max_lines, + false, is_utf8); } template -inline std::shared_ptr -qt_color_logger_st(const std::string &logger_name, QTextEdit *qt_text_edit, int max_lines, bool is_utf8 = false) { - return Factory::template create(logger_name, qt_text_edit, max_lines, false, is_utf8); +inline std::shared_ptr qt_color_logger_st(const std::string &logger_name, + QTextEdit *qt_text_edit, + int max_lines, + bool is_utf8 = false) { + return Factory::template create(logger_name, qt_text_edit, max_lines, + false, is_utf8); } } // namespace spdlog diff --git a/include/spdlog/sinks/ringbuffer_sink.h b/include/spdlog/sinks/ringbuffer_sink.h index 3bc736ae..824c4475 100644 --- a/include/spdlog/sinks/ringbuffer_sink.h +++ b/include/spdlog/sinks/ringbuffer_sink.h @@ -50,7 +50,9 @@ public: } protected: - void sink_it_(const details::log_msg &msg) override { q_.push_back(details::log_msg_buffer{msg}); } + void sink_it_(const details::log_msg &msg) override { + q_.push_back(details::log_msg_buffer{msg}); + } void flush_() override {} private: diff --git a/include/spdlog/sinks/rotating_file_sink-inl.h b/include/spdlog/sinks/rotating_file_sink-inl.h index 18a779ed..1696f91f 100644 --- a/include/spdlog/sinks/rotating_file_sink-inl.h +++ b/include/spdlog/sinks/rotating_file_sink-inl.h @@ -24,15 +24,16 @@ 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, - const file_event_handlers &event_handlers) - : base_filename_(std::move(base_filename)), - max_size_(max_size), - max_files_(max_files), - file_helper_{event_handlers} { +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, + const file_event_handlers &event_handlers) + : base_filename_(std::move(base_filename)) + , max_size_(max_size) + , max_files_(max_files) + , file_helper_{event_handlers} { if (max_size == 0) { throw_spdlog_ex("rotating sink constructor: max_size arg cannot be zero"); } @@ -51,7 +52,8 @@ SPDLOG_INLINE rotating_file_sink::rotating_file_sink(filename_t base_file // 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) { +SPDLOG_INLINE filename_t rotating_file_sink::calc_filename(const filename_t &filename, + std::size_t index) { if (index == 0u) { return filename; } @@ -116,10 +118,11 @@ SPDLOG_INLINE void rotating_file_sink::rotate_() { // 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! + 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), + throw_spdlog_ex("rotating_file_sink: failed renaming " + filename_to_str(src) + + " to " + filename_to_str(target), errno); } } diff --git a/include/spdlog/sinks/rotating_file_sink.h b/include/spdlog/sinks/rotating_file_sink.h index e1da2a10..068eaf33 100644 --- a/include/spdlog/sinks/rotating_file_sink.h +++ b/include/spdlog/sinks/rotating_file_sink.h @@ -68,8 +68,8 @@ inline std::shared_ptr rotating_logger_mt(const std::string &logger_name size_t max_files, bool rotate_on_open = false, const file_event_handlers &event_handlers = {}) { - return Factory::template create(logger_name, filename, max_file_size, max_files, - rotate_on_open, event_handlers); + return Factory::template create( + logger_name, filename, max_file_size, max_files, rotate_on_open, event_handlers); } template @@ -79,8 +79,8 @@ inline std::shared_ptr rotating_logger_st(const std::string &logger_name size_t max_files, bool rotate_on_open = false, const file_event_handlers &event_handlers = {}) { - return Factory::template create(logger_name, filename, max_file_size, max_files, - rotate_on_open, event_handlers); + return Factory::template create( + logger_name, filename, max_file_size, max_files, rotate_on_open, event_handlers); } } // namespace spdlog diff --git a/include/spdlog/sinks/stdout_color_sinks-inl.h b/include/spdlog/sinks/stdout_color_sinks-inl.h index 4f19ca9b..d0cf8d63 100644 --- a/include/spdlog/sinks/stdout_color_sinks-inl.h +++ b/include/spdlog/sinks/stdout_color_sinks-inl.h @@ -13,22 +13,26 @@ namespace spdlog { template -SPDLOG_INLINE std::shared_ptr stdout_color_mt(const std::string &logger_name, color_mode mode) { +SPDLOG_INLINE std::shared_ptr stdout_color_mt(const std::string &logger_name, + color_mode mode) { return Factory::template create(logger_name, mode); } template -SPDLOG_INLINE std::shared_ptr stdout_color_st(const std::string &logger_name, color_mode mode) { +SPDLOG_INLINE std::shared_ptr stdout_color_st(const std::string &logger_name, + color_mode mode) { return Factory::template create(logger_name, mode); } template -SPDLOG_INLINE std::shared_ptr stderr_color_mt(const std::string &logger_name, color_mode mode) { +SPDLOG_INLINE std::shared_ptr stderr_color_mt(const std::string &logger_name, + color_mode mode) { return Factory::template create(logger_name, mode); } template -SPDLOG_INLINE std::shared_ptr stderr_color_st(const std::string &logger_name, color_mode mode) { +SPDLOG_INLINE std::shared_ptr stderr_color_st(const std::string &logger_name, + color_mode mode) { return Factory::template create(logger_name, mode); } } // namespace spdlog diff --git a/include/spdlog/sinks/stdout_color_sinks.h b/include/spdlog/sinks/stdout_color_sinks.h index f46e2f94..77e3b45d 100644 --- a/include/spdlog/sinks/stdout_color_sinks.h +++ b/include/spdlog/sinks/stdout_color_sinks.h @@ -27,16 +27,20 @@ using stderr_color_sink_st = ansicolor_stderr_sink_st; } // namespace sinks template -std::shared_ptr stdout_color_mt(const std::string &logger_name, color_mode mode = color_mode::automatic); +std::shared_ptr stdout_color_mt(const std::string &logger_name, + color_mode mode = color_mode::automatic); template -std::shared_ptr stdout_color_st(const std::string &logger_name, color_mode mode = color_mode::automatic); +std::shared_ptr stdout_color_st(const std::string &logger_name, + color_mode mode = color_mode::automatic); template -std::shared_ptr stderr_color_mt(const std::string &logger_name, color_mode mode = color_mode::automatic); +std::shared_ptr stderr_color_mt(const std::string &logger_name, + color_mode mode = color_mode::automatic); template -std::shared_ptr stderr_color_st(const std::string &logger_name, color_mode mode = color_mode::automatic); +std::shared_ptr stderr_color_st(const std::string &logger_name, + color_mode mode = color_mode::automatic); } // namespace spdlog diff --git a/include/spdlog/sinks/stdout_sinks-inl.h b/include/spdlog/sinks/stdout_sinks-inl.h index 37e7a51d..0a8ef67f 100644 --- a/include/spdlog/sinks/stdout_sinks-inl.h +++ b/include/spdlog/sinks/stdout_sinks-inl.h @@ -30,9 +30,9 @@ namespace sinks { template SPDLOG_INLINE stdout_sink_base::stdout_sink_base(FILE *file) - : mutex_(ConsoleMutex::mutex()), - file_(file), - formatter_(details::make_unique()) { + : mutex_(ConsoleMutex::mutex()) + , file_(file) + , formatter_(details::make_unique()) { #ifdef _WIN32 // get windows handle from the FILE* object @@ -60,7 +60,8 @@ SPDLOG_INLINE void stdout_sink_base::log(const details::log_msg &m DWORD bytes_written = 0; bool ok = ::WriteFile(handle_, formatted.data(), size, &bytes_written, nullptr) != 0; if (!ok) { - throw_spdlog_ex("stdout_sink_base: WriteFile() failed. GetLastError(): " + std::to_string(::GetLastError())); + throw_spdlog_ex("stdout_sink_base: WriteFile() failed. GetLastError(): " + + std::to_string(::GetLastError())); } #else std::lock_guard lock(mutex_); @@ -84,7 +85,8 @@ SPDLOG_INLINE void stdout_sink_base::set_pattern(const std::string } template -SPDLOG_INLINE void stdout_sink_base::set_formatter(std::unique_ptr sink_formatter) { +SPDLOG_INLINE void +stdout_sink_base::set_formatter(std::unique_ptr sink_formatter) { std::lock_guard lock(mutex_); formatter_ = std::move(sink_formatter); } diff --git a/include/spdlog/sinks/syslog_sink.h b/include/spdlog/sinks/syslog_sink.h index 48a87d04..5bd01418 100644 --- a/include/spdlog/sinks/syslog_sink.h +++ b/include/spdlog/sinks/syslog_sink.h @@ -21,15 +21,15 @@ class syslog_sink : public base_sink { public: syslog_sink(std::string ident, int syslog_option, int syslog_facility, bool enable_formatting) - : enable_formatting_{enable_formatting}, - syslog_levels_{{/* spdlog::level::trace */ LOG_DEBUG, + : enable_formatting_{enable_formatting} + , syslog_levels_{{/* spdlog::level::trace */ LOG_DEBUG, /* spdlog::level::debug */ LOG_DEBUG, /* spdlog::level::info */ LOG_INFO, /* spdlog::level::warn */ LOG_WARNING, /* spdlog::level::err */ LOG_ERR, /* spdlog::level::critical */ LOG_CRIT, - /* spdlog::level::off */ LOG_INFO}}, - ident_{std::move(ident)} { + /* spdlog::level::off */ LOG_INFO}} + , ident_{std::move(ident)} { // set ident to be program name if empty ::openlog(ident_.empty() ? nullptr : ident_.c_str(), syslog_option, syslog_facility); } @@ -88,8 +88,8 @@ inline std::shared_ptr syslog_logger_mt(const std::string &logger_name, int syslog_option = 0, int syslog_facility = LOG_USER, bool enable_formatting = false) { - return Factory::template create(logger_name, syslog_ident, syslog_option, syslog_facility, - enable_formatting); + return Factory::template create(logger_name, syslog_ident, syslog_option, + syslog_facility, enable_formatting); } template @@ -98,7 +98,7 @@ inline std::shared_ptr syslog_logger_st(const std::string &logger_name, int syslog_option = 0, int syslog_facility = LOG_USER, bool enable_formatting = false) { - return Factory::template create(logger_name, syslog_ident, syslog_option, syslog_facility, - enable_formatting); + return Factory::template create(logger_name, syslog_ident, syslog_option, + syslog_facility, enable_formatting); } } // namespace spdlog diff --git a/include/spdlog/sinks/systemd_sink.h b/include/spdlog/sinks/systemd_sink.h index 722337bf..45396b3c 100644 --- a/include/spdlog/sinks/systemd_sink.h +++ b/include/spdlog/sinks/systemd_sink.h @@ -24,9 +24,9 @@ template class systemd_sink : public base_sink { public: systemd_sink(std::string ident = "", bool enable_formatting = false) - : ident_{std::move(ident)}, - enable_formatting_{enable_formatting}, - syslog_levels_{{/* spdlog::level::trace */ LOG_DEBUG, + : ident_{std::move(ident)} + , enable_formatting_{enable_formatting} + , syslog_levels_{{/* spdlog::level::trace */ LOG_DEBUG, /* spdlog::level::debug */ LOG_DEBUG, /* spdlog::level::info */ LOG_INFO, /* spdlog::level::warn */ LOG_WARNING, @@ -67,22 +67,25 @@ protected: // Do not send source location if not available if (msg.source.empty()) { // Note: function call inside '()' to avoid macro expansion - err = (sd_journal_send)("MESSAGE=%.*s", static_cast(length), payload.data(), "PRIORITY=%d", - syslog_level(msg.level), + err = (sd_journal_send)("MESSAGE=%.*s", static_cast(length), payload.data(), + "PRIORITY=%d", syslog_level(msg.level), #ifndef SPDLOG_NO_THREAD_ID "TID=%zu", details::os::thread_id(), #endif - "SYSLOG_IDENTIFIER=%.*s", static_cast(syslog_identifier.size()), + "SYSLOG_IDENTIFIER=%.*s", + static_cast(syslog_identifier.size()), syslog_identifier.data(), nullptr); } else { - err = (sd_journal_send)("MESSAGE=%.*s", static_cast(length), payload.data(), "PRIORITY=%d", - syslog_level(msg.level), + err = (sd_journal_send)("MESSAGE=%.*s", static_cast(length), payload.data(), + "PRIORITY=%d", syslog_level(msg.level), #ifndef SPDLOG_NO_THREAD_ID "TID=%zu", details::os::thread_id(), #endif - "SYSLOG_IDENTIFIER=%.*s", static_cast(syslog_identifier.size()), - syslog_identifier.data(), "CODE_FILE=%s", msg.source.filename, "CODE_LINE=%d", - msg.source.line, "CODE_FUNC=%s", msg.source.funcname, nullptr); + "SYSLOG_IDENTIFIER=%.*s", + static_cast(syslog_identifier.size()), + syslog_identifier.data(), "CODE_FILE=%s", msg.source.filename, + "CODE_LINE=%d", msg.source.line, "CODE_FUNC=%s", + msg.source.funcname, nullptr); } if (err) { @@ -90,7 +93,9 @@ protected: } } - int syslog_level(level::level_enum l) { return syslog_levels_.at(static_cast(l)); } + int syslog_level(level::level_enum l) { + return syslog_levels_.at(static_cast(l)); + } void flush_() override {} }; @@ -101,14 +106,16 @@ 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, const std::string &ident = "", bool enable_formatting = false) { +inline std::shared_ptr systemd_logger_mt(const std::string &logger_name, + const std::string &ident = "", + bool enable_formatting = false) { return Factory::template create(logger_name, ident, enable_formatting); } template -inline std::shared_ptr -systemd_logger_st(const std::string &logger_name, const std::string &ident = "", bool enable_formatting = false) { +inline std::shared_ptr systemd_logger_st(const std::string &logger_name, + const std::string &ident = "", + bool enable_formatting = false) { return Factory::template create(logger_name, ident, enable_formatting); } } // namespace spdlog diff --git a/include/spdlog/sinks/tcp_sink.h b/include/spdlog/sinks/tcp_sink.h index d783f32b..c7830cf7 100644 --- a/include/spdlog/sinks/tcp_sink.h +++ b/include/spdlog/sinks/tcp_sink.h @@ -22,7 +22,8 @@ // Simple tcp client sink // Connects to remote address and send the formatted log. // Will attempt to reconnect if connection drops. -// If more complicated behaviour is needed (i.e get responses), you can inherit it and override the sink_it_ method. +// If more complicated behaviour is needed (i.e get responses), you can inherit it and override the +// sink_it_ method. namespace spdlog { namespace sinks { @@ -33,8 +34,8 @@ struct tcp_sink_config { bool lazy_connect = false; // if true connect on first log call instead of on construction tcp_sink_config(std::string host, int port) - : server_host{std::move(host)}, - server_port{port} {} + : server_host{std::move(host)} + , server_port{port} {} }; template diff --git a/include/spdlog/sinks/udp_sink.h b/include/spdlog/sinks/udp_sink.h index d38c5590..5c37aad1 100644 --- a/include/spdlog/sinks/udp_sink.h +++ b/include/spdlog/sinks/udp_sink.h @@ -28,8 +28,8 @@ struct udp_sink_config { uint16_t server_port; udp_sink_config(std::string host, uint16_t port) - : server_host{std::move(host)}, - server_port{port} {} + : server_host{std::move(host)} + , server_port{port} {} }; template @@ -61,7 +61,8 @@ using udp_sink_st = udp_sink; // factory functions // template -inline std::shared_ptr udp_logger_mt(const std::string &logger_name, sinks::udp_sink_config skin_config) { +inline std::shared_ptr udp_logger_mt(const std::string &logger_name, + sinks::udp_sink_config skin_config) { return Factory::template create(logger_name, skin_config); } diff --git a/include/spdlog/sinks/win_eventlog_sink.h b/include/spdlog/sinks/win_eventlog_sink.h index ca16ad84..19663d2f 100644 --- a/include/spdlog/sinks/win_eventlog_sink.h +++ b/include/spdlog/sinks/win_eventlog_sink.h @@ -1,17 +1,20 @@ // Copyright(c) 2015-present, Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) -// Writing to Windows Event Log requires the registry entries below to be present, with the following modifications: +// Writing to Windows Event Log requires the registry entries below to be present, with the +// following modifications: // 1. should be replaced with your log name (e.g. your application name) -// 2. should be replaced with the specific source name and the key should be duplicated for +// 2. should be replaced with the specific source name and the key should be +// duplicated for // each source used in the application // -// Since typically modifications of this kind require elevation, it's better to do it as a part of setup procedure. -// The snippet below uses mscoree.dll as the message file as it exists on most of the Windows systems anyway and -// happens to contain the needed resource. +// Since typically modifications of this kind require elevation, it's better to do it as a part of +// setup procedure. The snippet below uses mscoree.dll as the message file as it exists on most of +// the Windows systems anyway and happens to contain the needed resource. // // You can also specify a custom message file if needed. -// Please refer to Event Log functions descriptions in MSDN for more details on custom message files. +// Please refer to Event Log functions descriptions in MSDN for more details on custom message +// files. /*--------------------------------------------------------------------------------------- @@ -69,9 +72,11 @@ struct win32_error : public spdlog_ex { std::string system_message; local_alloc_t format_message_result{}; - auto format_message_succeeded = ::FormatMessageA( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, - error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&format_message_result.hlocal_, 0, nullptr); + auto format_message_succeeded = + ::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPSTR)&format_message_result.hlocal_, 0, nullptr); if (format_message_succeeded && format_message_result.hlocal_) { system_message = fmt_lib::format(" ({})", (LPSTR)format_message_result.hlocal_); @@ -124,18 +129,21 @@ public: ~process_token_t() { ::CloseHandle(token_handle_); } - } current_process_token(::GetCurrentProcess()); // GetCurrentProcess returns pseudohandle, no leak here! + } current_process_token( + ::GetCurrentProcess()); // GetCurrentProcess returns pseudohandle, no leak here! - // Get the required size, this is expected to fail with ERROR_INSUFFICIENT_BUFFER and return the token size + // Get the required size, this is expected to fail with ERROR_INSUFFICIENT_BUFFER and return + // the token size DWORD tusize = 0; - if (::GetTokenInformation(current_process_token.token_handle_, TokenUser, NULL, 0, &tusize)) { + if (::GetTokenInformation(current_process_token.token_handle_, TokenUser, NULL, 0, + &tusize)) { SPDLOG_THROW(win32_error("GetTokenInformation should fail")); } // get user token std::vector buffer(static_cast(tusize)); - if (!::GetTokenInformation(current_process_token.token_handle_, TokenUser, (LPVOID)buffer.data(), tusize, - &tusize)) { + if (!::GetTokenInformation(current_process_token.token_handle_, TokenUser, + (LPVOID)buffer.data(), tusize, &tusize)) { SPDLOG_THROW(win32_error("GetTokenInformation")); } @@ -208,14 +216,14 @@ protected: details::os::utf8_to_wstrbuf(string_view_t(formatted.data(), formatted.size()), buf); LPCWSTR lp_wstr = buf.data(); - succeeded = static_cast(::ReportEventW(event_log_handle(), eventlog::get_event_type(msg), - eventlog::get_event_category(msg), event_id_, - current_user_sid_.as_sid(), 1, 0, &lp_wstr, nullptr)); + succeeded = static_cast(::ReportEventW( + event_log_handle(), eventlog::get_event_type(msg), eventlog::get_event_category(msg), + event_id_, current_user_sid_.as_sid(), 1, 0, &lp_wstr, nullptr)); #else LPCSTR lp_str = formatted.data(); - succeeded = static_cast(::ReportEventA(event_log_handle(), eventlog::get_event_type(msg), - eventlog::get_event_category(msg), event_id_, - current_user_sid_.as_sid(), 1, 0, &lp_str, nullptr)); + succeeded = static_cast(::ReportEventA( + event_log_handle(), eventlog::get_event_type(msg), eventlog::get_event_category(msg), + event_id_, current_user_sid_.as_sid(), 1, 0, &lp_str, nullptr)); #endif if (!succeeded) { @@ -226,14 +234,15 @@ protected: void flush_() override {} public: - win_eventlog_sink(std::string const &source, DWORD event_id = 1000 /* according to mscoree.dll */) - : source_(source), - event_id_(event_id) { + win_eventlog_sink(std::string const &source, + DWORD event_id = 1000 /* according to mscoree.dll */) + : source_(source) + , event_id_(event_id) { try { current_user_sid_ = internal::sid_t::get_current_user_sid(); } catch (...) { - // get_current_user_sid() is unlikely to fail and if it does, we can still proceed without - // current_user_sid but in the event log the record will have no user name + // get_current_user_sid() is unlikely to fail and if it does, we can still proceed + // without current_user_sid but in the event log the record will have no user name } } diff --git a/include/spdlog/sinks/wincolor_sink-inl.h b/include/spdlog/sinks/wincolor_sink-inl.h index 186bf983..5f66d36d 100644 --- a/include/spdlog/sinks/wincolor_sink-inl.h +++ b/include/spdlog/sinks/wincolor_sink-inl.h @@ -17,18 +17,20 @@ namespace spdlog { namespace sinks { template SPDLOG_INLINE wincolor_sink::wincolor_sink(void *out_handle, color_mode mode) - : out_handle_(out_handle), - mutex_(ConsoleMutex::mutex()), - formatter_(details::make_unique()) { + : out_handle_(out_handle) + , mutex_(ConsoleMutex::mutex()) + , formatter_(details::make_unique()) { set_color_mode_impl(mode); // set level colors - colors_[level::trace] = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; // white - colors_[level::debug] = FOREGROUND_GREEN | FOREGROUND_BLUE; // cyan - colors_[level::info] = FOREGROUND_GREEN; // green - colors_[level::warn] = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; // intense yellow - colors_[level::err] = FOREGROUND_RED | FOREGROUND_INTENSITY; // intense red - colors_[level::critical] = BACKGROUND_RED | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | + colors_[level::trace] = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; // white + colors_[level::debug] = FOREGROUND_GREEN | FOREGROUND_BLUE; // cyan + colors_[level::info] = FOREGROUND_GREEN; // green + colors_[level::warn] = + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; // intense yellow + colors_[level::err] = FOREGROUND_RED | FOREGROUND_INTENSITY; // intense red + colors_[level::critical] = BACKGROUND_RED | FOREGROUND_RED | FOREGROUND_GREEN | + FOREGROUND_BLUE | FOREGROUND_INTENSITY; // intense white on red background colors_[level::off] = 0; } @@ -40,7 +42,8 @@ SPDLOG_INLINE wincolor_sink::~wincolor_sink() { // change the color for the given level template -void SPDLOG_INLINE wincolor_sink::set_color(level::level_enum level, std::uint16_t color) { +void SPDLOG_INLINE wincolor_sink::set_color(level::level_enum level, + std::uint16_t color) { std::lock_guard lock(mutex_); colors_[static_cast(level)] = color; } @@ -60,7 +63,8 @@ void SPDLOG_INLINE wincolor_sink::log(const details::log_msg &msg) // before color range print_range_(formatted, 0, msg.color_range_start); // in color range - auto orig_attribs = static_cast(set_foreground_color_(colors_[static_cast(msg.level)])); + auto orig_attribs = + static_cast(set_foreground_color_(colors_[static_cast(msg.level)])); print_range_(formatted, msg.color_range_start, msg.color_range_end); // reset to orig colors ::SetConsoleTextAttribute(static_cast(out_handle_), orig_attribs); @@ -83,7 +87,8 @@ void SPDLOG_INLINE wincolor_sink::set_pattern(const std::string &p } template -void SPDLOG_INLINE wincolor_sink::set_formatter(std::unique_ptr sink_formatter) { +void SPDLOG_INLINE +wincolor_sink::set_formatter(std::unique_ptr sink_formatter) { std::lock_guard lock(mutex_); formatter_ = std::move(sink_formatter); } @@ -108,7 +113,8 @@ void SPDLOG_INLINE wincolor_sink::set_color_mode_impl(color_mode m // set foreground color and return the orig console attributes (for resetting later) template -std::uint16_t SPDLOG_INLINE wincolor_sink::set_foreground_color_(std::uint16_t attribs) { +std::uint16_t SPDLOG_INLINE +wincolor_sink::set_foreground_color_(std::uint16_t attribs) { CONSOLE_SCREEN_BUFFER_INFO orig_buffer_info; if (!::GetConsoleScreenBufferInfo(static_cast(out_handle_), &orig_buffer_info)) { // just return white if failed getting console info @@ -117,18 +123,21 @@ std::uint16_t SPDLOG_INLINE wincolor_sink::set_foreground_color_(s // change only the foreground bits (lowest 4 bits) auto new_attribs = static_cast(attribs) | (orig_buffer_info.wAttributes & 0xfff0); - auto ignored = ::SetConsoleTextAttribute(static_cast(out_handle_), static_cast(new_attribs)); + auto ignored = + ::SetConsoleTextAttribute(static_cast(out_handle_), static_cast(new_attribs)); (void)(ignored); return static_cast(orig_buffer_info.wAttributes); // return orig attribs } // print a range of formatted message to console template -void SPDLOG_INLINE wincolor_sink::print_range_(const memory_buf_t &formatted, size_t start, size_t end) { +void SPDLOG_INLINE wincolor_sink::print_range_(const memory_buf_t &formatted, + size_t start, + size_t end) { if (end > start) { auto size = static_cast(end - start); - auto ignored = - ::WriteConsoleA(static_cast(out_handle_), formatted.data() + start, size, nullptr, nullptr); + auto ignored = ::WriteConsoleA(static_cast(out_handle_), formatted.data() + start, + size, nullptr, nullptr); (void)(ignored); } } @@ -137,7 +146,8 @@ template void SPDLOG_INLINE wincolor_sink::write_to_file_(const memory_buf_t &formatted) { auto size = static_cast(formatted.size()); DWORD bytes_written = 0; - auto ignored = ::WriteFile(static_cast(out_handle_), formatted.data(), size, &bytes_written, nullptr); + auto ignored = ::WriteFile(static_cast(out_handle_), formatted.data(), size, + &bytes_written, nullptr); (void)(ignored); } diff --git a/include/spdlog/spdlog-inl.h b/include/spdlog/spdlog-inl.h index b888de84..d6681407 100644 --- a/include/spdlog/spdlog-inl.h +++ b/include/spdlog/spdlog-inl.h @@ -16,17 +16,22 @@ 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 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))); + set_formatter( + std::unique_ptr(new pattern_formatter(std::move(pattern), time_type))); } -SPDLOG_INLINE void enable_backtrace(size_t n_messages) { details::registry::instance().enable_backtrace(n_messages); } +SPDLOG_INLINE void enable_backtrace(size_t n_messages) { + details::registry::instance().enable_backtrace(n_messages); +} SPDLOG_INLINE void disable_backtrace() { details::registry::instance().disable_backtrace(); } @@ -34,11 +39,17 @@ SPDLOG_INLINE void dump_backtrace() { default_logger_raw()->dump_backtrace(); } SPDLOG_INLINE level::level_enum get_level() { return default_logger_raw()->level(); } -SPDLOG_INLINE bool should_log(level::level_enum log_level) { return default_logger_raw()->should_log(log_level); } +SPDLOG_INLINE bool should_log(level::level_enum log_level) { + return default_logger_raw()->should_log(log_level); +} -SPDLOG_INLINE void set_level(level::level_enum log_level) { details::registry::instance().set_level(log_level); } +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_on(level::level_enum log_level) { + details::registry::instance().flush_on(log_level); +} SPDLOG_INLINE void set_error_handler(void (*handler)(const std::string &msg)) { details::registry::instance().set_error_handler(handler); @@ -66,7 +77,9 @@ 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 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)); diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index b2a20317..0987b2d5 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -32,7 +32,8 @@ using default_factory = synchronous_factory; // spdlog::create("logger_name", "dailylog_filename", 11, 59); template inline std::shared_ptr create(std::string logger_name, SinkArgs &&...sink_args) { - return default_factory::create(std::move(logger_name), std::forward(sink_args)...); + return default_factory::create(std::move(logger_name), + std::forward(sink_args)...); } // Initialize and register a logger, @@ -55,7 +56,8 @@ SPDLOG_API void set_formatter(std::unique_ptr formatter); // Set global format string. // example: spdlog::set_pattern("%Y-%m-%d %H:%M:%S.%e %l : %v"); -SPDLOG_API void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local); +SPDLOG_API void set_pattern(std::string pattern, + pattern_time_type time_type = pattern_time_type::local); // enable global backtrace support SPDLOG_API void enable_backtrace(size_t n_messages); @@ -139,7 +141,8 @@ SPDLOG_API void set_default_logger(std::shared_ptr default_logge SPDLOG_API void apply_logger_env_levels(std::shared_ptr logger); template -inline void log(source_loc source, level::level_enum lvl, format_string_t fmt, Args &&...args) { +inline void +log(source_loc source, level::level_enum lvl, format_string_t fmt, Args &&...args) { default_logger_raw()->log(source, lvl, fmt, std::forward(args)...); } @@ -190,7 +193,8 @@ inline void log(level::level_enum lvl, const T &msg) { #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT template -inline void log(source_loc source, level::level_enum lvl, wformat_string_t fmt, Args &&...args) { +inline void +log(source_loc source, level::level_enum lvl, wformat_string_t fmt, Args &&...args) { default_logger_raw()->log(source, lvl, fmt, std::forward(args)...); } @@ -279,11 +283,13 @@ inline void critical(const T &msg) { #define SPDLOG_LOGGER_CALL(logger, level, ...) \ (logger)->log(spdlog::source_loc{__FILE__, __LINE__, SPDLOG_FUNCTION}, level, __VA_ARGS__) #else - #define SPDLOG_LOGGER_CALL(logger, level, ...) (logger)->log(spdlog::source_loc{}, level, __VA_ARGS__) + #define SPDLOG_LOGGER_CALL(logger, level, ...) \ + (logger)->log(spdlog::source_loc{}, level, __VA_ARGS__) #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE - #define SPDLOG_LOGGER_TRACE(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::trace, __VA_ARGS__) + #define SPDLOG_LOGGER_TRACE(logger, ...) \ + SPDLOG_LOGGER_CALL(logger, spdlog::level::trace, __VA_ARGS__) #define SPDLOG_TRACE(...) SPDLOG_LOGGER_TRACE(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_TRACE(logger, ...) (void)0 @@ -291,7 +297,8 @@ inline void critical(const T &msg) { #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_DEBUG - #define SPDLOG_LOGGER_DEBUG(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::debug, __VA_ARGS__) + #define SPDLOG_LOGGER_DEBUG(logger, ...) \ + SPDLOG_LOGGER_CALL(logger, spdlog::level::debug, __VA_ARGS__) #define SPDLOG_DEBUG(...) SPDLOG_LOGGER_DEBUG(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_DEBUG(logger, ...) (void)0 @@ -299,7 +306,8 @@ inline void critical(const T &msg) { #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_INFO - #define SPDLOG_LOGGER_INFO(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::info, __VA_ARGS__) + #define SPDLOG_LOGGER_INFO(logger, ...) \ + SPDLOG_LOGGER_CALL(logger, spdlog::level::info, __VA_ARGS__) #define SPDLOG_INFO(...) SPDLOG_LOGGER_INFO(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_INFO(logger, ...) (void)0 @@ -307,7 +315,8 @@ inline void critical(const T &msg) { #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_WARN - #define SPDLOG_LOGGER_WARN(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::warn, __VA_ARGS__) + #define SPDLOG_LOGGER_WARN(logger, ...) \ + SPDLOG_LOGGER_CALL(logger, spdlog::level::warn, __VA_ARGS__) #define SPDLOG_WARN(...) SPDLOG_LOGGER_WARN(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_WARN(logger, ...) (void)0 @@ -315,7 +324,8 @@ inline void critical(const T &msg) { #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_ERROR - #define SPDLOG_LOGGER_ERROR(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::err, __VA_ARGS__) + #define SPDLOG_LOGGER_ERROR(logger, ...) \ + SPDLOG_LOGGER_CALL(logger, spdlog::level::err, __VA_ARGS__) #define SPDLOG_ERROR(...) SPDLOG_LOGGER_ERROR(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_ERROR(logger, ...) (void)0 @@ -323,7 +333,8 @@ inline void critical(const T &msg) { #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_CRITICAL - #define SPDLOG_LOGGER_CRITICAL(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::critical, __VA_ARGS__) + #define SPDLOG_LOGGER_CRITICAL(logger, ...) \ + SPDLOG_LOGGER_CALL(logger, spdlog::level::critical, __VA_ARGS__) #define SPDLOG_CRITICAL(...) SPDLOG_LOGGER_CRITICAL(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_CRITICAL(logger, ...) (void)0 diff --git a/include/spdlog/stopwatch.h b/include/spdlog/stopwatch.h index 0fc3ea37..3dc1693b 100644 --- a/include/spdlog/stopwatch.h +++ b/include/spdlog/stopwatch.h @@ -35,7 +35,9 @@ public: stopwatch() : start_tp_{clock::now()} {} - std::chrono::duration elapsed() const { return std::chrono::duration(clock::now() - start_tp_); } + std::chrono::duration elapsed() const { + return std::chrono::duration(clock::now() - start_tp_); + } void reset() { start_tp_ = clock::now(); } }; diff --git a/include/spdlog/tweakme.h b/include/spdlog/tweakme.h index 5bcb5ff4..a47a9076 100644 --- a/include/spdlog/tweakme.h +++ b/include/spdlog/tweakme.h @@ -102,7 +102,8 @@ /////////////////////////////////////////////////////////////////////////////// // Uncomment to customize level names (e.g. "MY TRACE") // -// #define SPDLOG_LEVEL_NAMES { "MY TRACE", "MY DEBUG", "MY INFO", "MY WARNING", "MY ERROR", "MY CRITICAL", "OFF" } +// #define SPDLOG_LEVEL_NAMES { "MY TRACE", "MY DEBUG", "MY INFO", "MY WARNING", "MY ERROR", "MY +// CRITICAL", "OFF" } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// diff --git a/src/bundled_fmtlib_format.cpp b/src/bundled_fmtlib_format.cpp index 02bb55da..ff149484 100644 --- a/src/bundled_fmtlib_format.cpp +++ b/src/bundled_fmtlib_format.cpp @@ -31,7 +31,8 @@ template FMT_API void buffer::append(const char *, const char *); // DEPRECATED! // There is no correspondent extern template in format.h because of // incompatibility between clang and gcc (#2377). -template FMT_API void vformat_to(buffer &, string_view, basic_format_args, locale_ref); +template FMT_API void +vformat_to(buffer &, string_view, basic_format_args, locale_ref); // Explicit instantiations for wchar_t. diff --git a/src/color_sinks.cpp b/src/color_sinks.cpp index 1ad1bd66..d0516b45 100644 --- a/src/color_sinks.cpp +++ b/src/color_sinks.cpp @@ -33,13 +33,17 @@ template class SPDLOG_API spdlog::sinks::ansicolor_stderr_sink -spdlog::stdout_color_mt(const std::string &logger_name, color_mode mode); +spdlog::stdout_color_mt(const std::string &logger_name, + color_mode mode); template SPDLOG_API std::shared_ptr -spdlog::stdout_color_st(const std::string &logger_name, color_mode mode); +spdlog::stdout_color_st(const std::string &logger_name, + color_mode mode); template SPDLOG_API std::shared_ptr -spdlog::stderr_color_mt(const std::string &logger_name, color_mode mode); +spdlog::stderr_color_mt(const std::string &logger_name, + color_mode mode); template SPDLOG_API std::shared_ptr -spdlog::stderr_color_st(const std::string &logger_name, color_mode mode); +spdlog::stderr_color_st(const std::string &logger_name, + color_mode mode); template SPDLOG_API std::shared_ptr spdlog::stdout_color_mt(const std::string &logger_name, color_mode mode); diff --git a/src/spdlog.cpp b/src/spdlog.cpp index 9c7ae9c4..9f8390bc 100644 --- a/src/spdlog.cpp +++ b/src/spdlog.cpp @@ -21,7 +21,8 @@ #include // template instantiate logger constructor with sinks init list -template SPDLOG_API -spdlog::logger::logger(std::string name, sinks_init_list::iterator begin, sinks_init_list::iterator end); +template SPDLOG_API spdlog::logger::logger(std::string name, + sinks_init_list::iterator begin, + sinks_init_list::iterator end); template class SPDLOG_API spdlog::sinks::base_sink; template class SPDLOG_API spdlog::sinks::base_sink; diff --git a/tests/includes.h b/tests/includes.h index 6e46992b..84e8bf91 100644 --- a/tests/includes.h +++ b/tests/includes.h @@ -1,12 +1,12 @@ #pragma once #if defined(__GNUC__) && __GNUC__ == 12 -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wmaybe-uninitialized" // Workaround for GCC 12 + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" // Workaround for GCC 12 #endif #include #if defined(__GNUC__) && __GNUC__ == 12 -# pragma GCC diagnostic pop + #pragma GCC diagnostic pop #endif #include "utils.h" diff --git a/tests/main.cpp b/tests/main.cpp index c8dca193..fd562ad3 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -1,10 +1,10 @@ #if defined(__GNUC__) && __GNUC__ == 12 -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wmaybe-uninitialized" // Workaround for GCC 12 + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" // Workaround for GCC 12 #endif #include #if defined(__GNUC__) && __GNUC__ == 12 -# pragma GCC diagnostic pop + #pragma GCC diagnostic pop #endif diff --git a/tests/test_async.cpp b/tests/test_async.cpp index c82040ba..44d34ebe 100644 --- a/tests/test_async.cpp +++ b/tests/test_async.cpp @@ -5,17 +5,16 @@ #define TEST_FILENAME "test_logs/async_test.log" -TEST_CASE("basic async test ", "[async]") -{ +TEST_CASE("basic async test ", "[async]") { auto test_sink = std::make_shared(); size_t overrun_counter = 0; size_t queue_size = 128; size_t messages = 256; { auto tp = std::make_shared(queue_size, 1); - auto logger = std::make_shared("as", test_sink, tp, spdlog::async_overflow_policy::block); - for (size_t i = 0; i < messages; i++) - { + auto logger = std::make_shared("as", test_sink, tp, + spdlog::async_overflow_policy::block); + for (size_t i = 0; i < messages; i++) { logger->info("Hello message #{}", i); } logger->flush(); @@ -26,42 +25,39 @@ TEST_CASE("basic async test ", "[async]") REQUIRE(overrun_counter == 0); } -TEST_CASE("discard policy ", "[async]") -{ +TEST_CASE("discard policy ", "[async]") { auto test_sink = std::make_shared(); test_sink->set_delay(std::chrono::milliseconds(1)); size_t queue_size = 4; size_t messages = 1024; auto tp = std::make_shared(queue_size, 1); - auto logger = std::make_shared("as", test_sink, tp, spdlog::async_overflow_policy::overrun_oldest); - for (size_t i = 0; i < messages; i++) - { + auto logger = std::make_shared( + "as", test_sink, tp, spdlog::async_overflow_policy::overrun_oldest); + for (size_t i = 0; i < messages; i++) { logger->info("Hello message"); } REQUIRE(test_sink->msg_counter() < messages); REQUIRE(tp->overrun_counter() > 0); } -TEST_CASE("discard policy discard_new ", "[async]") -{ +TEST_CASE("discard policy discard_new ", "[async]") { auto test_sink = std::make_shared(); test_sink->set_delay(std::chrono::milliseconds(1)); size_t queue_size = 4; size_t messages = 1024; auto tp = std::make_shared(queue_size, 1); - auto logger = std::make_shared("as", test_sink, tp, spdlog::async_overflow_policy::discard_new); - for (size_t i = 0; i < messages; i++) - { + auto logger = std::make_shared( + "as", test_sink, tp, spdlog::async_overflow_policy::discard_new); + for (size_t i = 0; i < messages; i++) { logger->info("Hello message"); } REQUIRE(test_sink->msg_counter() < messages); REQUIRE(tp->discard_counter() > 0); } -TEST_CASE("discard policy using factory ", "[async]") -{ +TEST_CASE("discard policy using factory ", "[async]") { size_t queue_size = 4; size_t messages = 1024; spdlog::init_thread_pool(queue_size, 1); @@ -70,8 +66,7 @@ TEST_CASE("discard policy using factory ", "[async]") auto test_sink = std::static_pointer_cast(logger->sinks()[0]); test_sink->set_delay(std::chrono::milliseconds(3)); - for (size_t i = 0; i < messages; i++) - { + for (size_t i = 0; i < messages; i++) { logger->info("Hello message"); } @@ -79,16 +74,15 @@ TEST_CASE("discard policy using factory ", "[async]") spdlog::drop_all(); } -TEST_CASE("flush", "[async]") -{ +TEST_CASE("flush", "[async]") { auto test_sink = std::make_shared(); size_t queue_size = 256; size_t messages = 256; { auto tp = std::make_shared(queue_size, 1); - auto logger = std::make_shared("as", test_sink, tp, spdlog::async_overflow_policy::block); - for (size_t i = 0; i < messages; i++) - { + auto logger = std::make_shared("as", test_sink, tp, + spdlog::async_overflow_policy::block); + for (size_t i = 0; i < messages; i++) { logger->info("Hello message #{}", i); } @@ -99,8 +93,7 @@ TEST_CASE("flush", "[async]") REQUIRE(test_sink->flush_counter() == 1); } -TEST_CASE("async periodic flush", "[async]") -{ +TEST_CASE("async periodic flush", "[async]") { auto logger = spdlog::create_async("as"); auto test_sink = std::static_pointer_cast(logger->sinks()[0]); @@ -112,16 +105,15 @@ TEST_CASE("async periodic flush", "[async]") spdlog::drop_all(); } -TEST_CASE("tp->wait_empty() ", "[async]") -{ +TEST_CASE("tp->wait_empty() ", "[async]") { auto test_sink = std::make_shared(); test_sink->set_delay(std::chrono::milliseconds(5)); size_t messages = 100; auto tp = std::make_shared(messages, 2); - auto logger = std::make_shared("as", test_sink, tp, spdlog::async_overflow_policy::block); - for (size_t i = 0; i < messages; i++) - { + auto logger = std::make_shared("as", test_sink, tp, + spdlog::async_overflow_policy::block); + for (size_t i = 0; i < messages; i++) { logger->info("Hello message #{}", i); } logger->flush(); @@ -131,30 +123,27 @@ TEST_CASE("tp->wait_empty() ", "[async]") REQUIRE(test_sink->flush_counter() == 1); } -TEST_CASE("multi threads", "[async]") -{ +TEST_CASE("multi threads", "[async]") { auto test_sink = std::make_shared(); size_t queue_size = 128; size_t messages = 256; size_t n_threads = 10; { auto tp = std::make_shared(queue_size, 1); - auto logger = std::make_shared("as", test_sink, tp, spdlog::async_overflow_policy::block); + auto logger = std::make_shared("as", test_sink, tp, + spdlog::async_overflow_policy::block); std::vector threads; - for (size_t i = 0; i < n_threads; i++) - { + for (size_t i = 0; i < n_threads; i++) { threads.emplace_back([logger, messages] { - for (size_t j = 0; j < messages; j++) - { + for (size_t j = 0; j < messages; j++) { logger->info("Hello message #{}", j); } }); logger->flush(); } - for (auto &t : threads) - { + for (auto &t : threads) { t.join(); } } @@ -163,8 +152,7 @@ TEST_CASE("multi threads", "[async]") REQUIRE(test_sink->flush_counter() == n_threads); } -TEST_CASE("to_file", "[async]") -{ +TEST_CASE("to_file", "[async]") { prepare_logdir(); size_t messages = 1024; size_t tp_threads = 1; @@ -172,10 +160,10 @@ TEST_CASE("to_file", "[async]") { auto file_sink = std::make_shared(filename, true); auto tp = std::make_shared(messages, tp_threads); - auto logger = std::make_shared("as", std::move(file_sink), std::move(tp)); + auto logger = + std::make_shared("as", std::move(file_sink), std::move(tp)); - for (size_t j = 0; j < messages; j++) - { + for (size_t j = 0; j < messages; j++) { logger->info("Hello message #{}", j); } } @@ -186,8 +174,7 @@ TEST_CASE("to_file", "[async]") REQUIRE(ends_with(contents, spdlog::fmt_lib::format("Hello message #1023{}", default_eol))); } -TEST_CASE("to_file multi-workers", "[async]") -{ +TEST_CASE("to_file multi-workers", "[async]") { prepare_logdir(); size_t messages = 1024 * 10; size_t tp_threads = 10; @@ -195,18 +182,17 @@ TEST_CASE("to_file multi-workers", "[async]") { auto file_sink = std::make_shared(filename, true); auto tp = std::make_shared(messages, tp_threads); - auto logger = std::make_shared("as", std::move(file_sink), std::move(tp)); + auto logger = + std::make_shared("as", std::move(file_sink), std::move(tp)); - for (size_t j = 0; j < messages; j++) - { + for (size_t j = 0; j < messages; j++) { logger->info("Hello message #{}", j); } } require_message_count(TEST_FILENAME, messages); } -TEST_CASE("bad_tp", "[async]") -{ +TEST_CASE("bad_tp", "[async]") { auto test_sink = std::make_shared(); std::shared_ptr const empty_tp; auto logger = std::make_shared("as", test_sink, empty_tp); diff --git a/tests/test_backtrace.cpp b/tests/test_backtrace.cpp index 6cf9ec55..93888214 100644 --- a/tests/test_backtrace.cpp +++ b/tests/test_backtrace.cpp @@ -2,8 +2,7 @@ #include "test_sink.h" #include "spdlog/async.h" -TEST_CASE("bactrace1", "[bactrace]") -{ +TEST_CASE("bactrace1", "[bactrace]") { using spdlog::sinks::test_sink_st; auto test_sink = std::make_shared(); @@ -31,8 +30,7 @@ TEST_CASE("bactrace1", "[bactrace]") REQUIRE(test_sink->lines()[7] == "****************** Backtrace End ********************"); } -TEST_CASE("bactrace-empty", "[bactrace]") -{ +TEST_CASE("bactrace-empty", "[bactrace]") { using spdlog::sinks::test_sink_st; auto test_sink = std::make_shared(); size_t backtrace_size = 5; @@ -44,8 +42,7 @@ TEST_CASE("bactrace-empty", "[bactrace]") REQUIRE(test_sink->lines().size() == 0); } -TEST_CASE("bactrace-async", "[bactrace]") -{ +TEST_CASE("bactrace-async", "[bactrace]") { using spdlog::sinks::test_sink_mt; auto test_sink = std::make_shared(); using spdlog::details::os::sleep_for_millis; @@ -53,7 +50,8 @@ TEST_CASE("bactrace-async", "[bactrace]") size_t backtrace_size = 5; spdlog::init_thread_pool(120, 1); - auto logger = std::make_shared("test-bactrace-async", test_sink, spdlog::thread_pool()); + auto logger = std::make_shared("test-bactrace-async", test_sink, + spdlog::thread_pool()); logger->set_pattern("%v"); logger->enable_backtrace(backtrace_size); diff --git a/tests/test_bin_to_hex.cpp b/tests/test_bin_to_hex.cpp index 3c50c74a..45fc9fa9 100644 --- a/tests/test_bin_to_hex.cpp +++ b/tests/test_bin_to_hex.cpp @@ -2,8 +2,7 @@ #include "test_sink.h" #include "spdlog/fmt/bin_to_hex.h" -TEST_CASE("to_hex", "[to_hex]") -{ +TEST_CASE("to_hex", "[to_hex]") { std::ostringstream oss; auto oss_sink = std::make_shared(oss); spdlog::logger oss_logger("oss", oss_sink); @@ -12,11 +11,11 @@ TEST_CASE("to_hex", "[to_hex]") oss_logger.info("{}", spdlog::to_hex(v)); auto output = oss.str(); - REQUIRE(ends_with(output, "0000: 09 0a 0b 0c ff ff" + std::string(spdlog::details::os::default_eol))); + REQUIRE(ends_with(output, + "0000: 09 0a 0b 0c ff ff" + std::string(spdlog::details::os::default_eol))); } -TEST_CASE("to_hex_upper", "[to_hex]") -{ +TEST_CASE("to_hex_upper", "[to_hex]") { std::ostringstream oss; auto oss_sink = std::make_shared(oss); spdlog::logger oss_logger("oss", oss_sink); @@ -25,11 +24,11 @@ TEST_CASE("to_hex_upper", "[to_hex]") oss_logger.info("{:X}", spdlog::to_hex(v)); auto output = oss.str(); - REQUIRE(ends_with(output, "0000: 09 0A 0B 0C FF FF" + std::string(spdlog::details::os::default_eol))); + REQUIRE(ends_with(output, + "0000: 09 0A 0B 0C FF FF" + std::string(spdlog::details::os::default_eol))); } -TEST_CASE("to_hex_no_delimiter", "[to_hex]") -{ +TEST_CASE("to_hex_no_delimiter", "[to_hex]") { std::ostringstream oss; auto oss_sink = std::make_shared(oss); spdlog::logger oss_logger("oss", oss_sink); @@ -38,11 +37,11 @@ TEST_CASE("to_hex_no_delimiter", "[to_hex]") oss_logger.info("{:sX}", spdlog::to_hex(v)); auto output = oss.str(); - REQUIRE(ends_with(output, "0000: 090A0B0CFFFF" + std::string(spdlog::details::os::default_eol))); + REQUIRE( + ends_with(output, "0000: 090A0B0CFFFF" + std::string(spdlog::details::os::default_eol))); } -TEST_CASE("to_hex_show_ascii", "[to_hex]") -{ +TEST_CASE("to_hex_show_ascii", "[to_hex]") { std::ostringstream oss; auto oss_sink = std::make_shared(oss); spdlog::logger oss_logger("oss", oss_sink); @@ -50,11 +49,11 @@ TEST_CASE("to_hex_show_ascii", "[to_hex]") std::vector v{9, 0xa, 0xb, 0x41, 0xc, 0x4b, 0xff, 0xff}; oss_logger.info("{:Xsa}", spdlog::to_hex(v, 8)); - REQUIRE(ends_with(oss.str(), "0000: 090A0B410C4BFFFF ...A.K.." + std::string(spdlog::details::os::default_eol))); + REQUIRE(ends_with(oss.str(), "0000: 090A0B410C4BFFFF ...A.K.." + + std::string(spdlog::details::os::default_eol))); } -TEST_CASE("to_hex_different_size_per_line", "[to_hex]") -{ +TEST_CASE("to_hex_different_size_per_line", "[to_hex]") { std::ostringstream oss; auto oss_sink = std::make_shared(oss); spdlog::logger oss_logger("oss", oss_sink); @@ -62,22 +61,25 @@ TEST_CASE("to_hex_different_size_per_line", "[to_hex]") std::vector v{9, 0xa, 0xb, 0x41, 0xc, 0x4b, 0xff, 0xff}; oss_logger.info("{:Xsa}", spdlog::to_hex(v, 10)); - REQUIRE(ends_with(oss.str(), "0000: 090A0B410C4BFFFF ...A.K.." + std::string(spdlog::details::os::default_eol))); - - oss_logger.info("{:Xs}", spdlog::to_hex(v, 10)); - REQUIRE(ends_with(oss.str(), "0000: 090A0B410C4BFFFF" + std::string(spdlog::details::os::default_eol))); - - oss_logger.info("{:Xsa}", spdlog::to_hex(v, 6)); - REQUIRE(ends_with(oss.str(), "0000: 090A0B410C4B ...A.K" + std::string(spdlog::details::os::default_eol) + "0006: FFFF .." + + REQUIRE(ends_with(oss.str(), "0000: 090A0B410C4BFFFF ...A.K.." + std::string(spdlog::details::os::default_eol))); + oss_logger.info("{:Xs}", spdlog::to_hex(v, 10)); + REQUIRE(ends_with(oss.str(), + "0000: 090A0B410C4BFFFF" + std::string(spdlog::details::os::default_eol))); + + oss_logger.info("{:Xsa}", spdlog::to_hex(v, 6)); + REQUIRE(ends_with( + oss.str(), "0000: 090A0B410C4B ...A.K" + std::string(spdlog::details::os::default_eol) + + "0006: FFFF .." + std::string(spdlog::details::os::default_eol))); + oss_logger.info("{:Xs}", spdlog::to_hex(v, 6)); - REQUIRE(ends_with(oss.str(), "0000: 090A0B410C4B" + std::string(spdlog::details::os::default_eol) + "0006: FFFF" + + REQUIRE(ends_with(oss.str(), "0000: 090A0B410C4B" + + std::string(spdlog::details::os::default_eol) + "0006: FFFF" + std::string(spdlog::details::os::default_eol))); } -TEST_CASE("to_hex_no_ascii", "[to_hex]") -{ +TEST_CASE("to_hex_no_ascii", "[to_hex]") { std::ostringstream oss; auto oss_sink = std::make_shared(oss); spdlog::logger oss_logger("oss", oss_sink); @@ -85,9 +87,11 @@ TEST_CASE("to_hex_no_ascii", "[to_hex]") std::vector v{9, 0xa, 0xb, 0x41, 0xc, 0x4b, 0xff, 0xff}; oss_logger.info("{:Xs}", spdlog::to_hex(v, 8)); - REQUIRE(ends_with(oss.str(), "0000: 090A0B410C4BFFFF" + std::string(spdlog::details::os::default_eol))); + REQUIRE(ends_with(oss.str(), + "0000: 090A0B410C4BFFFF" + std::string(spdlog::details::os::default_eol))); oss_logger.info("{:Xsna}", spdlog::to_hex(v, 8)); - REQUIRE(ends_with(oss.str(), "090A0B410C4BFFFF" + std::string(spdlog::details::os::default_eol))); + REQUIRE( + ends_with(oss.str(), "090A0B410C4BFFFF" + std::string(spdlog::details::os::default_eol))); } diff --git a/tests/test_cfg.cpp b/tests/test_cfg.cpp index 11aefa20..684d870c 100644 --- a/tests/test_cfg.cpp +++ b/tests/test_cfg.cpp @@ -9,8 +9,7 @@ using spdlog::cfg::load_argv_levels; using spdlog::cfg::load_env_levels; using spdlog::sinks::test_sink_st; -TEST_CASE("env", "[cfg]") -{ +TEST_CASE("env", "[cfg]") { spdlog::drop("l1"); auto l1 = spdlog::create("l1"); #ifdef CATCH_PLATFORM_WINDOWS @@ -24,8 +23,7 @@ TEST_CASE("env", "[cfg]") REQUIRE(spdlog::default_logger()->level() == spdlog::level::info); } -TEST_CASE("argv1", "[cfg]") -{ +TEST_CASE("argv1", "[cfg]") { spdlog::drop("l1"); const char *argv[] = {"ignore", "SPDLOG_LEVEL=l1=warn"}; load_argv_levels(2, argv); @@ -34,8 +32,7 @@ TEST_CASE("argv1", "[cfg]") REQUIRE(spdlog::default_logger()->level() == spdlog::level::info); } -TEST_CASE("argv2", "[cfg]") -{ +TEST_CASE("argv2", "[cfg]") { spdlog::drop("l1"); const char *argv[] = {"ignore", "SPDLOG_LEVEL=l1=warn,trace"}; load_argv_levels(2, argv); @@ -44,8 +41,7 @@ TEST_CASE("argv2", "[cfg]") REQUIRE(spdlog::default_logger()->level() == spdlog::level::trace); } -TEST_CASE("argv3", "[cfg]") -{ +TEST_CASE("argv3", "[cfg]") { spdlog::set_level(spdlog::level::trace); spdlog::drop("l1"); @@ -56,8 +52,7 @@ TEST_CASE("argv3", "[cfg]") REQUIRE(spdlog::default_logger()->level() == spdlog::level::trace); } -TEST_CASE("argv4", "[cfg]") -{ +TEST_CASE("argv4", "[cfg]") { spdlog::set_level(spdlog::level::info); spdlog::drop("l1"); const char *argv[] = {"ignore", "SPDLOG_LEVEL=junk"}; @@ -66,8 +61,7 @@ TEST_CASE("argv4", "[cfg]") REQUIRE(l1->level() == spdlog::level::info); } -TEST_CASE("argv5", "[cfg]") -{ +TEST_CASE("argv5", "[cfg]") { spdlog::set_level(spdlog::level::info); spdlog::drop("l1"); const char *argv[] = {"ignore", "ignore", "SPDLOG_LEVEL=l1=warn,trace"}; @@ -78,8 +72,7 @@ TEST_CASE("argv5", "[cfg]") spdlog::set_level(spdlog::level::info); } -TEST_CASE("argv6", "[cfg]") -{ +TEST_CASE("argv6", "[cfg]") { spdlog::set_level(spdlog::level::err); const char *argv[] = {""}; load_argv_levels(1, argv); @@ -87,8 +80,7 @@ TEST_CASE("argv6", "[cfg]") spdlog::set_level(spdlog::level::info); } -TEST_CASE("argv7", "[cfg]") -{ +TEST_CASE("argv7", "[cfg]") { spdlog::set_level(spdlog::level::err); const char *argv[] = {""}; load_argv_levels(0, argv); @@ -96,8 +88,7 @@ TEST_CASE("argv7", "[cfg]") spdlog::set_level(spdlog::level::info); } -TEST_CASE("level-not-set-test1", "[cfg]") -{ +TEST_CASE("level-not-set-test1", "[cfg]") { spdlog::drop("l1"); const char *argv[] = {"ignore", ""}; load_argv_levels(2, argv); @@ -107,8 +98,7 @@ TEST_CASE("level-not-set-test1", "[cfg]") REQUIRE(spdlog::default_logger()->level() == spdlog::level::info); } -TEST_CASE("level-not-set-test2", "[cfg]") -{ +TEST_CASE("level-not-set-test2", "[cfg]") { spdlog::drop("l1"); spdlog::drop("l2"); const char *argv[] = {"ignore", "SPDLOG_LEVEL=l1=trace"}; @@ -125,8 +115,7 @@ TEST_CASE("level-not-set-test2", "[cfg]") REQUIRE(spdlog::default_logger()->level() == spdlog::level::info); } -TEST_CASE("level-not-set-test3", "[cfg]") -{ +TEST_CASE("level-not-set-test3", "[cfg]") { spdlog::drop("l1"); spdlog::drop("l2"); const char *argv[] = {"ignore", "SPDLOG_LEVEL=l1=trace"}; @@ -141,8 +130,7 @@ TEST_CASE("level-not-set-test3", "[cfg]") REQUIRE(spdlog::default_logger()->level() == spdlog::level::info); } -TEST_CASE("level-not-set-test4", "[cfg]") -{ +TEST_CASE("level-not-set-test4", "[cfg]") { spdlog::drop("l1"); spdlog::drop("l2"); const char *argv[] = {"ignore", "SPDLOG_LEVEL=l1=trace,warn"}; @@ -157,8 +145,7 @@ TEST_CASE("level-not-set-test4", "[cfg]") REQUIRE(spdlog::default_logger()->level() == spdlog::level::warn); } -TEST_CASE("level-not-set-test5", "[cfg]") -{ +TEST_CASE("level-not-set-test5", "[cfg]") { spdlog::drop("l1"); spdlog::drop("l2"); const char *argv[] = {"ignore", "SPDLOG_LEVEL=l1=junk,warn"}; @@ -173,8 +160,7 @@ TEST_CASE("level-not-set-test5", "[cfg]") REQUIRE(spdlog::default_logger()->level() == spdlog::level::warn); } -TEST_CASE("restore-to-default", "[cfg]") -{ +TEST_CASE("restore-to-default", "[cfg]") { spdlog::drop("l1"); spdlog::drop("l2"); const char *argv[] = {"ignore", "SPDLOG_LEVEL=info"}; diff --git a/tests/test_circular_q.cpp b/tests/test_circular_q.cpp index fd91503a..c8b02d36 100644 --- a/tests/test_circular_q.cpp +++ b/tests/test_circular_q.cpp @@ -2,14 +2,12 @@ #include "spdlog/details/circular_q.h" using q_type = spdlog::details::circular_q; -TEST_CASE("test_size", "[circular_q]") -{ +TEST_CASE("test_size", "[circular_q]") { const size_t q_size = 4; q_type q(q_size); REQUIRE(q.size() == 0); REQUIRE(q.empty() == true); - for (size_t i = 0; i < q_size; i++) - { + for (size_t i = 0; i < q_size; i++) { q.push_back(std::move(i)); } REQUIRE(q.size() == q_size); @@ -17,13 +15,11 @@ TEST_CASE("test_size", "[circular_q]") REQUIRE(q.size() == q_size); } -TEST_CASE("test_rolling", "[circular_q]") -{ +TEST_CASE("test_rolling", "[circular_q]") { const size_t q_size = 4; q_type q(q_size); - for (size_t i = 0; i < q_size + 2; i++) - { + for (size_t i = 0; i < q_size + 2; i++) { q.push_back(std::move(i)); } @@ -47,8 +43,7 @@ TEST_CASE("test_rolling", "[circular_q]") REQUIRE(q.front() == 6); } -TEST_CASE("test_empty", "[circular_q]") -{ +TEST_CASE("test_empty", "[circular_q]") { q_type q(0); q.push_back(1); REQUIRE(q.empty()); diff --git a/tests/test_create_dir.cpp b/tests/test_create_dir.cpp index f17126bc..b53bebf1 100644 --- a/tests/test_create_dir.cpp +++ b/tests/test_create_dir.cpp @@ -1,40 +1,46 @@ /* - * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + * This content is released under the MIT License as specified in + * https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE */ #include "includes.h" using spdlog::details::os::create_dir; using spdlog::details::os::path_exists; -bool try_create_dir(const spdlog::filename_t &path, const spdlog::filename_t &normalized_path) -{ +bool try_create_dir(const spdlog::filename_t &path, const spdlog::filename_t &normalized_path) { auto rv = create_dir(path); REQUIRE(rv == true); return path_exists(normalized_path); } -TEST_CASE("create_dir", "[create_dir]") -{ +TEST_CASE("create_dir", "[create_dir]") { prepare_logdir(); - REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/dir1/dir1"), SPDLOG_FILENAME_T("test_logs/dir1/dir1"))); - REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/dir1/dir1"), SPDLOG_FILENAME_T("test_logs/dir1/dir1"))); // test existing - REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/dir1///dir2//"), SPDLOG_FILENAME_T("test_logs/dir1/dir2"))); - REQUIRE(try_create_dir(SPDLOG_FILENAME_T("./test_logs/dir1/dir3"), SPDLOG_FILENAME_T("test_logs/dir1/dir3"))); - REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/../test_logs/dir1/dir4"), SPDLOG_FILENAME_T("test_logs/dir1/dir4"))); + REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/dir1/dir1"), + SPDLOG_FILENAME_T("test_logs/dir1/dir1"))); + REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/dir1/dir1"), + SPDLOG_FILENAME_T("test_logs/dir1/dir1"))); // test existing + REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/dir1///dir2//"), + SPDLOG_FILENAME_T("test_logs/dir1/dir2"))); + REQUIRE(try_create_dir(SPDLOG_FILENAME_T("./test_logs/dir1/dir3"), + SPDLOG_FILENAME_T("test_logs/dir1/dir3"))); + REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/../test_logs/dir1/dir4"), + SPDLOG_FILENAME_T("test_logs/dir1/dir4"))); #ifdef WIN32 // test backslash folder separator - REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs\\dir1\\dir222"), SPDLOG_FILENAME_T("test_logs\\dir1\\dir222"))); - REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs\\dir1\\dir223\\"), SPDLOG_FILENAME_T("test_logs\\dir1\\dir223\\"))); - REQUIRE( - try_create_dir(SPDLOG_FILENAME_T(".\\test_logs\\dir1\\dir2\\dir99\\..\\dir23"), SPDLOG_FILENAME_T("test_logs\\dir1\\dir2\\dir23"))); - REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs\\..\\test_logs\\dir1\\dir5"), SPDLOG_FILENAME_T("test_logs\\dir1\\dir5"))); + REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs\\dir1\\dir222"), + SPDLOG_FILENAME_T("test_logs\\dir1\\dir222"))); + REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs\\dir1\\dir223\\"), + SPDLOG_FILENAME_T("test_logs\\dir1\\dir223\\"))); + REQUIRE(try_create_dir(SPDLOG_FILENAME_T(".\\test_logs\\dir1\\dir2\\dir99\\..\\dir23"), + SPDLOG_FILENAME_T("test_logs\\dir1\\dir2\\dir23"))); + REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs\\..\\test_logs\\dir1\\dir5"), + SPDLOG_FILENAME_T("test_logs\\dir1\\dir5"))); #endif } -TEST_CASE("create_invalid_dir", "[create_dir]") -{ +TEST_CASE("create_invalid_dir", "[create_dir]") { REQUIRE(create_dir(SPDLOG_FILENAME_T("")) == false); REQUIRE(create_dir(spdlog::filename_t{}) == false); #ifdef __linux__ @@ -42,8 +48,7 @@ TEST_CASE("create_invalid_dir", "[create_dir]") #endif } -TEST_CASE("dir_name", "[create_dir]") -{ +TEST_CASE("dir_name", "[create_dir]") { using spdlog::details::os::dir_name; REQUIRE(dir_name(SPDLOG_FILENAME_T("")).empty()); REQUIRE(dir_name(SPDLOG_FILENAME_T("dir")).empty()); @@ -55,13 +60,16 @@ TEST_CASE("dir_name", "[create_dir]") REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(dir/file)")) == SPDLOG_FILENAME_T("dir")); REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(dir\file.txt)")) == SPDLOG_FILENAME_T("dir")); REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(dir/file)")) == SPDLOG_FILENAME_T("dir")); - REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(dir\file.txt\)")) == SPDLOG_FILENAME_T(R"(dir\file.txt)")); + REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(dir\file.txt\)")) == + SPDLOG_FILENAME_T(R"(dir\file.txt)")); REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(\dir\file.txt)")) == SPDLOG_FILENAME_T(R"(\dir)")); REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(\\dir\file.txt)")) == SPDLOG_FILENAME_T(R"(\\dir)")); REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(..\file.txt)")) == SPDLOG_FILENAME_T("..")); REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(.\file.txt)")) == SPDLOG_FILENAME_T(".")); - REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(c:\\a\b\c\d\file.txt)")) == SPDLOG_FILENAME_T(R"(c:\\a\b\c\d)")); - REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(c://a/b/c/d/file.txt)")) == SPDLOG_FILENAME_T(R"(c://a/b/c/d)")); + REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(c:\\a\b\c\d\file.txt)")) == + SPDLOG_FILENAME_T(R"(c:\\a\b\c\d)")); + REQUIRE(dir_name(SPDLOG_FILENAME_T(R"(c://a/b/c/d/file.txt)")) == + SPDLOG_FILENAME_T(R"(c://a/b/c/d)")); #endif REQUIRE(dir_name(SPDLOG_FILENAME_T("dir/")) == SPDLOG_FILENAME_T("dir")); REQUIRE(dir_name(SPDLOG_FILENAME_T("dir///")) == SPDLOG_FILENAME_T("dir//")); diff --git a/tests/test_custom_callbacks.cpp b/tests/test_custom_callbacks.cpp index 78babd79..4b048572 100644 --- a/tests/test_custom_callbacks.cpp +++ b/tests/test_custom_callbacks.cpp @@ -1,5 +1,6 @@ /* - * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + * This content is released under the MIT License as specified in + * https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE */ #include "includes.h" #include "test_sink.h" @@ -7,16 +8,16 @@ #include "spdlog/async.h" #include "spdlog/common.h" -TEST_CASE("custom_callback_logger", "[custom_callback_logger]") -{ +TEST_CASE("custom_callback_logger", "[custom_callback_logger]") { std::vector lines; spdlog::pattern_formatter formatter; - auto callback_logger = std::make_shared([&](const spdlog::details::log_msg &msg) { - spdlog::memory_buf_t formatted; - formatter.format(msg, formatted); - auto eol_len = strlen(spdlog::details::os::default_eol); - lines.emplace_back(formatted.begin(), formatted.end() - eol_len); - }); + auto callback_logger = + std::make_shared([&](const spdlog::details::log_msg &msg) { + spdlog::memory_buf_t formatted; + formatter.format(msg, formatted); + auto eol_len = strlen(spdlog::details::os::default_eol); + lines.emplace_back(formatted.begin(), formatted.end() - eol_len); + }); std::shared_ptr test_sink(new spdlog::sinks::test_sink_st); spdlog::logger logger("test-callback", {callback_logger, test_sink}); diff --git a/tests/test_daily_logger.cpp b/tests/test_daily_logger.cpp index 82f28941..138e6120 100644 --- a/tests/test_daily_logger.cpp +++ b/tests/test_daily_logger.cpp @@ -1,5 +1,6 @@ /* - * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + * This content is released under the MIT License as specified in + * https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE */ #include "includes.h" @@ -10,22 +11,20 @@ using filename_memory_buf_t = fmt::basic_memory_buffer; +TEST_CASE("daily_logger with dateonly calculator", "[daily_logger]") { + using sink_type = + spdlog::sinks::daily_file_sink; prepare_logdir(); @@ -33,12 +32,11 @@ TEST_CASE("daily_logger with dateonly calculator", "[daily_logger]") spdlog::filename_t basename = SPDLOG_FILENAME_T("test_logs/daily_dateonly"); std::tm tm = spdlog::details::os::localtime(); filename_memory_buf_t w; - spdlog::fmt_lib::format_to( - std::back_inserter(w), SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}"), basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); + spdlog::fmt_lib::format_to(std::back_inserter(w), SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}"), + basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); auto logger = spdlog::create("logger", basename, 0, 0); - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { logger->info("Test message {}", i); } @@ -47,20 +45,18 @@ TEST_CASE("daily_logger with dateonly calculator", "[daily_logger]") require_message_count(filename_buf_to_utf8string(w), 10); } -struct custom_daily_file_name_calculator -{ - static spdlog::filename_t calc_filename(const spdlog::filename_t &basename, const tm &now_tm) - { +struct custom_daily_file_name_calculator { + static spdlog::filename_t calc_filename(const spdlog::filename_t &basename, const tm &now_tm) { filename_memory_buf_t w; - spdlog::fmt_lib::format_to(std::back_inserter(w), SPDLOG_FILENAME_T("{}{:04d}{:02d}{:02d}"), basename, now_tm.tm_year + 1900, - now_tm.tm_mon + 1, now_tm.tm_mday); + spdlog::fmt_lib::format_to(std::back_inserter(w), SPDLOG_FILENAME_T("{}{:04d}{:02d}{:02d}"), + basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1, + now_tm.tm_mday); return SPDLOG_BUF_TO_STRING(w); } }; -TEST_CASE("daily_logger with custom calculator", "[daily_logger]") -{ +TEST_CASE("daily_logger with custom calculator", "[daily_logger]") { using sink_type = spdlog::sinks::daily_file_sink; prepare_logdir(); @@ -69,12 +65,11 @@ TEST_CASE("daily_logger with custom calculator", "[daily_logger]") spdlog::filename_t basename = SPDLOG_FILENAME_T("test_logs/daily_dateonly"); std::tm tm = spdlog::details::os::localtime(); filename_memory_buf_t w; - spdlog::fmt_lib::format_to( - std::back_inserter(w), SPDLOG_FILENAME_T("{}{:04d}{:02d}{:02d}"), basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); + spdlog::fmt_lib::format_to(std::back_inserter(w), SPDLOG_FILENAME_T("{}{:04d}{:02d}{:02d}"), + basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); auto logger = spdlog::create("logger", basename, 0, 0); - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { logger->info("Test message {}", i); } @@ -87,34 +82,33 @@ TEST_CASE("daily_logger with custom calculator", "[daily_logger]") * File name calculations */ -TEST_CASE("rotating_file_sink::calc_filename1", "[rotating_file_sink]") -{ - auto filename = spdlog::sinks::rotating_file_sink_st::calc_filename(SPDLOG_FILENAME_T("rotated.txt"), 3); +TEST_CASE("rotating_file_sink::calc_filename1", "[rotating_file_sink]") { + auto filename = + spdlog::sinks::rotating_file_sink_st::calc_filename(SPDLOG_FILENAME_T("rotated.txt"), 3); REQUIRE(filename == SPDLOG_FILENAME_T("rotated.3.txt")); } -TEST_CASE("rotating_file_sink::calc_filename2", "[rotating_file_sink]") -{ - auto filename = spdlog::sinks::rotating_file_sink_st::calc_filename(SPDLOG_FILENAME_T("rotated"), 3); +TEST_CASE("rotating_file_sink::calc_filename2", "[rotating_file_sink]") { + auto filename = + spdlog::sinks::rotating_file_sink_st::calc_filename(SPDLOG_FILENAME_T("rotated"), 3); REQUIRE(filename == SPDLOG_FILENAME_T("rotated.3")); } -TEST_CASE("rotating_file_sink::calc_filename3", "[rotating_file_sink]") -{ - auto filename = spdlog::sinks::rotating_file_sink_st::calc_filename(SPDLOG_FILENAME_T("rotated.txt"), 0); +TEST_CASE("rotating_file_sink::calc_filename3", "[rotating_file_sink]") { + auto filename = + spdlog::sinks::rotating_file_sink_st::calc_filename(SPDLOG_FILENAME_T("rotated.txt"), 0); REQUIRE(filename == SPDLOG_FILENAME_T("rotated.txt")); } // regex supported only from gcc 4.9 and above #if defined(_MSC_VER) || !(__GNUC__ <= 4 && __GNUC_MINOR__ < 9) -# include + #include -TEST_CASE("daily_file_sink::daily_filename_calculator", "[daily_file_sink]") -{ +TEST_CASE("daily_file_sink::daily_filename_calculator", "[daily_file_sink]") { // daily_YYYY-MM-DD_hh-mm.txt - auto filename = - spdlog::sinks::daily_filename_calculator::calc_filename(SPDLOG_FILENAME_T("daily.txt"), spdlog::details::os::localtime()); + auto filename = spdlog::sinks::daily_filename_calculator::calc_filename( + SPDLOG_FILENAME_T("daily.txt"), spdlog::details::os::localtime()); // date regex based on https://www.regular-expressions.info/dates.html std::basic_regex re( SPDLOG_FILENAME_T(R"(^daily_(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])\.txt$)")); @@ -123,27 +117,26 @@ TEST_CASE("daily_file_sink::daily_filename_calculator", "[daily_file_sink]") } #endif -TEST_CASE("daily_file_sink::daily_filename_format_calculator", "[daily_file_sink]") -{ +TEST_CASE("daily_file_sink::daily_filename_format_calculator", "[daily_file_sink]") { std::tm tm = spdlog::details::os::localtime(); // example-YYYY-MM-DD.log - auto filename = spdlog::sinks::daily_filename_format_calculator::calc_filename(SPDLOG_FILENAME_T("example-%Y-%m-%d.log"), tm); + auto filename = spdlog::sinks::daily_filename_format_calculator::calc_filename( + SPDLOG_FILENAME_T("example-%Y-%m-%d.log"), tm); REQUIRE(filename == - spdlog::fmt_lib::format(SPDLOG_FILENAME_T("example-{:04d}-{:02d}-{:02d}.log"), tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday)); + spdlog::fmt_lib::format(SPDLOG_FILENAME_T("example-{:04d}-{:02d}-{:02d}.log"), + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday)); } /* Test removal of old files */ -static spdlog::details::log_msg create_msg(std::chrono::seconds offset) -{ +static spdlog::details::log_msg create_msg(std::chrono::seconds offset) { using spdlog::log_clock; spdlog::details::log_msg msg{"test", spdlog::level::info, "Hello Message"}; msg.time = log_clock::now() + offset; return msg; } -static void test_rotate(int days_to_run, uint16_t max_days, uint16_t expected_n_files) -{ +static void test_rotate(int days_to_run, uint16_t max_days, uint16_t expected_n_files) { using spdlog::log_clock; using spdlog::details::log_msg; using spdlog::sinks::daily_file_sink_st; @@ -155,8 +148,7 @@ static void test_rotate(int days_to_run, uint16_t max_days, uint16_t expected_n_ // simulate messages with 24 intervals - for (int i = 0; i < days_to_run; i++) - { + for (int i = 0; i < days_to_run; i++) { auto offset = std::chrono::seconds{24 * 3600 * i}; sink.log(create_msg(offset)); } @@ -164,8 +156,7 @@ static void test_rotate(int days_to_run, uint16_t max_days, uint16_t expected_n_ REQUIRE(count_files("test_logs") == static_cast(expected_n_files)); } -TEST_CASE("daily_logger rotate", "[daily_file_sink]") -{ +TEST_CASE("daily_logger rotate", "[daily_file_sink]") { int days_to_run = 1; test_rotate(days_to_run, 0, 1); test_rotate(days_to_run, 1, 1); diff --git a/tests/test_dup_filter.cpp b/tests/test_dup_filter.cpp index 8ae2ee60..22623c2e 100644 --- a/tests/test_dup_filter.cpp +++ b/tests/test_dup_filter.cpp @@ -2,8 +2,7 @@ #include "spdlog/sinks/dup_filter_sink.h" #include "test_sink.h" -TEST_CASE("dup_filter_test1", "[dup_filter_sink]") -{ +TEST_CASE("dup_filter_test1", "[dup_filter_sink]") { using spdlog::sinks::dup_filter_sink_st; using spdlog::sinks::test_sink_mt; @@ -11,16 +10,14 @@ TEST_CASE("dup_filter_test1", "[dup_filter_sink]") auto test_sink = std::make_shared(); dup_sink.add_sink(test_sink); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"}); } REQUIRE(test_sink->msg_counter() == 1); } -TEST_CASE("dup_filter_test2", "[dup_filter_sink]") -{ +TEST_CASE("dup_filter_test2", "[dup_filter_sink]") { using spdlog::sinks::dup_filter_sink_st; using spdlog::sinks::test_sink_mt; @@ -28,8 +25,7 @@ TEST_CASE("dup_filter_test2", "[dup_filter_sink]") auto test_sink = std::make_shared(); dup_sink.add_sink(test_sink); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"}); std::this_thread::sleep_for(std::chrono::milliseconds(5)); } @@ -37,8 +33,7 @@ TEST_CASE("dup_filter_test2", "[dup_filter_sink]") REQUIRE(test_sink->msg_counter() == 10); } -TEST_CASE("dup_filter_test3", "[dup_filter_sink]") -{ +TEST_CASE("dup_filter_test3", "[dup_filter_sink]") { using spdlog::sinks::dup_filter_sink_st; using spdlog::sinks::test_sink_mt; @@ -46,8 +41,7 @@ TEST_CASE("dup_filter_test3", "[dup_filter_sink]") auto test_sink = std::make_shared(); dup_sink.add_sink(test_sink); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"}); dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message2"}); } @@ -55,8 +49,7 @@ TEST_CASE("dup_filter_test3", "[dup_filter_sink]") REQUIRE(test_sink->msg_counter() == 20); } -TEST_CASE("dup_filter_test4", "[dup_filter_sink]") -{ +TEST_CASE("dup_filter_test4", "[dup_filter_sink]") { using spdlog::sinks::dup_filter_sink_mt; using spdlog::sinks::test_sink_mt; @@ -70,8 +63,7 @@ TEST_CASE("dup_filter_test4", "[dup_filter_sink]") REQUIRE(test_sink->msg_counter() == 2); } -TEST_CASE("dup_filter_test5", "[dup_filter_sink]") -{ +TEST_CASE("dup_filter_test5", "[dup_filter_sink]") { using spdlog::sinks::dup_filter_sink_mt; using spdlog::sinks::test_sink_mt; @@ -85,6 +77,7 @@ TEST_CASE("dup_filter_test5", "[dup_filter_sink]") dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"}); dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message2"}); - REQUIRE(test_sink->msg_counter() == 3); // skip 2 messages but log the "skipped.." message before message2 + REQUIRE(test_sink->msg_counter() == + 3); // skip 2 messages but log the "skipped.." message before message2 REQUIRE(test_sink->lines()[1] == "Skipped 2 duplicate messages.."); } diff --git a/tests/test_errors.cpp b/tests/test_errors.cpp index 78032482..f985fd4e 100644 --- a/tests/test_errors.cpp +++ b/tests/test_errors.cpp @@ -1,5 +1,6 @@ /* - * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + * This content is released under the MIT License as specified in + * https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE */ #include "includes.h" @@ -8,25 +9,18 @@ #define SIMPLE_LOG "test_logs/simple_log.txt" #define SIMPLE_ASYNC_LOG "test_logs/simple_async_log.txt" -class failing_sink : public spdlog::sinks::base_sink -{ +class failing_sink : public spdlog::sinks::base_sink { protected: - void sink_it_(const spdlog::details::log_msg &) final - { + void sink_it_(const spdlog::details::log_msg &) final { throw std::runtime_error("some error happened during log"); } - void flush_() final - { - throw std::runtime_error("some error happened during flush"); - } + void flush_() final { throw std::runtime_error("some error happened during flush"); } }; -struct custom_ex -{}; +struct custom_ex {}; #if !defined(SPDLOG_USE_STD_FORMAT) // std formt doesn't fully support tuntime strings -TEST_CASE("default_error_handler", "[errors]") -{ +TEST_CASE("default_error_handler", "[errors]") { prepare_logdir(); spdlog::filename_t filename = SPDLOG_FILENAME_T(SIMPLE_LOG); @@ -40,8 +34,7 @@ TEST_CASE("default_error_handler", "[errors]") REQUIRE(count_lines(SIMPLE_LOG) == 1); } -TEST_CASE("custom_error_handler", "[errors]") -{ +TEST_CASE("custom_error_handler", "[errors]") { prepare_logdir(); spdlog::filename_t filename = SPDLOG_FILENAME_T(SIMPLE_LOG); auto logger = spdlog::create("logger", filename, true); @@ -55,16 +48,14 @@ TEST_CASE("custom_error_handler", "[errors]") } #endif -TEST_CASE("default_error_handler2", "[errors]") -{ +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(); }); REQUIRE_THROWS_AS(logger->info("Some message"), custom_ex); } -TEST_CASE("flush_error_handler", "[errors]") -{ +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(); }); @@ -72,19 +63,18 @@ TEST_CASE("flush_error_handler", "[errors]") } #if !defined(SPDLOG_USE_STD_FORMAT) -TEST_CASE("async_error_handler", "[errors]") -{ +TEST_CASE("async_error_handler", "[errors]") { prepare_logdir(); std::string err_msg("log failed with some msg"); spdlog::filename_t filename = SPDLOG_FILENAME_T(SIMPLE_ASYNC_LOG); { spdlog::init_thread_pool(128, 1); - auto logger = spdlog::create_async("logger", filename, true); + auto logger = + spdlog::create_async("logger", filename, true); logger->set_error_handler([=](const std::string &) { std::ofstream ofs("test_logs/custom_err.txt"); - if (!ofs) - { + if (!ofs) { throw std::runtime_error("Failed open test_logs/custom_err.txt"); } ofs << err_msg; @@ -101,8 +91,7 @@ TEST_CASE("async_error_handler", "[errors]") #endif // Make sure async error handler is executed -TEST_CASE("async_error_handler2", "[errors]") -{ +TEST_CASE("async_error_handler2", "[errors]") { prepare_logdir(); std::string err_msg("This is async handler error message"); { diff --git a/tests/test_eventlog.cpp b/tests/test_eventlog.cpp index 5253c5a7..45d7f58d 100644 --- a/tests/test_eventlog.cpp +++ b/tests/test_eventlog.cpp @@ -1,26 +1,25 @@ #if _WIN32 -# include "includes.h" -# include "test_sink.h" + #include "includes.h" + #include "test_sink.h" -# include "spdlog/sinks/win_eventlog_sink.h" + #include "spdlog/sinks/win_eventlog_sink.h" static const LPCSTR TEST_SOURCE = "spdlog_test"; -static void test_single_print(std::function do_log, std::string const &expected_contents, WORD expected_ev_type) -{ +static void test_single_print(std::function do_log, + std::string const &expected_contents, + WORD expected_ev_type) { using namespace std::chrono; do_log(expected_contents); - const auto expected_time_generated = duration_cast(system_clock::now().time_since_epoch()).count(); + const auto expected_time_generated = + duration_cast(system_clock::now().time_since_epoch()).count(); - struct handle_t - { + struct handle_t { HANDLE handle_; - ~handle_t() - { - if (handle_) - { + ~handle_t() { + if (handle_) { REQUIRE(CloseEventLog(handle_)); } } @@ -29,16 +28,16 @@ static void test_single_print(std::function do_log, s REQUIRE(event_log.handle_); DWORD read_bytes{}, size_needed{}; - auto ok = ::ReadEventLogA( - event_log.handle_, EVENTLOG_SEQUENTIAL_READ | EVENTLOG_BACKWARDS_READ, 0, &read_bytes, 0, &read_bytes, &size_needed); + auto ok = ::ReadEventLogA(event_log.handle_, EVENTLOG_SEQUENTIAL_READ | EVENTLOG_BACKWARDS_READ, + 0, &read_bytes, 0, &read_bytes, &size_needed); REQUIRE(!ok); REQUIRE(::GetLastError() == ERROR_INSUFFICIENT_BUFFER); std::vector record_buffer(size_needed); PEVENTLOGRECORD record = (PEVENTLOGRECORD)record_buffer.data(); - ok = ::ReadEventLogA( - event_log.handle_, EVENTLOG_SEQUENTIAL_READ | EVENTLOG_BACKWARDS_READ, 0, record, size_needed, &read_bytes, &size_needed); + ok = ::ReadEventLogA(event_log.handle_, EVENTLOG_SEQUENTIAL_READ | EVENTLOG_BACKWARDS_READ, 0, + record, size_needed, &read_bytes, &size_needed); REQUIRE(ok); REQUIRE(record->NumStrings == 1); @@ -49,8 +48,7 @@ static void test_single_print(std::function do_log, s REQUIRE(message_in_log == expected_contents + spdlog::details::os::default_eol); } -TEST_CASE("eventlog", "[eventlog]") -{ +TEST_CASE("eventlog", "[eventlog]") { using namespace spdlog; auto test_sink = std::make_shared(TEST_SOURCE); @@ -60,12 +58,18 @@ TEST_CASE("eventlog", "[eventlog]") test_sink->set_pattern("%v"); - test_single_print([&test_logger](std::string const &msg) { test_logger.trace(msg); }, "my trace message", EVENTLOG_SUCCESS); - test_single_print([&test_logger](std::string const &msg) { test_logger.debug(msg); }, "my debug message", EVENTLOG_SUCCESS); - test_single_print([&test_logger](std::string const &msg) { test_logger.info(msg); }, "my info message", EVENTLOG_INFORMATION_TYPE); - test_single_print([&test_logger](std::string const &msg) { test_logger.warn(msg); }, "my warn message", EVENTLOG_WARNING_TYPE); - test_single_print([&test_logger](std::string const &msg) { test_logger.error(msg); }, "my error message", EVENTLOG_ERROR_TYPE); - test_single_print([&test_logger](std::string const &msg) { test_logger.critical(msg); }, "my critical message", EVENTLOG_ERROR_TYPE); + test_single_print([&test_logger](std::string const &msg) { test_logger.trace(msg); }, + "my trace message", EVENTLOG_SUCCESS); + test_single_print([&test_logger](std::string const &msg) { test_logger.debug(msg); }, + "my debug message", EVENTLOG_SUCCESS); + test_single_print([&test_logger](std::string const &msg) { test_logger.info(msg); }, + "my info message", EVENTLOG_INFORMATION_TYPE); + test_single_print([&test_logger](std::string const &msg) { test_logger.warn(msg); }, + "my warn message", EVENTLOG_WARNING_TYPE); + test_single_print([&test_logger](std::string const &msg) { test_logger.error(msg); }, + "my error message", EVENTLOG_ERROR_TYPE); + test_single_print([&test_logger](std::string const &msg) { test_logger.critical(msg); }, + "my critical message", EVENTLOG_ERROR_TYPE); } #endif //_WIN32 diff --git a/tests/test_file_helper.cpp b/tests/test_file_helper.cpp index dd3ca4f8..de7d51d9 100644 --- a/tests/test_file_helper.cpp +++ b/tests/test_file_helper.cpp @@ -1,5 +1,6 @@ /* - * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + * This content is released under the MIT License as specified in + * https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE */ #include "includes.h" @@ -7,16 +8,14 @@ using spdlog::details::file_helper; -static void write_with_helper(file_helper &helper, size_t howmany) -{ +static void write_with_helper(file_helper &helper, size_t howmany) { spdlog::memory_buf_t formatted; spdlog::fmt_lib::format_to(std::back_inserter(formatted), "{}", std::string(howmany, '1')); helper.write(formatted); helper.flush(); } -TEST_CASE("file_helper_filename", "[file_helper::filename()]") -{ +TEST_CASE("file_helper_filename", "[file_helper::filename()]") { prepare_logdir(); file_helper helper; @@ -25,8 +24,7 @@ TEST_CASE("file_helper_filename", "[file_helper::filename()]") REQUIRE(helper.filename() == target_filename); } -TEST_CASE("file_helper_size", "[file_helper::size()]") -{ +TEST_CASE("file_helper_size", "[file_helper::size()]") { prepare_logdir(); spdlog::filename_t target_filename = SPDLOG_FILENAME_T(TEST_FILENAME); size_t expected_size = 123; @@ -39,8 +37,7 @@ TEST_CASE("file_helper_size", "[file_helper::size()]") REQUIRE(get_filesize(TEST_FILENAME) == expected_size); } -TEST_CASE("file_helper_reopen", "[file_helper::reopen()]") -{ +TEST_CASE("file_helper_reopen", "[file_helper::reopen()]") { prepare_logdir(); spdlog::filename_t target_filename = SPDLOG_FILENAME_T(TEST_FILENAME); file_helper helper; @@ -51,8 +48,7 @@ TEST_CASE("file_helper_reopen", "[file_helper::reopen()]") REQUIRE(helper.size() == 0); } -TEST_CASE("file_helper_reopen2", "[file_helper::reopen(false)]") -{ +TEST_CASE("file_helper_reopen2", "[file_helper::reopen(false)]") { prepare_logdir(); spdlog::filename_t target_filename = SPDLOG_FILENAME_T(TEST_FILENAME); size_t expected_size = 14; @@ -64,9 +60,9 @@ TEST_CASE("file_helper_reopen2", "[file_helper::reopen(false)]") REQUIRE(helper.size() == expected_size); } -static void test_split_ext(const spdlog::filename_t::value_type *fname, const spdlog::filename_t::value_type *expect_base, - const spdlog::filename_t::value_type *expect_ext) -{ +static void test_split_ext(const spdlog::filename_t::value_type *fname, + const spdlog::filename_t::value_type *expect_base, + const spdlog::filename_t::value_type *expect_ext) { spdlog::filename_t filename(fname); spdlog::filename_t expected_base(expect_base); spdlog::filename_t expected_ext(expect_ext); @@ -78,37 +74,43 @@ static void test_split_ext(const spdlog::filename_t::value_type *fname, const sp REQUIRE(ext == expected_ext); } -TEST_CASE("file_helper_split_by_extension", "[file_helper::split_by_extension()]") -{ - test_split_ext(SPDLOG_FILENAME_T("mylog.txt"), SPDLOG_FILENAME_T("mylog"), SPDLOG_FILENAME_T(".txt")); - test_split_ext(SPDLOG_FILENAME_T(".mylog.txt"), SPDLOG_FILENAME_T(".mylog"), SPDLOG_FILENAME_T(".txt")); +TEST_CASE("file_helper_split_by_extension", "[file_helper::split_by_extension()]") { + test_split_ext(SPDLOG_FILENAME_T("mylog.txt"), SPDLOG_FILENAME_T("mylog"), + SPDLOG_FILENAME_T(".txt")); + test_split_ext(SPDLOG_FILENAME_T(".mylog.txt"), SPDLOG_FILENAME_T(".mylog"), + SPDLOG_FILENAME_T(".txt")); test_split_ext(SPDLOG_FILENAME_T(".mylog"), SPDLOG_FILENAME_T(".mylog"), SPDLOG_FILENAME_T("")); - test_split_ext(SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), SPDLOG_FILENAME_T("")); - test_split_ext(SPDLOG_FILENAME_T("/aaa/bb.d/mylog.txt"), SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), SPDLOG_FILENAME_T(".txt")); - test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog.txt"), SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog"), SPDLOG_FILENAME_T(".txt")); - test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog."), SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog."), SPDLOG_FILENAME_T("")); - test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/.mylog.txt"), SPDLOG_FILENAME_T("aaa/bbb/ccc/.mylog"), SPDLOG_FILENAME_T(".txt")); - test_split_ext(SPDLOG_FILENAME_T("/aaa/bbb/ccc/mylog.txt"), SPDLOG_FILENAME_T("/aaa/bbb/ccc/mylog"), SPDLOG_FILENAME_T(".txt")); - test_split_ext(SPDLOG_FILENAME_T("/aaa/bbb/ccc/.mylog"), SPDLOG_FILENAME_T("/aaa/bbb/ccc/.mylog"), SPDLOG_FILENAME_T("")); - test_split_ext(SPDLOG_FILENAME_T("../mylog.txt"), SPDLOG_FILENAME_T("../mylog"), SPDLOG_FILENAME_T(".txt")); - test_split_ext(SPDLOG_FILENAME_T(".././mylog.txt"), SPDLOG_FILENAME_T(".././mylog"), SPDLOG_FILENAME_T(".txt")); - test_split_ext(SPDLOG_FILENAME_T(".././mylog.txt/xxx"), SPDLOG_FILENAME_T(".././mylog.txt/xxx"), SPDLOG_FILENAME_T("")); - test_split_ext(SPDLOG_FILENAME_T("/mylog.txt"), SPDLOG_FILENAME_T("/mylog"), SPDLOG_FILENAME_T(".txt")); - test_split_ext(SPDLOG_FILENAME_T("//mylog.txt"), SPDLOG_FILENAME_T("//mylog"), SPDLOG_FILENAME_T(".txt")); + test_split_ext(SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), + SPDLOG_FILENAME_T("")); + test_split_ext(SPDLOG_FILENAME_T("/aaa/bb.d/mylog.txt"), SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), + SPDLOG_FILENAME_T(".txt")); + test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog.txt"), + SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog"), SPDLOG_FILENAME_T(".txt")); + test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog."), SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog."), + SPDLOG_FILENAME_T("")); + test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/.mylog.txt"), + SPDLOG_FILENAME_T("aaa/bbb/ccc/.mylog"), SPDLOG_FILENAME_T(".txt")); + test_split_ext(SPDLOG_FILENAME_T("/aaa/bbb/ccc/mylog.txt"), + SPDLOG_FILENAME_T("/aaa/bbb/ccc/mylog"), SPDLOG_FILENAME_T(".txt")); + test_split_ext(SPDLOG_FILENAME_T("/aaa/bbb/ccc/.mylog"), + SPDLOG_FILENAME_T("/aaa/bbb/ccc/.mylog"), SPDLOG_FILENAME_T("")); + test_split_ext(SPDLOG_FILENAME_T("../mylog.txt"), SPDLOG_FILENAME_T("../mylog"), + SPDLOG_FILENAME_T(".txt")); + test_split_ext(SPDLOG_FILENAME_T(".././mylog.txt"), SPDLOG_FILENAME_T(".././mylog"), + SPDLOG_FILENAME_T(".txt")); + test_split_ext(SPDLOG_FILENAME_T(".././mylog.txt/xxx"), SPDLOG_FILENAME_T(".././mylog.txt/xxx"), + SPDLOG_FILENAME_T("")); + test_split_ext(SPDLOG_FILENAME_T("/mylog.txt"), SPDLOG_FILENAME_T("/mylog"), + SPDLOG_FILENAME_T(".txt")); + test_split_ext(SPDLOG_FILENAME_T("//mylog.txt"), SPDLOG_FILENAME_T("//mylog"), + SPDLOG_FILENAME_T(".txt")); test_split_ext(SPDLOG_FILENAME_T(""), SPDLOG_FILENAME_T(""), SPDLOG_FILENAME_T("")); test_split_ext(SPDLOG_FILENAME_T("."), SPDLOG_FILENAME_T("."), SPDLOG_FILENAME_T("")); test_split_ext(SPDLOG_FILENAME_T("..txt"), SPDLOG_FILENAME_T("."), SPDLOG_FILENAME_T(".txt")); } -TEST_CASE("file_event_handlers", "[file_helper]") -{ - enum class flags - { - before_open, - after_open, - before_close, - after_close - }; +TEST_CASE("file_event_handlers", "[file_helper]") { + enum class flags { before_open, after_open, before_close, after_close }; prepare_logdir(); spdlog::filename_t test_filename = SPDLOG_FILENAME_T(TEST_FILENAME); @@ -155,8 +157,7 @@ TEST_CASE("file_event_handlers", "[file_helper]") REQUIRE(file_contents(TEST_FILENAME) == "after_open\nbefore_close\n"); } -TEST_CASE("file_helper_open", "[file_helper]") -{ +TEST_CASE("file_helper_open", "[file_helper]") { prepare_logdir(); spdlog::filename_t target_filename = SPDLOG_FILENAME_T(TEST_FILENAME); file_helper helper; diff --git a/tests/test_file_logging.cpp b/tests/test_file_logging.cpp index 7a7119ad..73c59599 100644 --- a/tests/test_file_logging.cpp +++ b/tests/test_file_logging.cpp @@ -1,13 +1,13 @@ /* - * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + * This content is released under the MIT License as specified in + * https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE */ #include "includes.h" #define SIMPLE_LOG "test_logs/simple_log" #define ROTATING_LOG "test_logs/rotating_log" -TEST_CASE("simple_file_logger", "[simple_logger]") -{ +TEST_CASE("simple_file_logger", "[simple_logger]") { prepare_logdir(); spdlog::filename_t filename = SPDLOG_FILENAME_T(SIMPLE_LOG); @@ -20,11 +20,11 @@ TEST_CASE("simple_file_logger", "[simple_logger]") logger->flush(); require_message_count(SIMPLE_LOG, 2); using spdlog::details::os::default_eol; - REQUIRE(file_contents(SIMPLE_LOG) == spdlog::fmt_lib::format("Test message 1{}Test message 2{}", default_eol, default_eol)); + REQUIRE(file_contents(SIMPLE_LOG) == + spdlog::fmt_lib::format("Test message 1{}Test message 2{}", default_eol, default_eol)); } -TEST_CASE("flush_on", "[flush_on]") -{ +TEST_CASE("flush_on", "[flush_on]") { prepare_logdir(); spdlog::filename_t filename = SPDLOG_FILENAME_T(SIMPLE_LOG); @@ -41,18 +41,17 @@ TEST_CASE("flush_on", "[flush_on]") require_message_count(SIMPLE_LOG, 3); using spdlog::details::os::default_eol; REQUIRE(file_contents(SIMPLE_LOG) == - spdlog::fmt_lib::format("Should not be flushed{}Test message 1{}Test message 2{}", default_eol, default_eol, default_eol)); + spdlog::fmt_lib::format("Should not be flushed{}Test message 1{}Test message 2{}", + default_eol, default_eol, default_eol)); } -TEST_CASE("rotating_file_logger1", "[rotating_logger]") -{ +TEST_CASE("rotating_file_logger1", "[rotating_logger]") { prepare_logdir(); size_t max_size = 1024 * 10; spdlog::filename_t basename = SPDLOG_FILENAME_T(ROTATING_LOG); auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 0); - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { logger->info("Test message {}", i); } @@ -60,8 +59,7 @@ TEST_CASE("rotating_file_logger1", "[rotating_logger]") require_message_count(ROTATING_LOG, 10); } -TEST_CASE("rotating_file_logger2", "[rotating_logger]") -{ +TEST_CASE("rotating_file_logger2", "[rotating_logger]") { prepare_logdir(); size_t max_size = 1024 * 10; spdlog::filename_t basename = SPDLOG_FILENAME_T(ROTATING_LOG); @@ -69,8 +67,7 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]") { // make an initial logger to create the first output file auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 2, true); - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { logger->info("Test message {}", i); } // drop causes the logger destructor to be called, which is required so the @@ -79,8 +76,7 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]") } auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 2, true); - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { logger->info("Test message {}", i); } @@ -88,8 +84,7 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]") require_message_count(ROTATING_LOG, 10); - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { logger->info("Test message {}", i); } @@ -100,10 +95,10 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]") } // test that passing max_size=0 throws -TEST_CASE("rotating_file_logger3", "[rotating_logger]") -{ +TEST_CASE("rotating_file_logger3", "[rotating_logger]") { prepare_logdir(); size_t max_size = 0; spdlog::filename_t basename = SPDLOG_FILENAME_T(ROTATING_LOG); - REQUIRE_THROWS_AS(spdlog::rotating_logger_mt("logger", basename, max_size, 0), spdlog::spdlog_ex); + REQUIRE_THROWS_AS(spdlog::rotating_logger_mt("logger", basename, max_size, 0), + spdlog::spdlog_ex); } diff --git a/tests/test_fmt_helper.cpp b/tests/test_fmt_helper.cpp index 52141902..31b93067 100644 --- a/tests/test_fmt_helper.cpp +++ b/tests/test_fmt_helper.cpp @@ -4,40 +4,35 @@ using spdlog::memory_buf_t; using spdlog::details::to_string_view; -void test_pad2(int n, const char *expected) -{ +void test_pad2(int n, const char *expected) { memory_buf_t buf; spdlog::details::fmt_helper::pad2(n, buf); REQUIRE(to_string_view(buf) == expected); } -void test_pad3(uint32_t n, const char *expected) -{ +void test_pad3(uint32_t n, const char *expected) { memory_buf_t buf; spdlog::details::fmt_helper::pad3(n, buf); REQUIRE(to_string_view(buf) == expected); } -void test_pad6(std::size_t n, const char *expected) -{ +void test_pad6(std::size_t n, const char *expected) { memory_buf_t buf; spdlog::details::fmt_helper::pad6(n, buf); REQUIRE(to_string_view(buf) == expected); } -void test_pad9(std::size_t n, const char *expected) -{ +void test_pad9(std::size_t n, const char *expected) { memory_buf_t buf; spdlog::details::fmt_helper::pad9(n, buf); REQUIRE(to_string_view(buf) == expected); } -TEST_CASE("pad2", "[fmt_helper]") -{ +TEST_CASE("pad2", "[fmt_helper]") { test_pad2(0, "00"); test_pad2(3, "03"); test_pad2(10, "10"); @@ -49,8 +44,7 @@ TEST_CASE("pad2", "[fmt_helper]") test_pad2(-5, "-5"); } -TEST_CASE("pad3", "[fmt_helper]") -{ +TEST_CASE("pad3", "[fmt_helper]") { test_pad3(0, "000"); test_pad3(3, "003"); test_pad3(10, "010"); @@ -63,8 +57,7 @@ TEST_CASE("pad3", "[fmt_helper]") test_pad3(1234, "1234"); } -TEST_CASE("pad6", "[fmt_helper]") -{ +TEST_CASE("pad6", "[fmt_helper]") { test_pad6(0, "000000"); test_pad6(3, "000003"); test_pad6(23, "000023"); @@ -74,8 +67,7 @@ TEST_CASE("pad6", "[fmt_helper]") test_pad6(123456, "123456"); } -TEST_CASE("pad9", "[fmt_helper]") -{ +TEST_CASE("pad9", "[fmt_helper]") { test_pad9(0, "000000000"); test_pad9(3, "000000003"); test_pad9(23, "000000023"); diff --git a/tests/test_macros.cpp b/tests/test_macros.cpp index 36537958..37a2a916 100644 --- a/tests/test_macros.cpp +++ b/tests/test_macros.cpp @@ -1,17 +1,17 @@ /* - * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + * This content is released under the MIT License as specified in + * https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE */ #include "includes.h" #if SPDLOG_ACTIVE_LEVEL != SPDLOG_LEVEL_DEBUG -# error "Invalid SPDLOG_ACTIVE_LEVEL in test. Should be SPDLOG_LEVEL_DEBUG" + #error "Invalid SPDLOG_ACTIVE_LEVEL in test. Should be SPDLOG_LEVEL_DEBUG" #endif #define TEST_FILENAME "test_logs/simple_log" -TEST_CASE("debug and trace w/o format string", "[macros]") -{ +TEST_CASE("debug and trace w/o format string", "[macros]") { prepare_logdir(); spdlog::filename_t filename = SPDLOG_FILENAME_T(TEST_FILENAME); @@ -25,7 +25,8 @@ TEST_CASE("debug and trace w/o format string", "[macros]") logger->flush(); using spdlog::details::os::default_eol; - REQUIRE(ends_with(file_contents(TEST_FILENAME), spdlog::fmt_lib::format("Test message 2{}", default_eol))); + REQUIRE(ends_with(file_contents(TEST_FILENAME), + spdlog::fmt_lib::format("Test message 2{}", default_eol))); REQUIRE(count_lines(TEST_FILENAME) == 1); auto orig_default_logger = spdlog::default_logger(); @@ -36,17 +37,16 @@ TEST_CASE("debug and trace w/o format string", "[macros]") logger->flush(); require_message_count(TEST_FILENAME, 2); - REQUIRE(ends_with(file_contents(TEST_FILENAME), spdlog::fmt_lib::format("Test message 4{}", default_eol))); + REQUIRE(ends_with(file_contents(TEST_FILENAME), + spdlog::fmt_lib::format("Test message 4{}", default_eol))); spdlog::set_default_logger(std::move(orig_default_logger)); } -TEST_CASE("disable param evaluation", "[macros]") -{ +TEST_CASE("disable param evaluation", "[macros]") { SPDLOG_TRACE("Test message {}", throw std::runtime_error("Should not be evaluated")); } -TEST_CASE("pass logger pointer", "[macros]") -{ +TEST_CASE("pass logger pointer", "[macros]") { auto logger = spdlog::create("refmacro"); auto &ref = *logger; SPDLOG_LOGGER_TRACE(&ref, "Test message 1"); diff --git a/tests/test_misc.cpp b/tests/test_misc.cpp index 6199641f..9f359e7f 100644 --- a/tests/test_misc.cpp +++ b/tests/test_misc.cpp @@ -1,9 +1,8 @@ #include "includes.h" #include "test_sink.h" -template -std::string log_info(const T &what, spdlog::level::level_enum logger_level = spdlog::level::info) -{ +template +std::string log_info(const T &what, spdlog::level::level_enum logger_level = spdlog::level::info) { std::ostringstream oss; auto oss_sink = std::make_shared(oss); @@ -16,8 +15,7 @@ std::string log_info(const T &what, spdlog::level::level_enum logger_level = spd return oss.str().substr(0, oss.str().length() - strlen(spdlog::details::os::default_eol)); } -TEST_CASE("basic_logging ", "[basic_logging]") -{ +TEST_CASE("basic_logging ", "[basic_logging]") { // const char REQUIRE(log_info("Hello") == "Hello"); REQUIRE(log_info("").empty()); @@ -34,8 +32,7 @@ TEST_CASE("basic_logging ", "[basic_logging]") // REQUIRE(log_info(some_logged_class("some_val")) == "some_val"); } -TEST_CASE("log_levels", "[log_levels]") -{ +TEST_CASE("log_levels", "[log_levels]") { REQUIRE(log_info("Hello", spdlog::level::err).empty()); REQUIRE(log_info("Hello", spdlog::level::critical).empty()); REQUIRE(log_info("Hello", spdlog::level::info) == "Hello"); @@ -43,8 +40,7 @@ TEST_CASE("log_levels", "[log_levels]") REQUIRE(log_info("Hello", spdlog::level::trace) == "Hello"); } -TEST_CASE("level_to_string_view", "[convert_to_string_view]") -{ +TEST_CASE("level_to_string_view", "[convert_to_string_view]") { REQUIRE(spdlog::level::to_string_view(spdlog::level::trace) == "trace"); REQUIRE(spdlog::level::to_string_view(spdlog::level::debug) == "debug"); REQUIRE(spdlog::level::to_string_view(spdlog::level::info) == "info"); @@ -54,8 +50,7 @@ TEST_CASE("level_to_string_view", "[convert_to_string_view]") REQUIRE(spdlog::level::to_string_view(spdlog::level::off) == "off"); } -TEST_CASE("to_short_c_str", "[convert_to_short_c_str]") -{ +TEST_CASE("to_short_c_str", "[convert_to_short_c_str]") { REQUIRE(std::string(spdlog::level::to_short_c_str(spdlog::level::trace)) == "T"); REQUIRE(std::string(spdlog::level::to_short_c_str(spdlog::level::debug)) == "D"); REQUIRE(std::string(spdlog::level::to_short_c_str(spdlog::level::info)) == "I"); @@ -65,8 +60,7 @@ TEST_CASE("to_short_c_str", "[convert_to_short_c_str]") REQUIRE(std::string(spdlog::level::to_short_c_str(spdlog::level::off)) == "O"); } -TEST_CASE("to_level_enum", "[convert_to_level_enum]") -{ +TEST_CASE("to_level_enum", "[convert_to_level_enum]") { REQUIRE(spdlog::level::from_str("trace") == spdlog::level::trace); REQUIRE(spdlog::level::from_str("debug") == spdlog::level::debug); REQUIRE(spdlog::level::from_str("info") == spdlog::level::info); @@ -78,8 +72,7 @@ TEST_CASE("to_level_enum", "[convert_to_level_enum]") REQUIRE(spdlog::level::from_str("null") == spdlog::level::off); } -TEST_CASE("periodic flush", "[periodic_flush]") -{ +TEST_CASE("periodic flush", "[periodic_flush]") { using spdlog::sinks::test_sink_mt; auto logger = spdlog::create("periodic_flush"); auto test_sink = std::static_pointer_cast(logger->sinks()[0]); @@ -91,8 +84,7 @@ TEST_CASE("periodic flush", "[periodic_flush]") spdlog::drop_all(); } -TEST_CASE("clone-logger", "[clone]") -{ +TEST_CASE("clone-logger", "[clone]") { using spdlog::sinks::test_sink_mt; auto test_sink = std::make_shared(); auto logger = std::make_shared("orig", test_sink); @@ -113,8 +105,7 @@ TEST_CASE("clone-logger", "[clone]") spdlog::drop_all(); } -TEST_CASE("clone async", "[clone]") -{ +TEST_CASE("clone async", "[clone]") { using spdlog::sinks::test_sink_st; spdlog::init_thread_pool(4, 1); auto test_sink = std::make_shared(); @@ -139,8 +130,7 @@ TEST_CASE("clone async", "[clone]") spdlog::drop_all(); } -TEST_CASE("default logger API", "[default logger]") -{ +TEST_CASE("default logger API", "[default logger]") { std::ostringstream oss; auto oss_sink = std::make_shared(oss); diff --git a/tests/test_mpmc_q.cpp b/tests/test_mpmc_q.cpp index 1540dcc8..41b99a21 100644 --- a/tests/test_mpmc_q.cpp +++ b/tests/test_mpmc_q.cpp @@ -3,12 +3,10 @@ using std::chrono::milliseconds; using test_clock = std::chrono::high_resolution_clock; -static milliseconds millis_from(const test_clock::time_point &tp0) -{ +static milliseconds millis_from(const test_clock::time_point &tp0) { return std::chrono::duration_cast(test_clock::now() - tp0); } -TEST_CASE("dequeue-empty-nowait", "[mpmc_blocking_q]") -{ +TEST_CASE("dequeue-empty-nowait", "[mpmc_blocking_q]") { size_t q_size = 100; milliseconds tolerance_wait(20); spdlog::details::mpmc_blocking_queue q(q_size); @@ -23,8 +21,7 @@ TEST_CASE("dequeue-empty-nowait", "[mpmc_blocking_q]") REQUIRE(delta_ms <= tolerance_wait); } -TEST_CASE("dequeue-empty-wait", "[mpmc_blocking_q]") -{ +TEST_CASE("dequeue-empty-wait", "[mpmc_blocking_q]") { size_t q_size = 100; milliseconds wait_ms(250); @@ -43,8 +40,7 @@ TEST_CASE("dequeue-empty-wait", "[mpmc_blocking_q]") REQUIRE(delta_ms <= wait_ms + tolerance_wait); } -TEST_CASE("dequeue-full-nowait", "[mpmc_blocking_q]") -{ +TEST_CASE("dequeue-full-nowait", "[mpmc_blocking_q]") { spdlog::details::mpmc_blocking_queue q(1); q.enqueue(42); @@ -53,8 +49,7 @@ TEST_CASE("dequeue-full-nowait", "[mpmc_blocking_q]") REQUIRE(item == 42); } -TEST_CASE("dequeue-full-wait", "[mpmc_blocking_q]") -{ +TEST_CASE("dequeue-full-wait", "[mpmc_blocking_q]") { spdlog::details::mpmc_blocking_queue q(1); q.enqueue(42); @@ -63,8 +58,7 @@ TEST_CASE("dequeue-full-wait", "[mpmc_blocking_q]") REQUIRE(item == 42); } -TEST_CASE("enqueue_nowait", "[mpmc_blocking_q]") -{ +TEST_CASE("enqueue_nowait", "[mpmc_blocking_q]") { size_t q_size = 1; spdlog::details::mpmc_blocking_queue q(q_size); @@ -82,8 +76,7 @@ TEST_CASE("enqueue_nowait", "[mpmc_blocking_q]") REQUIRE(q.overrun_counter() == 1); } -TEST_CASE("bad_queue", "[mpmc_blocking_q]") -{ +TEST_CASE("bad_queue", "[mpmc_blocking_q]") { size_t q_size = 0; spdlog::details::mpmc_blocking_queue q(q_size); q.enqueue_nowait(1); @@ -92,28 +85,25 @@ TEST_CASE("bad_queue", "[mpmc_blocking_q]") REQUIRE(q.dequeue_for(i, milliseconds(0)) == false); } -TEST_CASE("empty_queue", "[mpmc_blocking_q]") -{ +TEST_CASE("empty_queue", "[mpmc_blocking_q]") { size_t q_size = 10; spdlog::details::mpmc_blocking_queue q(q_size); int i = 0; REQUIRE(q.dequeue_for(i, milliseconds(10)) == false); } -TEST_CASE("full_queue", "[mpmc_blocking_q]") -{ +TEST_CASE("full_queue", "[mpmc_blocking_q]") { size_t q_size = 100; spdlog::details::mpmc_blocking_queue q(q_size); - for (int i = 0; i < static_cast(q_size); i++) - { - q.enqueue(i + 0); // i+0 to force rvalue and avoid tidy warnings on the same time if we std::move(i) instead + for (int i = 0; i < static_cast(q_size); i++) { + q.enqueue(i + 0); // i+0 to force rvalue and avoid tidy warnings on the same time if we + // std::move(i) instead } q.enqueue_nowait(123456); REQUIRE(q.overrun_counter() == 1); - for (int i = 1; i < static_cast(q_size); i++) - { + for (int i = 1; i < static_cast(q_size); i++) { int item = -1; q.dequeue(item); REQUIRE(item == i); diff --git a/tests/test_pattern_formatter.cpp b/tests/test_pattern_formatter.cpp index bafea884..350b973b 100644 --- a/tests/test_pattern_formatter.cpp +++ b/tests/test_pattern_formatter.cpp @@ -5,79 +5,78 @@ using spdlog::memory_buf_t; using spdlog::details::to_string_view; // log to str and return it -template -static std::string log_to_str(const std::string &msg, const Args &...args) -{ +template +static std::string log_to_str(const std::string &msg, const Args &...args) { std::ostringstream oss; auto oss_sink = std::make_shared(oss); spdlog::logger oss_logger("pattern_tester", oss_sink); oss_logger.set_level(spdlog::level::info); - oss_logger.set_formatter(std::unique_ptr(new spdlog::pattern_formatter(args...))); + oss_logger.set_formatter( + std::unique_ptr(new spdlog::pattern_formatter(args...))); oss_logger.info(msg); return oss.str(); } -TEST_CASE("custom eol", "[pattern_formatter]") -{ +TEST_CASE("custom eol", "[pattern_formatter]") { std::string msg = "Hello custom eol test"; std::string eol = ";)"; REQUIRE(log_to_str(msg, "%v", spdlog::pattern_time_type::local, ";)") == msg + eol); } -TEST_CASE("empty format", "[pattern_formatter]") -{ +TEST_CASE("empty format", "[pattern_formatter]") { REQUIRE(log_to_str("Some message", "", spdlog::pattern_time_type::local, "").empty()); } -TEST_CASE("empty format2", "[pattern_formatter]") -{ +TEST_CASE("empty format2", "[pattern_formatter]") { REQUIRE(log_to_str("Some message", "", spdlog::pattern_time_type::local, "\n") == "\n"); } -TEST_CASE("level", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%l] %v", spdlog::pattern_time_type::local, "\n") == "[info] Some message\n"); +TEST_CASE("level", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%l] %v", spdlog::pattern_time_type::local, "\n") == + "[info] Some message\n"); } -TEST_CASE("short level", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%L] %v", spdlog::pattern_time_type::local, "\n") == "[I] Some message\n"); +TEST_CASE("short level", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%L] %v", spdlog::pattern_time_type::local, "\n") == + "[I] Some message\n"); } -TEST_CASE("name", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%n] %v", spdlog::pattern_time_type::local, "\n") == "[pattern_tester] Some message\n"); +TEST_CASE("name", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%n] %v", spdlog::pattern_time_type::local, "\n") == + "[pattern_tester] Some message\n"); } -TEST_CASE("date MM/DD/YY ", "[pattern_formatter]") -{ +TEST_CASE("date MM/DD/YY ", "[pattern_formatter]") { auto now_tm = spdlog::details::os::localtime(); std::stringstream oss; - oss << std::setfill('0') << std::setw(2) << now_tm.tm_mon + 1 << "/" << std::setw(2) << now_tm.tm_mday << "/" << std::setw(2) - << (now_tm.tm_year + 1900) % 1000 << " Some message\n"; - REQUIRE(log_to_str("Some message", "%D %v", spdlog::pattern_time_type::local, "\n") == oss.str()); + oss << std::setfill('0') << std::setw(2) << now_tm.tm_mon + 1 << "/" << std::setw(2) + << now_tm.tm_mday << "/" << std::setw(2) << (now_tm.tm_year + 1900) % 1000 + << " Some message\n"; + REQUIRE(log_to_str("Some message", "%D %v", spdlog::pattern_time_type::local, "\n") == + oss.str()); } -TEST_CASE("color range test1", "[pattern_formatter]") -{ - auto formatter = std::make_shared("%^%v%$", spdlog::pattern_time_type::local, "\n"); +TEST_CASE("color range test1", "[pattern_formatter]") { + auto formatter = std::make_shared( + "%^%v%$", spdlog::pattern_time_type::local, "\n"); memory_buf_t buf; spdlog::fmt_lib::format_to(std::back_inserter(buf), "Hello"); memory_buf_t formatted; std::string logger_name = "test"; - spdlog::details::log_msg msg(logger_name, spdlog::level::info, spdlog::string_view_t(buf.data(), buf.size())); + spdlog::details::log_msg msg(logger_name, spdlog::level::info, + spdlog::string_view_t(buf.data(), buf.size())); formatter->format(msg, formatted); REQUIRE(msg.color_range_start == 0); REQUIRE(msg.color_range_end == 5); REQUIRE(log_to_str("hello", "%^%v%$", spdlog::pattern_time_type::local, "\n") == "hello\n"); } -TEST_CASE("color range test2", "[pattern_formatter]") -{ - auto formatter = std::make_shared("%^%$", spdlog::pattern_time_type::local, "\n"); +TEST_CASE("color range test2", "[pattern_formatter]") { + auto formatter = + std::make_shared("%^%$", spdlog::pattern_time_type::local, "\n"); std::string logger_name = "test"; spdlog::details::log_msg msg(logger_name, spdlog::level::info, ""); memory_buf_t formatted; @@ -87,8 +86,7 @@ TEST_CASE("color range test2", "[pattern_formatter]") REQUIRE(log_to_str("", "%^%$", spdlog::pattern_time_type::local, "\n") == "\n"); } -TEST_CASE("color range test3", "[pattern_formatter]") -{ +TEST_CASE("color range test3", "[pattern_formatter]") { auto formatter = std::make_shared("%^***%$"); std::string logger_name = "test"; spdlog::details::log_msg msg(logger_name, spdlog::level::info, "ignored"); @@ -98,9 +96,9 @@ TEST_CASE("color range test3", "[pattern_formatter]") REQUIRE(msg.color_range_end == 3); } -TEST_CASE("color range test4", "[pattern_formatter]") -{ - auto formatter = std::make_shared("XX%^YYY%$", spdlog::pattern_time_type::local, "\n"); +TEST_CASE("color range test4", "[pattern_formatter]") { + auto formatter = std::make_shared( + "XX%^YYY%$", spdlog::pattern_time_type::local, "\n"); std::string logger_name = "test"; spdlog::details::log_msg msg(logger_name, spdlog::level::info, "ignored"); @@ -108,11 +106,11 @@ TEST_CASE("color range test4", "[pattern_formatter]") formatter->format(msg, formatted); REQUIRE(msg.color_range_start == 2); REQUIRE(msg.color_range_end == 5); - REQUIRE(log_to_str("ignored", "XX%^YYY%$", spdlog::pattern_time_type::local, "\n") == "XXYYY\n"); + REQUIRE(log_to_str("ignored", "XX%^YYY%$", spdlog::pattern_time_type::local, "\n") == + "XXYYY\n"); } -TEST_CASE("color range test5", "[pattern_formatter]") -{ +TEST_CASE("color range test5", "[pattern_formatter]") { auto formatter = std::make_shared("**%^"); std::string logger_name = "test"; spdlog::details::log_msg msg(logger_name, spdlog::level::info, "ignored"); @@ -122,8 +120,7 @@ TEST_CASE("color range test5", "[pattern_formatter]") REQUIRE(msg.color_range_end == 0); } -TEST_CASE("color range test6", "[pattern_formatter]") -{ +TEST_CASE("color range test6", "[pattern_formatter]") { auto formatter = std::make_shared("**%$"); std::string logger_name = "test"; spdlog::details::log_msg msg(logger_name, spdlog::level::info, "ignored"); @@ -137,62 +134,70 @@ TEST_CASE("color range test6", "[pattern_formatter]") // Test padding // -TEST_CASE("level_left_padded", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%8l] %v", spdlog::pattern_time_type::local, "\n") == "[ info] Some message\n"); - REQUIRE(log_to_str("Some message", "[%8!l] %v", spdlog::pattern_time_type::local, "\n") == "[ info] Some message\n"); +TEST_CASE("level_left_padded", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%8l] %v", spdlog::pattern_time_type::local, "\n") == + "[ info] Some message\n"); + REQUIRE(log_to_str("Some message", "[%8!l] %v", spdlog::pattern_time_type::local, "\n") == + "[ info] Some message\n"); } -TEST_CASE("level_right_padded", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%-8l] %v", spdlog::pattern_time_type::local, "\n") == "[info ] Some message\n"); - REQUIRE(log_to_str("Some message", "[%-8!l] %v", spdlog::pattern_time_type::local, "\n") == "[info ] Some message\n"); +TEST_CASE("level_right_padded", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%-8l] %v", spdlog::pattern_time_type::local, "\n") == + "[info ] Some message\n"); + REQUIRE(log_to_str("Some message", "[%-8!l] %v", spdlog::pattern_time_type::local, "\n") == + "[info ] Some message\n"); } -TEST_CASE("level_center_padded", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%=8l] %v", spdlog::pattern_time_type::local, "\n") == "[ info ] Some message\n"); - REQUIRE(log_to_str("Some message", "[%=8!l] %v", spdlog::pattern_time_type::local, "\n") == "[ info ] Some message\n"); +TEST_CASE("level_center_padded", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%=8l] %v", spdlog::pattern_time_type::local, "\n") == + "[ info ] Some message\n"); + REQUIRE(log_to_str("Some message", "[%=8!l] %v", spdlog::pattern_time_type::local, "\n") == + "[ info ] Some message\n"); } -TEST_CASE("short level_left_padded", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%3L] %v", spdlog::pattern_time_type::local, "\n") == "[ I] Some message\n"); - REQUIRE(log_to_str("Some message", "[%3!L] %v", spdlog::pattern_time_type::local, "\n") == "[ I] Some message\n"); +TEST_CASE("short level_left_padded", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%3L] %v", spdlog::pattern_time_type::local, "\n") == + "[ I] Some message\n"); + REQUIRE(log_to_str("Some message", "[%3!L] %v", spdlog::pattern_time_type::local, "\n") == + "[ I] Some message\n"); } -TEST_CASE("short level_right_padded", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%-3L] %v", spdlog::pattern_time_type::local, "\n") == "[I ] Some message\n"); - REQUIRE(log_to_str("Some message", "[%-3!L] %v", spdlog::pattern_time_type::local, "\n") == "[I ] Some message\n"); +TEST_CASE("short level_right_padded", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%-3L] %v", spdlog::pattern_time_type::local, "\n") == + "[I ] Some message\n"); + REQUIRE(log_to_str("Some message", "[%-3!L] %v", spdlog::pattern_time_type::local, "\n") == + "[I ] Some message\n"); } -TEST_CASE("short level_center_padded", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%=3L] %v", spdlog::pattern_time_type::local, "\n") == "[ I ] Some message\n"); - REQUIRE(log_to_str("Some message", "[%=3!L] %v", spdlog::pattern_time_type::local, "\n") == "[ I ] Some message\n"); +TEST_CASE("short level_center_padded", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%=3L] %v", spdlog::pattern_time_type::local, "\n") == + "[ I ] Some message\n"); + REQUIRE(log_to_str("Some message", "[%=3!L] %v", spdlog::pattern_time_type::local, "\n") == + "[ I ] Some message\n"); } -TEST_CASE("left_padded_short", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%3n] %v", spdlog::pattern_time_type::local, "\n") == "[pattern_tester] Some message\n"); - REQUIRE(log_to_str("Some message", "[%3!n] %v", spdlog::pattern_time_type::local, "\n") == "[pat] Some message\n"); +TEST_CASE("left_padded_short", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%3n] %v", spdlog::pattern_time_type::local, "\n") == + "[pattern_tester] Some message\n"); + REQUIRE(log_to_str("Some message", "[%3!n] %v", spdlog::pattern_time_type::local, "\n") == + "[pat] Some message\n"); } -TEST_CASE("right_padded_short", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%-3n] %v", spdlog::pattern_time_type::local, "\n") == "[pattern_tester] Some message\n"); - REQUIRE(log_to_str("Some message", "[%-3!n] %v", spdlog::pattern_time_type::local, "\n") == "[pat] Some message\n"); +TEST_CASE("right_padded_short", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%-3n] %v", spdlog::pattern_time_type::local, "\n") == + "[pattern_tester] Some message\n"); + REQUIRE(log_to_str("Some message", "[%-3!n] %v", spdlog::pattern_time_type::local, "\n") == + "[pat] Some message\n"); } -TEST_CASE("center_padded_short", "[pattern_formatter]") -{ - REQUIRE(log_to_str("Some message", "[%=3n] %v", spdlog::pattern_time_type::local, "\n") == "[pattern_tester] Some message\n"); - REQUIRE(log_to_str("Some message", "[%=3!n] %v", spdlog::pattern_time_type::local, "\n") == "[pat] Some message\n"); +TEST_CASE("center_padded_short", "[pattern_formatter]") { + REQUIRE(log_to_str("Some message", "[%=3n] %v", spdlog::pattern_time_type::local, "\n") == + "[pattern_tester] Some message\n"); + REQUIRE(log_to_str("Some message", "[%=3!n] %v", spdlog::pattern_time_type::local, "\n") == + "[pat] Some message\n"); } -TEST_CASE("left_padded_huge", "[pattern_formatter]") -{ +TEST_CASE("left_padded_huge", "[pattern_formatter]") { REQUIRE(log_to_str("Some message", "[%-300n] %v", spdlog::pattern_time_type::local, "\n") == "[pattern_tester ] Some message\n"); @@ -200,8 +205,7 @@ TEST_CASE("left_padded_huge", "[pattern_formatter]") "[pattern_tester ] Some message\n"); } -TEST_CASE("left_padded_max", "[pattern_formatter]") -{ +TEST_CASE("left_padded_max", "[pattern_formatter]") { REQUIRE(log_to_str("Some message", "[%-64n] %v", spdlog::pattern_time_type::local, "\n") == "[pattern_tester ] Some message\n"); @@ -211,8 +215,7 @@ TEST_CASE("left_padded_max", "[pattern_formatter]") // Test padding + truncate flag -TEST_CASE("paddinng_truncate", "[pattern_formatter]") -{ +TEST_CASE("paddinng_truncate", "[pattern_formatter]") { REQUIRE(log_to_str("123456", "%6!v", spdlog::pattern_time_type::local, "\n") == "123456\n"); REQUIRE(log_to_str("123456", "%5!v", spdlog::pattern_time_type::local, "\n") == "12345\n"); REQUIRE(log_to_str("123456", "%7!v", spdlog::pattern_time_type::local, "\n") == " 123456\n"); @@ -228,42 +231,43 @@ TEST_CASE("paddinng_truncate", "[pattern_formatter]") REQUIRE(log_to_str("123456", "%0!v", spdlog::pattern_time_type::local, "\n") == "\n"); } -TEST_CASE("padding_truncate_funcname", "[pattern_formatter]") -{ +TEST_CASE("padding_truncate_funcname", "[pattern_formatter]") { spdlog::sinks::test_sink_st test_sink; const char *pattern = "%v [%5!!]"; auto formatter = std::unique_ptr(new spdlog::pattern_formatter(pattern)); test_sink.set_formatter(std::move(formatter)); - spdlog::details::log_msg msg1{spdlog::source_loc{"ignored", 1, "func"}, "test_logger", spdlog::level::info, "message"}; + spdlog::details::log_msg msg1{spdlog::source_loc{"ignored", 1, "func"}, "test_logger", + spdlog::level::info, "message"}; test_sink.log(msg1); REQUIRE(test_sink.lines()[0] == "message [ func]"); - spdlog::details::log_msg msg2{spdlog::source_loc{"ignored", 1, "function"}, "test_logger", spdlog::level::info, "message"}; + spdlog::details::log_msg msg2{spdlog::source_loc{"ignored", 1, "function"}, "test_logger", + spdlog::level::info, "message"}; test_sink.log(msg2); REQUIRE(test_sink.lines()[1] == "message [funct]"); } -TEST_CASE("padding_funcname", "[pattern_formatter]") -{ +TEST_CASE("padding_funcname", "[pattern_formatter]") { spdlog::sinks::test_sink_st test_sink; const char *pattern = "%v [%10!]"; auto formatter = std::unique_ptr(new spdlog::pattern_formatter(pattern)); test_sink.set_formatter(std::move(formatter)); - spdlog::details::log_msg msg1{spdlog::source_loc{"ignored", 1, "func"}, "test_logger", spdlog::level::info, "message"}; + spdlog::details::log_msg msg1{spdlog::source_loc{"ignored", 1, "func"}, "test_logger", + spdlog::level::info, "message"}; test_sink.log(msg1); REQUIRE(test_sink.lines()[0] == "message [ func]"); - spdlog::details::log_msg msg2{spdlog::source_loc{"ignored", 1, "func567890123"}, "test_logger", spdlog::level::info, "message"}; + spdlog::details::log_msg msg2{spdlog::source_loc{"ignored", 1, "func567890123"}, "test_logger", + spdlog::level::info, "message"}; test_sink.log(msg2); REQUIRE(test_sink.lines()[1] == "message [func567890123]"); } -TEST_CASE("clone-default-formatter", "[pattern_formatter]") -{ +TEST_CASE("clone-default-formatter", "[pattern_formatter]") { auto formatter_1 = std::make_shared(); auto formatter_2 = formatter_1->clone(); std::string logger_name = "test"; @@ -277,8 +281,7 @@ TEST_CASE("clone-default-formatter", "[pattern_formatter]") REQUIRE(to_string_view(formatted_1) == to_string_view(formatted_2)); } -TEST_CASE("clone-default-formatter2", "[pattern_formatter]") -{ +TEST_CASE("clone-default-formatter2", "[pattern_formatter]") { auto formatter_1 = std::make_shared("%+"); auto formatter_2 = formatter_1->clone(); std::string logger_name = "test"; @@ -292,8 +295,7 @@ TEST_CASE("clone-default-formatter2", "[pattern_formatter]") REQUIRE(to_string_view(formatted_1) == to_string_view(formatted_2)); } -TEST_CASE("clone-formatter", "[pattern_formatter]") -{ +TEST_CASE("clone-formatter", "[pattern_formatter]") { auto formatter_1 = std::make_shared("%D %X [%] [%n] %v"); auto formatter_2 = formatter_1->clone(); std::string logger_name = "test"; @@ -307,10 +309,10 @@ TEST_CASE("clone-formatter", "[pattern_formatter]") REQUIRE(to_string_view(formatted_1) == to_string_view(formatted_2)); } -TEST_CASE("clone-formatter-2", "[pattern_formatter]") -{ +TEST_CASE("clone-formatter-2", "[pattern_formatter]") { using spdlog::pattern_time_type; - auto formatter_1 = std::make_shared("%D %X [%] [%n] %v", pattern_time_type::utc, "xxxxxx\n"); + auto formatter_1 = std::make_shared( + "%D %X [%] [%n] %v", pattern_time_type::utc, "xxxxxx\n"); auto formatter_2 = formatter_1->clone(); std::string logger_name = "test2"; spdlog::details::log_msg msg(logger_name, spdlog::level::info, "some message"); @@ -323,43 +325,35 @@ TEST_CASE("clone-formatter-2", "[pattern_formatter]") REQUIRE(to_string_view(formatted_1) == to_string_view(formatted_2)); } -class custom_test_flag : public spdlog::custom_flag_formatter -{ +class custom_test_flag : public spdlog::custom_flag_formatter { public: explicit custom_test_flag(std::string txt) - : some_txt{std::move(txt)} - {} + : some_txt{std::move(txt)} {} - void format(const spdlog::details::log_msg &, const std::tm &tm, spdlog::memory_buf_t &dest) override - { - if (some_txt == "throw_me") - { + void format(const spdlog::details::log_msg &, + const std::tm &tm, + spdlog::memory_buf_t &dest) override { + if (some_txt == "throw_me") { throw spdlog::spdlog_ex("custom_flag_exception_test"); - } - else if (some_txt == "time") - { - auto formatted = spdlog::fmt_lib::format("{:d}:{:02d}{:s}", tm.tm_hour % 12, tm.tm_min, tm.tm_hour / 12 ? "PM" : "AM"); + } else if (some_txt == "time") { + auto formatted = spdlog::fmt_lib::format("{:d}:{:02d}{:s}", tm.tm_hour % 12, tm.tm_min, + tm.tm_hour / 12 ? "PM" : "AM"); dest.append(formatted.data(), formatted.data() + formatted.size()); return; } some_txt = std::string(padinfo_.width_, ' ') + some_txt; dest.append(some_txt.data(), some_txt.data() + some_txt.size()); } - spdlog::details::padding_info get_padding_info() - { - return padinfo_; - } + spdlog::details::padding_info get_padding_info() { return padinfo_; } std::string some_txt; - std::unique_ptr clone() const override - { + std::unique_ptr clone() const override { return spdlog::details::make_unique(some_txt); } }; // test clone with custom flag formatters -TEST_CASE("clone-custom_formatter", "[pattern_formatter]") -{ +TEST_CASE("clone-custom_formatter", "[pattern_formatter]") { auto formatter_1 = std::make_shared(); formatter_1->add_flag('t', "custom_output").set_pattern("[%n] [%t] %v"); auto formatter_2 = formatter_1->clone(); @@ -371,7 +365,8 @@ TEST_CASE("clone-custom_formatter", "[pattern_formatter]") formatter_1->format(msg, formatted_1); formatter_2->format(msg, formatted_2); - auto expected = spdlog::fmt_lib::format("[logger-name] [custom_output] some message{}", spdlog::details::os::default_eol); + auto expected = spdlog::fmt_lib::format("[logger-name] [custom_output] some message{}", + spdlog::details::os::default_eol); REQUIRE(to_string_view(formatted_1) == expected); REQUIRE(to_string_view(formatted_2) == expected); @@ -387,8 +382,7 @@ static const char *const test_path = "\\a\\b\\c/myfile.cpp"; static const char *const test_path = "/a/b//myfile.cpp"; #endif -TEST_CASE("short filename formatter-1", "[pattern_formatter]") -{ +TEST_CASE("short filename formatter-1", "[pattern_formatter]") { spdlog::pattern_formatter formatter("%s", spdlog::pattern_time_type::local, ""); memory_buf_t formatted; std::string logger_name = "logger-name"; @@ -399,8 +393,7 @@ TEST_CASE("short filename formatter-1", "[pattern_formatter]") REQUIRE(to_string_view(formatted) == "myfile.cpp"); } -TEST_CASE("short filename formatter-2", "[pattern_formatter]") -{ +TEST_CASE("short filename formatter-2", "[pattern_formatter]") { spdlog::pattern_formatter formatter("%s:%#", spdlog::pattern_time_type::local, ""); memory_buf_t formatted; std::string logger_name = "logger-name"; @@ -411,8 +404,7 @@ TEST_CASE("short filename formatter-2", "[pattern_formatter]") REQUIRE(to_string_view(formatted) == "myfile.cpp:123"); } -TEST_CASE("short filename formatter-3", "[pattern_formatter]") -{ +TEST_CASE("short filename formatter-3", "[pattern_formatter]") { spdlog::pattern_formatter formatter("%s %v", spdlog::pattern_time_type::local, ""); memory_buf_t formatted; std::string logger_name = "logger-name"; @@ -423,8 +415,7 @@ TEST_CASE("short filename formatter-3", "[pattern_formatter]") REQUIRE(to_string_view(formatted) == " Hello"); } -TEST_CASE("full filename formatter", "[pattern_formatter]") -{ +TEST_CASE("full filename formatter", "[pattern_formatter]") { spdlog::pattern_formatter formatter("%g", spdlog::pattern_time_type::local, ""); memory_buf_t formatted; std::string logger_name = "logger-name"; @@ -435,52 +426,61 @@ TEST_CASE("full filename formatter", "[pattern_formatter]") REQUIRE(to_string_view(formatted) == test_path); } -TEST_CASE("custom flags", "[pattern_formatter]") -{ +TEST_CASE("custom flags", "[pattern_formatter]") { auto formatter = std::make_shared(); - formatter->add_flag('t', "custom1").add_flag('u', "custom2").set_pattern("[%n] [%t] [%u] %v"); + formatter->add_flag('t', "custom1") + .add_flag('u', "custom2") + .set_pattern("[%n] [%t] [%u] %v"); memory_buf_t formatted; - spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, "some message"); + spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, + "some message"); formatter->format(msg, formatted); - auto expected = spdlog::fmt_lib::format("[logger-name] [custom1] [custom2] some message{}", spdlog::details::os::default_eol); + auto expected = spdlog::fmt_lib::format("[logger-name] [custom1] [custom2] some message{}", + spdlog::details::os::default_eol); REQUIRE(to_string_view(formatted) == expected); } -TEST_CASE("custom flags-padding", "[pattern_formatter]") -{ +TEST_CASE("custom flags-padding", "[pattern_formatter]") { auto formatter = std::make_shared(); - formatter->add_flag('t', "custom1").add_flag('u', "custom2").set_pattern("[%n] [%t] [%5u] %v"); + formatter->add_flag('t', "custom1") + .add_flag('u', "custom2") + .set_pattern("[%n] [%t] [%5u] %v"); memory_buf_t formatted; - spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, "some message"); + spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, + "some message"); formatter->format(msg, formatted); - auto expected = spdlog::fmt_lib::format("[logger-name] [custom1] [ custom2] some message{}", spdlog::details::os::default_eol); + auto expected = spdlog::fmt_lib::format("[logger-name] [custom1] [ custom2] some message{}", + spdlog::details::os::default_eol); REQUIRE(to_string_view(formatted) == expected); } -TEST_CASE("custom flags-exception", "[pattern_formatter]") -{ +TEST_CASE("custom flags-exception", "[pattern_formatter]") { auto formatter = std::make_shared(); - formatter->add_flag('t', "throw_me").add_flag('u', "custom2").set_pattern("[%n] [%t] [%u] %v"); + formatter->add_flag('t', "throw_me") + .add_flag('u', "custom2") + .set_pattern("[%n] [%t] [%u] %v"); memory_buf_t formatted; - spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, "some message"); + spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, + "some message"); CHECK_THROWS_AS(formatter->format(msg, formatted), spdlog::spdlog_ex); } -TEST_CASE("override need_localtime", "[pattern_formatter]") -{ - auto formatter = std::make_shared(spdlog::pattern_time_type::local, "\n"); +TEST_CASE("override need_localtime", "[pattern_formatter]") { + auto formatter = + std::make_shared(spdlog::pattern_time_type::local, "\n"); formatter->add_flag('t', "time").set_pattern("%t> %v"); { memory_buf_t formatted; - spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, "some message"); + spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, + "some message"); formatter->format(msg, formatted); REQUIRE(to_string_view(formatted) == "0:00AM> some message\n"); } @@ -490,11 +490,12 @@ TEST_CASE("override need_localtime", "[pattern_formatter]") auto now_tm = spdlog::details::os::localtime(); std::stringstream oss; - oss << (now_tm.tm_hour % 12) << ":" << std::setfill('0') << std::setw(2) << now_tm.tm_min << (now_tm.tm_hour / 12 ? "PM" : "AM") - << "> some message\n"; + oss << (now_tm.tm_hour % 12) << ":" << std::setfill('0') << std::setw(2) << now_tm.tm_min + << (now_tm.tm_hour / 12 ? "PM" : "AM") << "> some message\n"; memory_buf_t formatted; - spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, "some message"); + spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, + "some message"); formatter->format(msg, formatted); REQUIRE(to_string_view(formatted) == oss.str()); } diff --git a/tests/test_registry.cpp b/tests/test_registry.cpp index 8e632cc6..69ec8f53 100644 --- a/tests/test_registry.cpp +++ b/tests/test_registry.cpp @@ -4,32 +4,34 @@ static const char *const tested_logger_name = "null_logger"; static const char *const tested_logger_name2 = "null_logger2"; #ifndef SPDLOG_NO_EXCEPTIONS -TEST_CASE("register_drop", "[registry]") -{ +TEST_CASE("register_drop", "[registry]") { spdlog::drop_all(); spdlog::create(tested_logger_name); REQUIRE(spdlog::get(tested_logger_name) != nullptr); // Throw if registering existing name - REQUIRE_THROWS_AS(spdlog::create(tested_logger_name), spdlog::spdlog_ex); + REQUIRE_THROWS_AS(spdlog::create(tested_logger_name), + spdlog::spdlog_ex); } -TEST_CASE("explicit register", "[registry]") -{ +TEST_CASE("explicit register", "[registry]") { spdlog::drop_all(); - auto logger = std::make_shared(tested_logger_name, std::make_shared()); + auto logger = std::make_shared(tested_logger_name, + std::make_shared()); spdlog::register_logger(logger); REQUIRE(spdlog::get(tested_logger_name) != nullptr); // Throw if registering existing name - REQUIRE_THROWS_AS(spdlog::create(tested_logger_name), spdlog::spdlog_ex); + REQUIRE_THROWS_AS(spdlog::create(tested_logger_name), + spdlog::spdlog_ex); } #endif -TEST_CASE("apply_all", "[registry]") -{ +TEST_CASE("apply_all", "[registry]") { spdlog::drop_all(); - auto logger = std::make_shared(tested_logger_name, std::make_shared()); + auto logger = std::make_shared(tested_logger_name, + std::make_shared()); spdlog::register_logger(logger); - auto logger2 = std::make_shared(tested_logger_name2, std::make_shared()); + auto logger2 = std::make_shared( + tested_logger_name2, std::make_shared()); spdlog::register_logger(logger2); int counter = 0; @@ -45,24 +47,21 @@ TEST_CASE("apply_all", "[registry]") REQUIRE(counter == 1); } -TEST_CASE("drop", "[registry]") -{ +TEST_CASE("drop", "[registry]") { spdlog::drop_all(); spdlog::create(tested_logger_name); spdlog::drop(tested_logger_name); REQUIRE_FALSE(spdlog::get(tested_logger_name)); } -TEST_CASE("drop-default", "[registry]") -{ +TEST_CASE("drop-default", "[registry]") { spdlog::set_default_logger(spdlog::null_logger_st(tested_logger_name)); spdlog::drop(tested_logger_name); REQUIRE_FALSE(spdlog::default_logger()); REQUIRE_FALSE(spdlog::get(tested_logger_name)); } -TEST_CASE("drop_all", "[registry]") -{ +TEST_CASE("drop_all", "[registry]") { spdlog::drop_all(); spdlog::create(tested_logger_name); spdlog::create(tested_logger_name2); @@ -72,8 +71,7 @@ TEST_CASE("drop_all", "[registry]") REQUIRE_FALSE(spdlog::default_logger()); } -TEST_CASE("drop non existing", "[registry]") -{ +TEST_CASE("drop non existing", "[registry]") { spdlog::drop_all(); spdlog::create(tested_logger_name); spdlog::drop("some_name"); @@ -82,28 +80,26 @@ TEST_CASE("drop non existing", "[registry]") spdlog::drop_all(); } -TEST_CASE("default logger", "[registry]") -{ +TEST_CASE("default logger", "[registry]") { spdlog::drop_all(); spdlog::set_default_logger(spdlog::null_logger_st(tested_logger_name)); REQUIRE(spdlog::get(tested_logger_name) == spdlog::default_logger()); spdlog::drop_all(); } -TEST_CASE("set_default_logger(nullptr)", "[registry]") -{ +TEST_CASE("set_default_logger(nullptr)", "[registry]") { spdlog::set_default_logger(nullptr); REQUIRE_FALSE(spdlog::default_logger()); } -TEST_CASE("disable automatic registration", "[registry]") -{ +TEST_CASE("disable automatic registration", "[registry]") { // set some global parameters spdlog::level::level_enum log_level = spdlog::level::level_enum::warn; spdlog::set_level(log_level); // but disable automatic registration spdlog::set_automatic_registration(false); - auto logger1 = spdlog::create(tested_logger_name, SPDLOG_FILENAME_T("filename"), 11, 59); + auto logger1 = spdlog::create( + tested_logger_name, SPDLOG_FILENAME_T("filename"), 11, 59); auto logger2 = spdlog::create_async(tested_logger_name2); // loggers should not be part of the registry REQUIRE_FALSE(spdlog::get(tested_logger_name)); diff --git a/tests/test_sink.h b/tests/test_sink.h index 57db65c1..9f5a9394 100644 --- a/tests/test_sink.h +++ b/tests/test_sink.h @@ -15,56 +15,46 @@ namespace spdlog { namespace sinks { -template -class test_sink : public base_sink -{ +template +class test_sink : public base_sink { const size_t lines_to_save = 100; public: - size_t msg_counter() - { + size_t msg_counter() { std::lock_guard lock(base_sink::mutex_); return msg_counter_; } - size_t flush_counter() - { + size_t flush_counter() { std::lock_guard lock(base_sink::mutex_); return flush_counter_; } - void set_delay(std::chrono::milliseconds delay) - { + void set_delay(std::chrono::milliseconds delay) { std::lock_guard lock(base_sink::mutex_); delay_ = delay; } // return last output without the eol - std::vector lines() - { + std::vector lines() { std::lock_guard lock(base_sink::mutex_); return lines_; } protected: - void sink_it_(const details::log_msg &msg) override - { + void sink_it_(const details::log_msg &msg) override { memory_buf_t formatted; base_sink::formatter_->format(msg, formatted); // save the line without the eol auto eol_len = strlen(details::os::default_eol); - if (lines_.size() < lines_to_save) - { + if (lines_.size() < lines_to_save) { lines_.emplace_back(formatted.begin(), formatted.end() - eol_len); } msg_counter_++; std::this_thread::sleep_for(delay_); } - void flush_() override - { - flush_counter_++; - } + void flush_() override { flush_counter_++; } size_t msg_counter_{0}; size_t flush_counter_{0}; diff --git a/tests/test_stdout_api.cpp b/tests/test_stdout_api.cpp index d55223ff..67659b84 100644 --- a/tests/test_stdout_api.cpp +++ b/tests/test_stdout_api.cpp @@ -1,11 +1,11 @@ /* - * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + * This content is released under the MIT License as specified in + * https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE */ #include "includes.h" #include "spdlog/sinks/stdout_sinks.h" #include "spdlog/sinks/stdout_color_sinks.h" -TEST_CASE("stdout_st", "[stdout]") -{ +TEST_CASE("stdout_st", "[stdout]") { auto l = spdlog::stdout_logger_st("test"); l->set_pattern("%+"); l->set_level(spdlog::level::trace); @@ -13,8 +13,7 @@ TEST_CASE("stdout_st", "[stdout]") spdlog::drop_all(); } -TEST_CASE("stdout_mt", "[stdout]") -{ +TEST_CASE("stdout_mt", "[stdout]") { auto l = spdlog::stdout_logger_mt("test"); l->set_pattern("%+"); l->set_level(spdlog::level::debug); @@ -22,16 +21,14 @@ TEST_CASE("stdout_mt", "[stdout]") spdlog::drop_all(); } -TEST_CASE("stderr_st", "[stderr]") -{ +TEST_CASE("stderr_st", "[stderr]") { auto l = spdlog::stderr_logger_st("test"); l->set_pattern("%+"); l->info("Test stderr_st"); spdlog::drop_all(); } -TEST_CASE("stderr_mt", "[stderr]") -{ +TEST_CASE("stderr_mt", "[stderr]") { auto l = spdlog::stderr_logger_mt("test"); l->set_pattern("%+"); l->info("Test stderr_mt"); @@ -42,16 +39,14 @@ TEST_CASE("stderr_mt", "[stderr]") } // color loggers -TEST_CASE("stdout_color_st", "[stdout]") -{ +TEST_CASE("stdout_color_st", "[stdout]") { auto l = spdlog::stdout_color_st("test"); l->set_pattern("%+"); l->info("Test stdout_color_st"); spdlog::drop_all(); } -TEST_CASE("stdout_color_mt", "[stdout]") -{ +TEST_CASE("stdout_color_mt", "[stdout]") { auto l = spdlog::stdout_color_mt("test"); l->set_pattern("%+"); l->set_level(spdlog::level::trace); @@ -59,8 +54,7 @@ TEST_CASE("stdout_color_mt", "[stdout]") spdlog::drop_all(); } -TEST_CASE("stderr_color_st", "[stderr]") -{ +TEST_CASE("stderr_color_st", "[stderr]") { auto l = spdlog::stderr_color_st("test"); l->set_pattern("%+"); l->set_level(spdlog::level::debug); @@ -68,8 +62,7 @@ TEST_CASE("stderr_color_st", "[stderr]") spdlog::drop_all(); } -TEST_CASE("stderr_color_mt", "[stderr]") -{ +TEST_CASE("stderr_color_mt", "[stderr]") { auto l = spdlog::stderr_color_mt("test"); l->set_pattern("%+"); l->info("Test stderr_color_mt"); @@ -81,8 +74,7 @@ TEST_CASE("stderr_color_mt", "[stderr]") #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT -TEST_CASE("wchar_api", "[stdout]") -{ +TEST_CASE("wchar_api", "[stdout]") { auto l = spdlog::stdout_logger_st("wchar_logger"); l->set_pattern("%+"); l->set_level(spdlog::level::trace); diff --git a/tests/test_stopwatch.cpp b/tests/test_stopwatch.cpp index 81827b87..b2aa246b 100644 --- a/tests/test_stopwatch.cpp +++ b/tests/test_stopwatch.cpp @@ -2,8 +2,7 @@ #include "test_sink.h" #include "spdlog/stopwatch.h" -TEST_CASE("stopwatch1", "[stopwatch]") -{ +TEST_CASE("stopwatch1", "[stopwatch]") { using std::chrono::milliseconds; using clock = std::chrono::steady_clock; milliseconds wait_ms(200); @@ -17,8 +16,7 @@ TEST_CASE("stopwatch1", "[stopwatch]") REQUIRE(sw.elapsed() <= diff_ms + tolerance_ms); } -TEST_CASE("stopwatch2", "[stopwatch]") -{ +TEST_CASE("stopwatch2", "[stopwatch]") { using spdlog::sinks::test_sink_st; using std::chrono::duration_cast; using std::chrono::milliseconds; diff --git a/tests/test_systemd.cpp b/tests/test_systemd.cpp index 8688f41d..e3636574 100644 --- a/tests/test_systemd.cpp +++ b/tests/test_systemd.cpp @@ -1,8 +1,7 @@ #include "includes.h" #include "spdlog/sinks/systemd_sink.h" -TEST_CASE("systemd", "[all]") -{ +TEST_CASE("systemd", "[all]") { auto systemd_sink = std::make_shared(); spdlog::logger logger("spdlog_systemd_test", systemd_sink); logger.set_level(spdlog::level::trace); diff --git a/tests/test_time_point.cpp b/tests/test_time_point.cpp index bacff69a..c409bb24 100644 --- a/tests/test_time_point.cpp +++ b/tests/test_time_point.cpp @@ -2,8 +2,7 @@ #include "test_sink.h" #include "spdlog/async.h" -TEST_CASE("time_point1", "[time_point log_msg]") -{ +TEST_CASE("time_point1", "[time_point log_msg]") { std::shared_ptr test_sink(new spdlog::sinks::test_sink_st); spdlog::logger logger("test-time_point", test_sink); @@ -13,8 +12,7 @@ TEST_CASE("time_point1", "[time_point log_msg]") // all the following should have the same time test_sink->set_delay(std::chrono::milliseconds(10)); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { spdlog::details::log_msg msg{tp, source, "test_logger", spdlog::level::info, "message"}; test_sink->log(msg); } @@ -23,7 +21,8 @@ TEST_CASE("time_point1", "[time_point log_msg]") logger.log(tp, source, spdlog::level::info, "formatted message"); logger.log(tp, source, spdlog::level::info, "formatted message"); logger.log(tp, source, spdlog::level::info, "formatted message"); - logger.log(source, spdlog::level::info, "formatted message"); // last line has different time_point + logger.log(source, spdlog::level::info, + "formatted message"); // last line has different time_point // now the real test... that the times are the same. std::vector lines = test_sink->lines(); diff --git a/tests/utils.cpp b/tests/utils.cpp index 6d027797..cec29c42 100644 --- a/tests/utils.cpp +++ b/tests/utils.cpp @@ -1,41 +1,35 @@ #include "includes.h" #ifdef _WIN32 -# include + #include #else -# include -# include + #include + #include #endif -void prepare_logdir() -{ +void prepare_logdir() { spdlog::drop_all(); #ifdef _WIN32 system("rmdir /S /Q test_logs"); #else auto rv = system("rm -rf test_logs"); - if (rv != 0) - { + if (rv != 0) { throw std::runtime_error("Failed to rm -rf test_logs"); } #endif } -std::string file_contents(const std::string &filename) -{ +std::string file_contents(const std::string &filename) { std::ifstream ifs(filename, std::ios_base::binary); - if (!ifs) - { + if (!ifs) { throw std::runtime_error("Failed open file "); } return std::string((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); } -std::size_t count_lines(const std::string &filename) -{ +std::size_t count_lines(const std::string &filename) { std::ifstream ifs(filename); - if (!ifs) - { + if (!ifs) { throw std::runtime_error("Failed open file "); } @@ -46,23 +40,17 @@ std::size_t count_lines(const std::string &filename) return counter; } -void require_message_count(const std::string &filename, const std::size_t messages) -{ - if (strlen(spdlog::details::os::default_eol) == 0) - { +void require_message_count(const std::string &filename, const std::size_t messages) { + if (strlen(spdlog::details::os::default_eol) == 0) { REQUIRE(count_lines(filename) == 1); - } - else - { + } else { REQUIRE(count_lines(filename) == messages); } } -std::size_t get_filesize(const std::string &filename) -{ +std::size_t get_filesize(const std::string &filename) { std::ifstream ifs(filename, std::ifstream::ate | std::ifstream::binary); - if (!ifs) - { + if (!ifs) { throw std::runtime_error("Failed open file "); } @@ -70,10 +58,8 @@ std::size_t get_filesize(const std::string &filename) } // source: https://stackoverflow.com/a/2072890/192001 -bool ends_with(std::string const &value, std::string const &ending) -{ - if (ending.size() > value.size()) - { +bool ends_with(std::string const &value, std::string const &ending) { + if (ending.size() > value.size()) { return false; } return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); @@ -81,24 +67,20 @@ bool ends_with(std::string const &value, std::string const &ending) #ifdef _WIN32 // Based on: https://stackoverflow.com/a/37416569/192001 -std::size_t count_files(const std::string &folder) -{ +std::size_t count_files(const std::string &folder) { size_t counter = 0; WIN32_FIND_DATAA ffd; // Start iterating over the files in the folder directory. HANDLE hFind = ::FindFirstFileA((folder + "\\*").c_str(), &ffd); - if (hFind != INVALID_HANDLE_VALUE) - { + if (hFind != INVALID_HANDLE_VALUE) { do // Managed to locate and create an handle to that folder. { if (ffd.cFileName[0] != '.') counter++; } while (::FindNextFileA(hFind, &ffd) != 0); ::FindClose(hFind); - } - else - { + } else { throw std::runtime_error("Failed open folder " + folder); } @@ -106,18 +88,15 @@ std::size_t count_files(const std::string &folder) } #else // Based on: https://stackoverflow.com/a/2802255/192001 -std::size_t count_files(const std::string &folder) -{ +std::size_t count_files(const std::string &folder) { size_t counter = 0; DIR *dp = opendir(folder.c_str()); - if (dp == nullptr) - { + if (dp == nullptr) { throw std::runtime_error("Failed open folder " + folder); } struct dirent *ep = nullptr; - while ((ep = readdir(dp)) != nullptr) - { + while ((ep = readdir(dp)) != nullptr) { if (ep->d_name[0] != '.') counter++; }