From 8696ad8739ae35b9caf290c6905c713d5fd00378 Mon Sep 17 00:00:00 2001 From: fegomes Date: Wed, 24 Jan 2018 23:08:46 -0200 Subject: [PATCH 01/62] new function to convert level_enum from string --- include/spdlog/common.h | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index ea0b0567..339e8b29 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -51,6 +51,9 @@ namespace spdlog class formatter; +template +constexpr size_t size(T(&)[N]) { return N; } + namespace sinks { class sink; @@ -98,6 +101,18 @@ inline const char* to_short_str(spdlog::level::level_enum l) { return short_level_names[l]; } +inline spdlog::level::level_enum to_level_enum(const char* name) +{ + for (size_t level = 0; level < size(level_names); level++) + { + if (!strcmp(level_names[level], name)) + { + return (spdlog::level::level_enum) level; + } + } + return (spdlog::level::level_enum) 0; +} + } //level From 48c8755d06bfa56e5771832078d23628da7db03e Mon Sep 17 00:00:00 2001 From: fegomes Date: Thu, 8 Mar 2018 19:08:24 -0300 Subject: [PATCH 02/62] include test to convert functions and change suggested by @gabime --- include/spdlog/common.h | 34 ++++++++++++++++++++++++---------- tests/test_misc.cpp | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 10 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index cad705f9..2ef4d24c 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -15,7 +15,8 @@ #include #include #include -#include +#include +#include #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) #include @@ -89,6 +90,17 @@ enum level_enum off = 6 }; +static std::unordered_map name_to_level = { + { "trace" , level::trace }, + { "debug" , level::debug }, + { "info" , level::info }, + { "warning" , level::warn }, + { "error" , level::err }, + { "critical", level::critical }, + { "off" , level::off } + }; + + #if !defined(SPDLOG_LEVEL_NAMES) #define SPDLOG_LEVEL_NAMES { "trace", "debug", "info", "warning", "error", "critical", "off" } #endif @@ -105,17 +117,19 @@ inline const char* to_short_str(spdlog::level::level_enum l) { return short_level_names[l]; } -inline spdlog::level::level_enum to_level_enum(const char* name) +inline spdlog::level::level_enum to_level_enum(const std::string& name) { - for (size_t level = 0; level < size(level_names); level++) - { - if (!strcmp(level_names[level], name)) - { - return (spdlog::level::level_enum) level; - } - } - return (spdlog::level::level_enum) 0; + auto ci = name_to_level.find(name); + if (ci != name_to_level.end()) + { + return ci->second; + } + else + { + return level::off; + } } + using level_hasher = std::hash; } //level diff --git a/tests/test_misc.cpp b/tests/test_misc.cpp index 9afaa932..9f97a9d8 100644 --- a/tests/test_misc.cpp +++ b/tests/test_misc.cpp @@ -42,6 +42,39 @@ TEST_CASE("log_levels", "[log_levels]") REQUIRE(log_info("Hello", spdlog::level::trace) == "Hello"); } +TEST_CASE("to_str", "[convert_to_str]") +{ + REQUIRE(std::string(spdlog::level::to_str(spdlog::level::trace)) == "trace"); + REQUIRE(std::string(spdlog::level::to_str(spdlog::level::debug)) == "debug"); + REQUIRE(std::string(spdlog::level::to_str(spdlog::level::info)) == "info"); + REQUIRE(std::string(spdlog::level::to_str(spdlog::level::warn)) == "warning"); + REQUIRE(std::string(spdlog::level::to_str(spdlog::level::err)) == "error"); + REQUIRE(std::string(spdlog::level::to_str(spdlog::level::critical)) == "critical"); + REQUIRE(std::string(spdlog::level::to_str(spdlog::level::off)) == "off"); +} + +TEST_CASE("to_short_str", "[convert_to_short_str]") +{ + REQUIRE(std::string(spdlog::level::to_short_str(spdlog::level::trace)) == "T"); + REQUIRE(std::string(spdlog::level::to_short_str(spdlog::level::debug)) == "D"); + REQUIRE(std::string(spdlog::level::to_short_str(spdlog::level::info)) == "I"); + REQUIRE(std::string(spdlog::level::to_short_str(spdlog::level::warn)) == "W"); + REQUIRE(std::string(spdlog::level::to_short_str(spdlog::level::err)) == "E"); + REQUIRE(std::string(spdlog::level::to_short_str(spdlog::level::critical)) == "C"); + REQUIRE(std::string(spdlog::level::to_short_str(spdlog::level::off)) == "O"); +} + +TEST_CASE("to_level_enum", "[convert_to_level_enum]") +{ + REQUIRE(spdlog::level::to_level_enum("trace") == spdlog::level::trace); + REQUIRE(spdlog::level::to_level_enum("debug") == spdlog::level::debug); + REQUIRE(spdlog::level::to_level_enum("info") == spdlog::level::info); + REQUIRE(spdlog::level::to_level_enum("warning") == spdlog::level::warn); + REQUIRE(spdlog::level::to_level_enum("error") == spdlog::level::err); + REQUIRE(spdlog::level::to_level_enum("critical") == spdlog::level::critical); + REQUIRE(spdlog::level::to_level_enum("off") == spdlog::level::off); + REQUIRE(spdlog::level::to_level_enum("null") == spdlog::level::off); +} From c21dd874d1bea2a7d692409144dd499f848ba4a6 Mon Sep 17 00:00:00 2001 From: fegomes Date: Thu, 8 Mar 2018 19:09:46 -0300 Subject: [PATCH 03/62] removed class to return size of array. --- include/spdlog/common.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 2ef4d24c..bad9c317 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -56,9 +56,6 @@ namespace spdlog class formatter; -template -constexpr size_t size(T(&)[N]) { return N; } - namespace sinks { class sink; From 2e098421f1d635895e8f18c499c57502010213bd Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 9 Mar 2018 12:08:56 +0200 Subject: [PATCH 04/62] added .log extension to bench test --- example/bench.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/example/bench.cpp b/example/bench.cpp index b21c4435..e42bec1f 100644 --- a/example/bench.cpp +++ b/example/bench.cpp @@ -53,9 +53,9 @@ int main(int argc, char* argv[]) cout << "Single thread, " << format(howmany) << " iterations" << endl; cout << "*******************************************************************************\n"; - auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st", file_size, rotating_files); + auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files); bench(howmany, rotating_st); - auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st"); + auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log"); bench(howmany, daily_st); bench(howmany, spdlog::create("null_st")); @@ -63,11 +63,11 @@ int main(int argc, char* argv[]) cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl; cout << "*******************************************************************************\n"; - auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt", file_size, rotating_files); + auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files); bench_mt(howmany, rotating_mt, threads); - auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt"); + auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log"); bench_mt(howmany, daily_mt, threads); bench(howmany, spdlog::create("null_mt")); @@ -80,7 +80,7 @@ int main(int argc, char* argv[]) for(int i = 0; i < 3; ++i) { - auto as = spdlog::daily_logger_st("as", "logs/daily_async"); + auto as = spdlog::daily_logger_st("as", "logs/daily_async.log"); bench_mt(howmany, as, threads); spdlog::drop("as"); } From 46f97685994b96b91301dfe5a5e21a80062a23e2 Mon Sep 17 00:00:00 2001 From: fegomes Date: Fri, 9 Mar 2018 09:04:44 -0300 Subject: [PATCH 05/62] change of scope the name_to_level variable --- include/spdlog/common.h | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index bad9c317..cb656386 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -87,16 +87,6 @@ enum level_enum off = 6 }; -static std::unordered_map name_to_level = { - { "trace" , level::trace }, - { "debug" , level::debug }, - { "info" , level::info }, - { "warning" , level::warn }, - { "error" , level::err }, - { "critical", level::critical }, - { "off" , level::off } - }; - #if !defined(SPDLOG_LEVEL_NAMES) #define SPDLOG_LEVEL_NAMES { "trace", "debug", "info", "warning", "error", "critical", "off" } @@ -116,6 +106,15 @@ inline const char* to_short_str(spdlog::level::level_enum l) } inline spdlog::level::level_enum to_level_enum(const std::string& name) { + static std::unordered_map name_to_level = { + { level_names[0], level::trace }, + { level_names[1], level::debug }, + { level_names[2], level::info }, + { level_names[3], level::warn }, + { level_names[4], level::err }, + { level_names[5], level::critical }, + { level_names[6], level::off } + }; auto ci = name_to_level.find(name); if (ci != name_to_level.end()) { From 1f79c01dc4dd21ac29c278a9ccd23c298ac83246 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 9 Mar 2018 14:27:15 +0200 Subject: [PATCH 06/62] Use clang-format-5.0 instead of astyle --- format.sh | 5 +++++ 1 file changed, 5 insertions(+) create mode 100755 format.sh diff --git a/format.sh b/format.sh new file mode 100755 index 00000000..e23097b9 --- /dev/null +++ b/format.sh @@ -0,0 +1,5 @@ +#!/bin/bash +find . -name "*\.h" -o -name "*\.cpp"|xargs dos2unix +find . -name "*\.h" -o -name "*\.cpp"|xargs clang-format-5.0 -i + + From 03bc9ebb1fcbcbb68703f5e17b4e2b18d8e8c011 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 9 Mar 2018 14:29:20 +0200 Subject: [PATCH 07/62] .clang-format --- .clang-format | 108 ++++++++++++++++++++++++++++++++++++++++++++++++++ astyle.sh | 5 --- 2 files changed, 108 insertions(+), 5 deletions(-) create mode 100644 .clang-format delete mode 100755 astyle.sh diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..b30d71b1 --- /dev/null +++ b/.clang-format @@ -0,0 +1,108 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -4 +AlignAfterOpenBracket: DontAlign +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Right +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: false +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: true + AfterStruct: true + AfterUnion: true + BeforeCatch: true + BeforeElse: true + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 140 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: true +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + - Regex: '.*' + Priority: 1 +IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: false +IndentWidth: 4 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 +TabWidth: 8 +UseTab: Never +... + diff --git a/astyle.sh b/astyle.sh deleted file mode 100755 index a7a90510..00000000 --- a/astyle.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash -find . -name "*\.h" -o -name "*\.cpp"|xargs dos2unix -find . -name "*\.h" -o -name "*\.cpp"|xargs astyle -n -c -A1 - - From d741f1b6540853402b8b352ad2f996fd84be7c50 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 9 Mar 2018 15:02:15 +0200 Subject: [PATCH 08/62] some clang format fixes --- .clang-format | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.clang-format b/.clang-format index b30d71b1..ba46f843 100644 --- a/.clang-format +++ b/.clang-format @@ -11,7 +11,7 @@ AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: true AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: All +AllowShortFunctionsOnASingleLine: Empty AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None @@ -39,7 +39,7 @@ BreakBeforeBinaryOperators: None BreakBeforeBraces: Custom BreakBeforeInheritanceComma: false BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializersBeforeComma: true BreakConstructorInitializers: BeforeColon BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true From 7f1f7b62327bb2b048a10f3feeefe2d1887003f6 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 9 Mar 2018 15:24:37 +0200 Subject: [PATCH 09/62] Changed function name to level::from_str --- include/spdlog/common.h | 96 ++++++++++++++++++----------------------- tests/test_misc.cpp | 37 ++++++---------- 2 files changed, 57 insertions(+), 76 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index cb656386..3ba8931d 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -9,13 +9,13 @@ #include "tweakme.h" -#include -#include -#include -#include #include +#include #include #include +#include +#include +#include #include #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) @@ -25,7 +25,7 @@ #include "details/null_mutex.h" -//visual studio upto 2013 does not support noexcept nor constexpr +// visual studio upto 2013 does not support noexcept nor constexpr #if defined(_MSC_VER) && (_MSC_VER < 1900) #define SPDLOG_NOEXCEPT throw() #define SPDLOG_CONSTEXPR @@ -41,7 +41,7 @@ #define SPDLOG_FINAL final #endif -#if defined(__GNUC__) || defined(__clang__) +#if defined(__GNUC__) || defined(__clang__) #define SPDLOG_DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) #define SPDLOG_DEPRECATED __declspec(deprecated) @@ -51,19 +51,17 @@ #include "fmt/fmt.h" -namespace spdlog -{ +namespace spdlog { class formatter; -namespace sinks -{ +namespace sinks { class sink; } using log_clock = std::chrono::system_clock; -using sink_ptr = std::shared_ptr < sinks::sink >; -using sinks_init_list = std::initializer_list < sink_ptr >; +using sink_ptr = std::shared_ptr; +using sinks_init_list = std::initializer_list; using formatter_ptr = std::shared_ptr; #if defined(SPDLOG_NO_ATOMIC_LEVELS) using level_t = details::null_atomic_int; @@ -73,9 +71,8 @@ using level_t = std::atomic; using log_err_handler = std::function; -//Log level enum -namespace level -{ +// Log level enum +namespace level { enum level_enum { trace = 0, @@ -87,54 +84,49 @@ enum level_enum off = 6 }; - #if !defined(SPDLOG_LEVEL_NAMES) -#define SPDLOG_LEVEL_NAMES { "trace", "debug", "info", "warning", "error", "critical", "off" } +#define SPDLOG_LEVEL_NAMES \ + { \ + "trace", "debug", "info", "warning", "error", "critical", "off" \ + } #endif -static const char* level_names[] SPDLOG_LEVEL_NAMES; +static const char *level_names[] SPDLOG_LEVEL_NAMES; -static const char* short_level_names[] { "T", "D", "I", "W", "E", "C", "O" }; +static const char *short_level_names[]{"T", "D", "I", "W", "E", "C", "O"}; -inline const char* to_str(spdlog::level::level_enum l) +inline const char *to_str(spdlog::level::level_enum l) { return level_names[l]; } -inline const char* to_short_str(spdlog::level::level_enum l) +inline const char *to_short_str(spdlog::level::level_enum l) { return short_level_names[l]; } -inline spdlog::level::level_enum to_level_enum(const std::string& name) +inline spdlog::level::level_enum to_level_enum(const std::string &name) { - static std::unordered_map name_to_level = { - { level_names[0], level::trace }, - { level_names[1], level::debug }, - { level_names[2], level::info }, - { level_names[3], level::warn }, - { level_names[4], level::err }, - { level_names[5], level::critical }, - { level_names[6], level::off } - }; - auto ci = name_to_level.find(name); - if (ci != name_to_level.end()) - { - return ci->second; - } - else - { - return level::off; - } + static std::unordered_map name_to_level = // map string->level + {{level_names[0], level::trace}, // trace + {level_names[1], level::debug}, // debug + {level_names[2], level::info}, // info + {level_names[3], level::warn}, // warn + {level_names[4], level::err}, // err + {level_names[5], level::critical}, // critical + {level_names[6], level::off}}; // off + + auto lvl_it = name_to_level.find(name); + return lvl_it != name_to_level.end() ? lvl_it->second : level::off } using level_hasher = std::hash; -} //level +} // namespace level // // Async overflow policy - block by default. // enum class async_overflow_policy { - block_retry, // Block / yield / sleep until message can be enqueued + block_retry, // Block / yield / sleep until message can be enqueued discard_log_msg // Discard the message it enqueue fails }; @@ -151,25 +143,23 @@ enum class pattern_time_type // // Log exception // -namespace details -{ -namespace os -{ +namespace details { namespace os { std::string errno_str(int err_num); -} -} +}} // namespace details::os class spdlog_ex : public std::exception { public: - explicit spdlog_ex(std::string msg) : _msg(std::move(msg)) - {} + explicit spdlog_ex(std::string msg) + : _msg(std::move(msg)) + { + } - spdlog_ex(const std::string& msg, int last_errno) + spdlog_ex(const std::string &msg, int last_errno) { _msg = msg + ": " + details::os::errno_str(last_errno); } - const char* what() const SPDLOG_NOEXCEPT override + const char *what() const SPDLOG_NOEXCEPT override { return _msg.c_str(); } @@ -187,4 +177,4 @@ using filename_t = std::wstring; using filename_t = std::string; #endif -} //spdlog +} // namespace spdlog diff --git a/tests/test_misc.cpp b/tests/test_misc.cpp index 9f97a9d8..772e928d 100644 --- a/tests/test_misc.cpp +++ b/tests/test_misc.cpp @@ -1,7 +1,6 @@ #include "includes.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; @@ -17,20 +16,20 @@ std::string log_info(const T& what, spdlog::level::level_enum logger_level = spd TEST_CASE("basic_logging ", "[basic_logging]") { - //const char + // const char REQUIRE(log_info("Hello") == "Hello"); REQUIRE(log_info("") == ""); - //std::string + // std::string REQUIRE(log_info(std::string("Hello")) == "Hello"); REQUIRE(log_info(std::string()) == std::string()); - //Numbers + // Numbers REQUIRE(log_info(5) == "5"); REQUIRE(log_info(5.6) == "5.6"); - //User defined class - //REQUIRE(log_info(some_logged_class("some_val")) == "some_val"); + // User defined class + // REQUIRE(log_info(some_logged_class("some_val")) == "some_val"); } TEST_CASE("log_levels", "[log_levels]") @@ -66,20 +65,12 @@ TEST_CASE("to_short_str", "[convert_to_short_str]") TEST_CASE("to_level_enum", "[convert_to_level_enum]") { - REQUIRE(spdlog::level::to_level_enum("trace") == spdlog::level::trace); - REQUIRE(spdlog::level::to_level_enum("debug") == spdlog::level::debug); - REQUIRE(spdlog::level::to_level_enum("info") == spdlog::level::info); - REQUIRE(spdlog::level::to_level_enum("warning") == spdlog::level::warn); - REQUIRE(spdlog::level::to_level_enum("error") == spdlog::level::err); - REQUIRE(spdlog::level::to_level_enum("critical") == spdlog::level::critical); - REQUIRE(spdlog::level::to_level_enum("off") == spdlog::level::off); - REQUIRE(spdlog::level::to_level_enum("null") == spdlog::level::off); + 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); + REQUIRE(spdlog::level::from_str("warning") == spdlog::level::warn); + REQUIRE(spdlog::level::from_str("error") == spdlog::level::err); + REQUIRE(spdlog::level::from_str("critical") == spdlog::level::critical); + REQUIRE(spdlog::level::from_str("off") == spdlog::level::off); + REQUIRE(spdlog::level::from_str("null") == spdlog::level::off); } - - - - - - - - From 461b5ef28a2afa3e94a1d03fb2c98ae9f4423dcc Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 9 Mar 2018 15:26:00 +0200 Subject: [PATCH 10/62] Fixed missing ; --- include/spdlog/common.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 3ba8931d..b4e10170 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -115,7 +115,7 @@ inline spdlog::level::level_enum to_level_enum(const std::string &name) {level_names[6], level::off}}; // off auto lvl_it = name_to_level.find(name); - return lvl_it != name_to_level.end() ? lvl_it->second : level::off + return lvl_it != name_to_level.end() ? lvl_it->second : level::off; } using level_hasher = std::hash; From a2653d409ffa04b6543cde83db3e24f4c47d258f Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 9 Mar 2018 15:26:33 +0200 Subject: [PATCH 11/62] clang-format --- bench/boost-bench-mt.cpp | 45 +- bench/boost-bench.cpp | 28 +- bench/easylogging-bench-mt.cpp | 17 +- bench/easylogging-bench.cpp | 5 +- bench/g2log-async.cpp | 30 +- bench/glog-bench-mt.cpp | 17 +- bench/glog-bench.cpp | 6 +- bench/latency/g3log-crush.cpp | 11 +- bench/latency/g3log-latency.cpp | 61 +- bench/latency/spdlog-latency.cpp | 47 +- bench/latency/utils.h | 13 +- bench/spdlog-async.cpp | 27 +- bench/spdlog-bench-mt.cpp | 24 +- bench/spdlog-bench.cpp | 7 +- bench/spdlog-null-async.cpp | 47 +- bench/utils.h | 13 +- example/bench.cpp | 48 +- example/example.cpp | 37 +- example/jni/example.cpp | 157 +- example/multisink.cpp | 29 +- example/utils.h | 13 +- include/spdlog/async_logger.h | 57 +- include/spdlog/details/async_log_helper.h | 160 +- include/spdlog/details/async_logger_impl.h | 66 +- include/spdlog/details/file_helper.h | 30 +- include/spdlog/details/log_msg.h | 25 +- include/spdlog/details/logger_impl.h | 151 +- include/spdlog/details/mpmc_bounded_q.h | 59 +- include/spdlog/details/null_mutex.h | 14 +- include/spdlog/details/os.h | 174 +- .../spdlog/details/pattern_formatter_impl.h | 216 +- include/spdlog/details/registry.h | 82 +- include/spdlog/details/spdlog_impl.h | 97 +- include/spdlog/fmt/bundled/format.h | 1938 ++++++++--------- include/spdlog/fmt/bundled/ostream.h | 35 +- include/spdlog/fmt/bundled/posix.h | 123 +- include/spdlog/fmt/bundled/printf.h | 146 +- include/spdlog/fmt/bundled/time.h | 40 +- include/spdlog/fmt/fmt.h | 3 +- include/spdlog/fmt/ostr.h | 4 +- include/spdlog/formatter.h | 27 +- include/spdlog/logger.h | 80 +- include/spdlog/sinks/android_sink.h | 36 +- include/spdlog/sinks/ansicolor_sink.h | 44 +- include/spdlog/sinks/base_sink.h | 23 +- include/spdlog/sinks/dist_sink.h | 26 +- include/spdlog/sinks/file_sinks.h | 70 +- include/spdlog/sinks/msvc_sink.h | 26 +- include/spdlog/sinks/null_sink.h | 21 +- include/spdlog/sinks/ostream_sink.h | 27 +- include/spdlog/sinks/sink.h | 12 +- include/spdlog/sinks/stdout_sinks.h | 18 +- include/spdlog/sinks/syslog_sink.h | 30 +- include/spdlog/sinks/wincolor_sink.h | 48 +- include/spdlog/sinks/windebug_sink.h | 15 +- include/spdlog/spdlog.h | 109 +- include/spdlog/tweakme.h | 17 - tests/errors.cpp | 48 +- tests/file_helper.cpp | 8 +- tests/file_log.cpp | 28 +- tests/includes.h | 13 +- tests/registry.cpp | 39 +- tests/test_macros.cpp | 12 +- tests/test_pattern_formatter.cpp | 8 +- tests/utils.cpp | 20 +- tests/utils.h | 12 +- 66 files changed, 2331 insertions(+), 2588 deletions(-) mode change 120000 => 100644 example/jni/example.cpp diff --git a/bench/boost-bench-mt.cpp b/bench/boost-bench-mt.cpp index d845fcec..73219b91 100644 --- a/bench/boost-bench-mt.cpp +++ b/bench/boost-bench-mt.cpp @@ -3,18 +3,18 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // +#include #include #include -#include #include -#include #include #include -#include -#include -#include #include +#include +#include +#include +#include namespace logging = boost::log; namespace src = boost::log::sources; @@ -23,62 +23,49 @@ namespace keywords = boost::log::keywords; void init() { - logging::add_file_log - ( - keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/ - keywords::auto_flush = false, - keywords::format = "[%TimeStamp%]: %Message%" - ); + logging::add_file_log(keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/ + keywords::auto_flush = false, keywords::format = "[%TimeStamp%]: %Message%"); - logging::core::get()->set_filter - ( - logging::trivial::severity >= logging::trivial::info - ); + logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info); } - - using namespace std; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = atoi(argv[1]); int howmany = 1000000; - init(); logging::add_common_attributes(); - using namespace logging::trivial; - src::severity_logger_mt< severity_level > lg; + src::severity_logger_mt lg; - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; BOOST_LOG_SEV(lg, info) << "boost message #" << counter << ": This is some text for your pleasure"; } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; - return 0; } diff --git a/bench/boost-bench.cpp b/bench/boost-bench.cpp index 32c5b692..cb432578 100644 --- a/bench/boost-bench.cpp +++ b/bench/boost-bench.cpp @@ -3,13 +3,13 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // #include -#include #include #include -#include -#include -#include #include +#include +#include +#include +#include namespace logging = boost::log; namespace src = boost::log::sources; @@ -18,29 +18,21 @@ namespace keywords = boost::log::keywords; void init() { - logging::add_file_log - ( - keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/ - keywords::auto_flush = false, - keywords::format = "[%TimeStamp%]: %Message%" - ); + logging::add_file_log(keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/ + keywords::auto_flush = false, keywords::format = "[%TimeStamp%]: %Message%"); - logging::core::get()->set_filter - ( - logging::trivial::severity >= logging::trivial::info - ); + logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info); } - -int main(int argc, char* []) +int main(int argc, char *[]) { int howmany = 1000000; init(); logging::add_common_attributes(); using namespace logging::trivial; - src::severity_logger_mt< severity_level > lg; - for(int i = 0 ; i < howmany; ++i) + src::severity_logger_mt lg; + for (int i = 0; i < howmany; ++i) BOOST_LOG_SEV(lg, info) << "boost message #" << i << ": This is some text for your pleasure"; return 0; diff --git a/bench/easylogging-bench-mt.cpp b/bench/easylogging-bench-mt.cpp index 98d1ae35..00f507c6 100644 --- a/bench/easylogging-bench-mt.cpp +++ b/bench/easylogging-bench-mt.cpp @@ -3,9 +3,9 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // +#include #include #include -#include #define _ELPP_THREAD_SAFE #include "easylogging++.h" @@ -13,11 +13,11 @@ _INITIALIZE_EASYLOGGINGPP using namespace std; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = atoi(argv[1]); int howmany = 1000000; @@ -26,24 +26,23 @@ int main(int argc, char* argv[]) el::Configurations conf("easyl.conf"); el::Loggers::reconfigureLogger("default", conf); - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; LOG(INFO) << "easylog message #" << counter << ": This is some text for your pleasure"; } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; diff --git a/bench/easylogging-bench.cpp b/bench/easylogging-bench.cpp index a952cbd5..5306435f 100644 --- a/bench/easylogging-bench.cpp +++ b/bench/easylogging-bench.cpp @@ -3,12 +3,11 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // - #include "easylogging++.h" _INITIALIZE_EASYLOGGINGPP -int main(int, char* []) +int main(int, char *[]) { int howmany = 1000000; @@ -16,7 +15,7 @@ int main(int, char* []) el::Configurations conf("easyl.conf"); el::Loggers::reconfigureLogger("default", conf); - for(int i = 0 ; i < howmany; ++i) + for (int i = 0; i < howmany; ++i) LOG(INFO) << "easylog message #" << i << ": This is some text for your pleasure"; return 0; } diff --git a/bench/g2log-async.cpp b/bench/g2log-async.cpp index 9f9eb71e..97cac5dc 100644 --- a/bench/g2log-async.cpp +++ b/bench/g2log-async.cpp @@ -3,57 +3,55 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#include -#include #include -#include #include +#include +#include +#include -#include "g2logworker.h" #include "g2log.h" +#include "g2logworker.h" using namespace std; -template std::string format(const T& value); +template std::string format(const T &value); -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { using namespace std::chrono; - using clock=steady_clock; + using clock = steady_clock; int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = atoi(argv[1]); int howmany = 1000000; g2LogWorker g2log(argv[0], "logs"); g2::initializeLogging(&g2log); - - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; auto start = clock::now(); for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; LOG(INFO) << "g2log message #" << counter << ": This is some text for your pleasure"; } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; duration delta = clock::now() - start; float deltaf = delta.count(); - auto rate = howmany/deltaf; + auto rate = howmany / deltaf; cout << "Total: " << howmany << std::endl; cout << "Threads: " << thread_count << std::endl; diff --git a/bench/glog-bench-mt.cpp b/bench/glog-bench-mt.cpp index db193aeb..5e43de78 100644 --- a/bench/glog-bench-mt.cpp +++ b/bench/glog-bench-mt.cpp @@ -3,19 +3,19 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // +#include #include #include -#include #include "glog/logging.h" using namespace std; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = atoi(argv[1]); int howmany = 1000000; @@ -24,24 +24,23 @@ int main(int argc, char* argv[]) FLAGS_log_dir = "logs"; google::InitGoogleLogging(argv[0]); - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; LOG(INFO) << "glog message #" << counter << ": This is some text for your pleasure"; } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; diff --git a/bench/glog-bench.cpp b/bench/glog-bench.cpp index cf7e70a2..2a8db891 100644 --- a/bench/glog-bench.cpp +++ b/bench/glog-bench.cpp @@ -5,16 +5,14 @@ #include "glog/logging.h" - -int main(int, char* argv[]) +int main(int, char *argv[]) { int howmany = 1000000; - FLAGS_logtostderr = 0; FLAGS_log_dir = "logs"; google::InitGoogleLogging(argv[0]); - for(int i = 0 ; i < howmany; ++i) + for (int i = 0; i < howmany; ++i) LOG(INFO) << "glog message # " << i << ": This is some text for your pleasure"; return 0; diff --git a/bench/latency/g3log-crush.cpp b/bench/latency/g3log-crush.cpp index 417b014c..5ab85d7a 100644 --- a/bench/latency/g3log-crush.cpp +++ b/bench/latency/g3log-crush.cpp @@ -9,29 +9,26 @@ void CrusherLoop() while (true) { LOGF(INFO, "Some text to crush you machine. thread:"); - if(++counter % 1000000 == 0) + if (++counter % 1000000 == 0) { std::cout << "Wrote " << counter << " entries" << std::endl; } } } - -int main(int argc, char** argv) +int main(int argc, char **argv) { std::cout << "WARNING: This test will exaust all your machine memory and will crush it!" << std::endl; std::cout << "Are you sure you want to continue ? " << std::endl; char c; std::cin >> c; - if (toupper( c ) != 'Y') + if (toupper(c) != 'Y') return 0; auto worker = g3::LogWorker::createLogWorker(); - auto handle= worker->addDefaultLogger(argv[0], "g3log.txt"); + auto handle = worker->addDefaultLogger(argv[0], "g3log.txt"); g3::initializeLogging(worker.get()); CrusherLoop(); return 0; } - - diff --git a/bench/latency/g3log-latency.cpp b/bench/latency/g3log-latency.cpp index e96e421b..fe067f77 100644 --- a/bench/latency/g3log-latency.cpp +++ b/bench/latency/g3log-latency.cpp @@ -1,32 +1,26 @@ -#include -#include +#include "utils.h" +#include #include -#include #include -#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include #include #include -#include +#include #include -#include "utils.h" -#include -#include - +#include -namespace -{ +namespace { const uint64_t g_iterations = 1000000; - std::atomic g_counter = {0}; - -void MeasurePeakDuringLogWrites(const size_t id, std::vector& result) +void MeasurePeakDuringLogWrites(const size_t id, std::vector &result) { while (true) @@ -45,14 +39,12 @@ void MeasurePeakDuringLogWrites(const size_t id, std::vector& result) } } - - -void PrintResults(const std::map>& threads_result, size_t total_us) +void PrintResults(const std::map> &threads_result, size_t total_us) { std::vector all_measurements; all_measurements.reserve(g_iterations); - for (auto& t_result : threads_result) + for (auto &t_result : threads_result) { all_measurements.insert(all_measurements.end(), t_result.second.begin(), t_result.second.end()); } @@ -62,13 +54,12 @@ void PrintResults(const std::map>& threads_result, // calc avg auto total = accumulate(begin(all_measurements), end(all_measurements), 0, std::plus()); - auto avg = double(total)/all_measurements.size(); - - std::cout << "[g3log] worst: " << std::setw(10) << std::right << worst << "\tAvg: " << avg << "\tTotal: " << utils::format(total_us) << " us" << std::endl; + auto avg = double(total) / all_measurements.size(); + std::cout << "[g3log] worst: " << std::setw(10) << std::right << worst << "\tAvg: " << avg << "\tTotal: " << utils::format(total_us) + << " us" << std::endl; } -}// anonymous - +} // namespace // The purpose of this test is NOT to see how fast // each thread can possibly write. It is to see what @@ -78,9 +69,9 @@ void PrintResults(const std::map>& threads_result, // an atomic counter is used to give each thread what // it is to write next. The overhead of atomic // synchronization between the threads are not counted in the worst case latency -int main(int argc, char** argv) +int main(int argc, char **argv) { - size_t number_of_threads {0}; + size_t number_of_threads{0}; if (argc == 2) { number_of_threads = atoi(argv[1]); @@ -91,7 +82,6 @@ int main(int argc, char** argv) return 1; } - std::vector threads(number_of_threads); std::map> threads_result; @@ -102,12 +92,12 @@ int main(int argc, char** argv) threads_result[idx].reserve(g_iterations); } - const std::string g_path = "./" ; - const std::string g_prefix_log_name = "g3log-performance-"; - const std::string g_measurement_dump = g_path + g_prefix_log_name + "_RESULT.txt"; + const std::string g_path = "./"; + const std::string g_prefix_log_name = "g3log-performance-"; + const std::string g_measurement_dump = g_path + g_prefix_log_name + "_RESULT.txt"; auto worker = g3::LogWorker::createLogWorker(); - auto handle= worker->addDefaultLogger(argv[0], "g3log.txt"); + auto handle = worker->addDefaultLogger(argv[0], "g3log.txt"); g3::initializeLogging(worker.get()); auto start_time_application_total = std::chrono::high_resolution_clock::now(); @@ -121,9 +111,8 @@ int main(int argc, char** argv) } auto stop_time_application_total = std::chrono::high_resolution_clock::now(); - uint64_t total_time_in_us = std::chrono::duration_cast(stop_time_application_total - start_time_application_total).count(); + uint64_t total_time_in_us = + std::chrono::duration_cast(stop_time_application_total - start_time_application_total).count(); PrintResults(threads_result, total_time_in_us); return 0; } - - diff --git a/bench/latency/spdlog-latency.cpp b/bench/latency/spdlog-latency.cpp index ed4966cc..a2200c5d 100644 --- a/bench/latency/spdlog-latency.cpp +++ b/bench/latency/spdlog-latency.cpp @@ -1,31 +1,26 @@ -#include -#include +#include "utils.h" +#include #include -#include #include -#include -#include #include +#include +#include #include #include -#include -#include "utils.h" #include +#include #include "spdlog/spdlog.h" namespace spd = spdlog; -namespace -{ +namespace { const uint64_t g_iterations = 1000000; - std::atomic g_counter = {0}; - -void MeasurePeakDuringLogWrites(const size_t id, std::vector& result) +void MeasurePeakDuringLogWrites(const size_t id, std::vector &result) { auto logger = spd::get("file_logger"); while (true) @@ -44,13 +39,12 @@ void MeasurePeakDuringLogWrites(const size_t id, std::vector& result) } } - -void PrintResults(const std::map>& threads_result, size_t total_us) +void PrintResults(const std::map> &threads_result, size_t total_us) { std::vector all_measurements; all_measurements.reserve(g_iterations); - for (auto& t_result : threads_result) + for (auto &t_result : threads_result) { all_measurements.insert(all_measurements.end(), t_result.second.begin(), t_result.second.end()); } @@ -60,13 +54,12 @@ void PrintResults(const std::map>& threads_result, // calc avg auto total = accumulate(begin(all_measurements), end(all_measurements), 0, std::plus()); - auto avg = double(total)/all_measurements.size(); - - std::cout << "[spdlog] worst: " << std::setw(10) << std::right << worst << "\tAvg: " << avg << "\tTotal: " << utils::format(total_us) << " us" << std::endl; + auto avg = double(total) / all_measurements.size(); + std::cout << "[spdlog] worst: " << std::setw(10) << std::right << worst << "\tAvg: " << avg << "\tTotal: " << utils::format(total_us) + << " us" << std::endl; } -}// anonymous - +} // namespace // The purpose of this test is NOT to see how fast // each thread can possibly write. It is to see what @@ -76,9 +69,9 @@ void PrintResults(const std::map>& threads_result, // an atomic counter is used to give each thread what // it is to write next. The overhead of atomic // synchronization between the threads are not counted in the worst case latency -int main(int argc, char** argv) +int main(int argc, char **argv) { - size_t number_of_threads {0}; + size_t number_of_threads{0}; if (argc == 2) { number_of_threads = atoi(argv[1]); @@ -89,7 +82,6 @@ int main(int argc, char** argv) return 1; } - std::vector threads(number_of_threads); std::map> threads_result; @@ -104,8 +96,8 @@ int main(int argc, char** argv) spdlog::set_async_mode(queue_size); auto logger = spdlog::create("file_logger", "spdlog.log", true); - //force flush on every call to compare with g3log - auto s = (spd::sinks::simple_file_sink_mt*)logger->sinks()[0].get(); + // force flush on every call to compare with g3log + auto s = (spd::sinks::simple_file_sink_mt *)logger->sinks()[0].get(); s->set_force_flush(true); auto start_time_application_total = std::chrono::high_resolution_clock::now(); @@ -119,10 +111,9 @@ int main(int argc, char** argv) } auto stop_time_application_total = std::chrono::high_resolution_clock::now(); - uint64_t total_time_in_us = std::chrono::duration_cast(stop_time_application_total - start_time_application_total).count(); + uint64_t total_time_in_us = + std::chrono::duration_cast(stop_time_application_total - start_time_application_total).count(); PrintResults(threads_result, total_time_in_us); return 0; } - - diff --git a/bench/latency/utils.h b/bench/latency/utils.h index b260f724..6d6ee85d 100644 --- a/bench/latency/utils.h +++ b/bench/latency/utils.h @@ -5,15 +5,13 @@ #pragma once -#include #include #include +#include -namespace utils -{ +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; @@ -22,8 +20,7 @@ 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; @@ -32,4 +29,4 @@ inline std::string format(const double & value) return ss.str(); } -} +} // namespace utils diff --git a/bench/spdlog-async.cpp b/bench/spdlog-async.cpp index f788e4df..0db4f6c6 100644 --- a/bench/spdlog-async.cpp +++ b/bench/spdlog-async.cpp @@ -3,25 +3,25 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#include -#include +#include "spdlog/spdlog.h" #include -#include #include #include -#include "spdlog/spdlog.h" +#include +#include +#include using namespace std; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { using namespace std::chrono; - using clock=steady_clock; + using clock = steady_clock; namespace spd = spdlog; int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = ::atoi(argv[1]); int howmany = 1000000; @@ -29,31 +29,30 @@ int main(int argc, char* argv[]) auto logger = spdlog::create("file_logger", "logs/spd-bench-async.txt", false); logger->set_pattern("[%Y-%b-%d %T.%e]: %v"); - - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; auto start = clock::now(); for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; logger->info("spdlog message #{}: This is some text for your pleasure", counter); } })); } - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; duration delta = clock::now() - start; float deltaf = delta.count(); - auto rate = howmany/deltaf; + auto rate = howmany / deltaf; cout << "Total: " << howmany << std::endl; cout << "Threads: " << thread_count << std::endl; diff --git a/bench/spdlog-bench-mt.cpp b/bench/spdlog-bench-mt.cpp index e28e7bb8..5feb7044 100644 --- a/bench/spdlog-bench-mt.cpp +++ b/bench/spdlog-bench-mt.cpp @@ -3,20 +3,19 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#include -#include +#include "spdlog/spdlog.h" #include #include -#include "spdlog/spdlog.h" - +#include +#include using namespace std; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = std::atoi(argv[1]); int howmany = 1000000; @@ -27,29 +26,26 @@ int main(int argc, char* argv[]) logger->set_pattern("[%Y-%b-%d %T.%e]: %v"); - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; std::vector threads; for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; logger->info("spdlog message #{}: This is some text for your pleasure", counter); } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; - - return 0; } diff --git a/bench/spdlog-bench.cpp b/bench/spdlog-bench.cpp index 4ac95f6a..8d122249 100644 --- a/bench/spdlog-bench.cpp +++ b/bench/spdlog-bench.cpp @@ -5,16 +5,15 @@ #include "spdlog/spdlog.h" - -int main(int, char* []) +int main(int, char *[]) { int howmany = 1000000; namespace spd = spdlog; - ///Create a file rotating logger with 5mb size max and 3 rotated files + /// Create a file rotating logger with 5mb size max and 3 rotated files auto logger = spdlog::create("file_logger", "logs/spd-bench-st.txt", false); logger->set_pattern("[%Y-%b-%d %T.%e]: %v"); - for(int i = 0 ; i < howmany; ++i) + for (int i = 0; i < howmany; ++i) logger->info("spdlog message #{} : This is some text for your pleasure", i); return 0; } diff --git a/bench/spdlog-null-async.cpp b/bench/spdlog-null-async.cpp index 3874371a..df07f834 100644 --- a/bench/spdlog-null-async.cpp +++ b/bench/spdlog-null-async.cpp @@ -6,17 +6,16 @@ // // bench.cpp : spdlog benchmarks // +#include "spdlog/async_logger.h" +#include "spdlog/sinks/null_sink.h" +#include "spdlog/spdlog.h" +#include "utils.h" #include #include // EXIT_FAILURE #include #include #include #include -#include "spdlog/spdlog.h" -#include "spdlog/async_logger.h" -#include "spdlog/sinks/null_sink.h" -#include "utils.h" - using namespace std; using namespace std::chrono; @@ -24,11 +23,9 @@ using namespace spdlog; using namespace spdlog::sinks; using namespace utils; - - size_t bench_as(int howmany, std::shared_ptr log, int thread_count); -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int queue_size = 1048576; @@ -39,14 +36,13 @@ int main(int argc, char* argv[]) try { - if(argc > 1) + if (argc > 1) howmany = atoi(argv[1]); if (argc > 2) - threads = atoi(argv[2]); + threads = atoi(argv[2]); if (argc > 3) queue_size = atoi(argv[3]); - cout << "\n*******************************************************************************\n"; cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " messages " << endl; cout << "*******************************************************************************\n"; @@ -55,16 +51,15 @@ int main(int argc, char* argv[]) size_t total_rate = 0; - for(int i = 0; i < iters; ++i) + for (int i = 0; i < iters; ++i) { - //auto as = spdlog::daily_logger_st("as", "logs/daily_async"); + // auto as = spdlog::daily_logger_st("as", "logs/daily_async"); auto as = spdlog::create("async(null-sink)"); - total_rate+= bench_as(howmany, as, threads); + total_rate += bench_as(howmany, as, threads); spdlog::drop("async(null-sink)"); } std::cout << endl; - std::cout << "Avg rate: " << format(total_rate/iters) << "/sec" < log, int thread_count) { cout << log->name() << "...\t\t" << flush; - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; auto start = system_clock::now(); for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { - for(;;) + threads.push_back(std::thread([&]() { + for (;;) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; log->info("Hello logger: msg number {}", counter); } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; - auto delta = system_clock::now() - start; - auto delta_d = duration_cast> (delta).count(); + auto delta_d = duration_cast>(delta).count(); auto per_sec = size_t(howmany / delta_d); cout << format(per_sec) << "/sec" << endl; return per_sec; diff --git a/bench/utils.h b/bench/utils.h index b260f724..6d6ee85d 100644 --- a/bench/utils.h +++ b/bench/utils.h @@ -5,15 +5,13 @@ #pragma once -#include #include #include +#include -namespace utils -{ +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; @@ -22,8 +20,7 @@ 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; @@ -32,4 +29,4 @@ inline std::string format(const double & value) return ss.str(); } -} +} // namespace utils diff --git a/example/bench.cpp b/example/bench.cpp index e42bec1f..49385e0f 100644 --- a/example/bench.cpp +++ b/example/bench.cpp @@ -6,18 +6,17 @@ // // bench.cpp : spdlog benchmarks // +#include "spdlog/async_logger.h" +#include "spdlog/sinks/file_sinks.h" +#include "spdlog/sinks/null_sink.h" +#include "spdlog/spdlog.h" +#include "utils.h" #include #include // EXIT_FAILURE #include #include #include #include -#include "spdlog/spdlog.h" -#include "spdlog/async_logger.h" -#include "spdlog/sinks/file_sinks.h" -#include "spdlog/sinks/null_sink.h" -#include "utils.h" - using namespace std; using namespace std::chrono; @@ -25,11 +24,10 @@ using namespace spdlog; using namespace spdlog::sinks; using namespace utils; - void bench(int howmany, std::shared_ptr log); void bench_mt(int howmany, std::shared_ptr log, int thread_count); -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int queue_size = 1048576; @@ -41,16 +39,15 @@ int main(int argc, char* argv[]) try { - if(argc > 1) + if (argc > 1) howmany = atoi(argv[1]); if (argc > 2) - threads = atoi(argv[2]); + threads = atoi(argv[2]); if (argc > 3) queue_size = atoi(argv[3]); - cout << "*******************************************************************************\n"; - cout << "Single thread, " << format(howmany) << " iterations" << endl; + cout << "Single thread, " << format(howmany) << " iterations" << endl; cout << "*******************************************************************************\n"; auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files); @@ -60,13 +57,12 @@ int main(int argc, char* argv[]) bench(howmany, spdlog::create("null_st")); cout << "\n*******************************************************************************\n"; - cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl; + cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl; cout << "*******************************************************************************\n"; auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files); bench_mt(howmany, rotating_mt, threads); - auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log"); bench_mt(howmany, daily_mt, threads); bench(howmany, spdlog::create("null_mt")); @@ -75,10 +71,9 @@ int main(int argc, char* argv[]) cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " iterations " << endl; cout << "*******************************************************************************\n"; - spdlog::set_async_mode(queue_size); - for(int i = 0; i < 3; ++i) + for (int i = 0; i < 3; ++i) { auto as = spdlog::daily_logger_st("as", "logs/daily_async.log"); bench_mt(howmany, as, threads); @@ -94,7 +89,6 @@ int main(int argc, char* argv[]) return EXIT_SUCCESS; } - void bench(int howmany, std::shared_ptr log) { cout << log->name() << "...\t\t" << flush; @@ -104,41 +98,37 @@ void bench(int howmany, std::shared_ptr log) log->info("Hello logger: msg number {}", i); } - auto delta = system_clock::now() - start; - auto delta_d = duration_cast> (delta).count(); + auto delta_d = duration_cast>(delta).count(); cout << format(int(howmany / delta_d)) << "/sec" << endl; } - void bench_mt(int howmany, std::shared_ptr log, int thread_count) { cout << log->name() << "...\t\t" << flush; - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; auto start = system_clock::now(); for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { - for(;;) + threads.push_back(std::thread([&]() { + for (;;) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; log->info("Hello logger: msg number {}", counter); } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; - auto delta = system_clock::now() - start; - auto delta_d = duration_cast> (delta).count(); + auto delta_d = duration_cast>(delta).count(); cout << format(int(howmany / delta_d)) << "/sec" << endl; } diff --git a/example/example.cpp b/example/example.cpp index cf747834..937c69f9 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -22,7 +22,7 @@ void user_defined_example(); void err_handler_example(); namespace spd = spdlog; -int main(int, char*[]) +int main(int, char *[]) { try { @@ -31,7 +31,6 @@ int main(int, char*[]) console->info("Welcome to spdlog!"); console->error("Some error message with arg{}..", 1); - // Formatting examples console->warn("Easy padding in numbers like {:08d}", 12); console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); @@ -41,7 +40,6 @@ int main(int, char*[]) spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function"); - // Create basic file logger (not rotated) auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt"); my_logger->info("Some log message"); @@ -49,7 +47,7 @@ int main(int, char*[]) // Create a file rotating logger with 5mb size max and 3 rotated files auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); for (int i = 0; i < 10; ++i) - rotating_logger->info("{} * {} equals {:>10}", i, i, i*i); + rotating_logger->info("{} * {} equals {:>10}", i, i, i * i); // Create a daily logger - a new file is created every day on 2:30am auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); @@ -61,9 +59,8 @@ int main(int, char*[]) spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***"); rotating_logger->info("This is another message with custom format"); - // Runtime log levels - spd::set_level(spd::level::info); //Set global log level to info + spd::set_level(spd::level::info); // Set global log level to info console->debug("This message should not be displayed!"); console->set_level(spd::level::debug); // Set specific logger's log level console->debug("This message should be displayed.."); @@ -73,7 +70,6 @@ int main(int, char*[]) SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23); SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23); - // Asynchronous logging is very fast.. // Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous.. async_example(); @@ -91,16 +87,13 @@ int main(int, char*[]) err_handler_example(); // Apply a function on all registered loggers - spd::apply_all([&](std::shared_ptr l) - { - l->info("End of example."); - }); + spd::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); // Release and close all loggers spdlog::drop_all(); } // Exceptions will only be thrown upon failed logger or sink construction (not during logging) - catch (const spd::spdlog_ex& ex) + catch (const spd::spdlog_ex &ex) { std::cout << "Log init failed: " << ex.what() << std::endl; return 1; @@ -109,14 +102,14 @@ int main(int, char*[]) void async_example() { - size_t q_size = 4096; //queue size must be power of 2 + size_t q_size = 4096; // queue size must be power of 2 spdlog::set_async_mode(q_size); auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt"); for (int i = 0; i < 100; ++i) async_file->info("Async message #{}", i); } -//syslog example (linux/osx/freebsd) +// syslog example (linux/osx/freebsd) void syslog_example() { #ifdef SPDLOG_ENABLE_SYSLOG @@ -140,28 +133,24 @@ void android_example() struct my_type { int i; - template - friend OStream& operator<<(OStream& os, const my_type &c) + template friend OStream &operator<<(OStream &os, const my_type &c) { - return os << "[my_type i="<info("user defined type: {}", my_type { 14 }); + spd::get("console")->info("user defined type: {}", my_type{14}); } // -//custom error handler +// custom error handler // void err_handler_example() { - //can be set globaly or per logger(logger->set_error_handler(..)) - spdlog::set_error_handler([](const std::string& msg) - { - std::cerr << "my err handler: " << msg << std::endl; - }); + // can be set globaly or per logger(logger->set_error_handler(..)) + spdlog::set_error_handler([](const std::string &msg) { std::cerr << "my err handler: " << msg << std::endl; }); spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3); } diff --git a/example/jni/example.cpp b/example/jni/example.cpp deleted file mode 120000 index 6170abce..00000000 --- a/example/jni/example.cpp +++ /dev/null @@ -1 +0,0 @@ -../example.cpp \ No newline at end of file diff --git a/example/jni/example.cpp b/example/jni/example.cpp new file mode 100644 index 00000000..937c69f9 --- /dev/null +++ b/example/jni/example.cpp @@ -0,0 +1,156 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// +// +// spdlog usage example +// +// + +#define SPDLOG_TRACE_ON +#define SPDLOG_DEBUG_ON + +#include "spdlog/spdlog.h" + +#include +#include + +void async_example(); +void syslog_example(); +void android_example(); +void user_defined_example(); +void err_handler_example(); + +namespace spd = spdlog; +int main(int, char *[]) +{ + try + { + // Console logger with color + auto console = spd::stdout_color_mt("console"); + console->info("Welcome to spdlog!"); + console->error("Some error message with arg{}..", 1); + + // Formatting examples + console->warn("Easy padding in numbers like {:08d}", 12); + console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); + console->info("Support for floats {:03.2f}", 1.23456); + console->info("Positional args are {1} {0}..", "too", "supported"); + console->info("{:<30}", "left aligned"); + + spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function"); + + // Create basic file logger (not rotated) + auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt"); + my_logger->info("Some log message"); + + // Create a file rotating logger with 5mb size max and 3 rotated files + auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); + for (int i = 0; i < 10; ++i) + rotating_logger->info("{} * {} equals {:>10}", i, i, i * i); + + // Create a daily logger - a new file is created every day on 2:30am + auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); + // trigger flush if the log severity is error or higher + daily_logger->flush_on(spd::level::err); + daily_logger->info(123.44); + + // Customize msg format for all messages + spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***"); + rotating_logger->info("This is another message with custom format"); + + // Runtime log levels + spd::set_level(spd::level::info); // Set global log level to info + console->debug("This message should not be displayed!"); + console->set_level(spd::level::debug); // Set specific logger's log level + console->debug("This message should be displayed.."); + + // Compile time log levels + // define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON + SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23); + SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23); + + // Asynchronous logging is very fast.. + // Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous.. + async_example(); + + // syslog example. linux/osx only + syslog_example(); + + // android example. compile with NDK + android_example(); + + // Log user-defined types example + user_defined_example(); + + // Change default log error handler + err_handler_example(); + + // Apply a function on all registered loggers + spd::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); + + // Release and close all loggers + spdlog::drop_all(); + } + // Exceptions will only be thrown upon failed logger or sink construction (not during logging) + catch (const spd::spdlog_ex &ex) + { + std::cout << "Log init failed: " << ex.what() << std::endl; + return 1; + } +} + +void async_example() +{ + size_t q_size = 4096; // queue size must be power of 2 + spdlog::set_async_mode(q_size); + auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt"); + for (int i = 0; i < 100; ++i) + async_file->info("Async message #{}", i); +} + +// syslog example (linux/osx/freebsd) +void syslog_example() +{ +#ifdef SPDLOG_ENABLE_SYSLOG + std::string ident = "spdlog-example"; + auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID); + syslog_logger->warn("This is warning that will end up in syslog."); +#endif +} + +// Android example +void android_example() +{ +#if defined(__ANDROID__) + std::string tag = "spdlog-android"; + auto android_logger = spd::android_logger("android", tag); + android_logger->critical("Use \"adb shell logcat\" to view this message."); +#endif +} + +// user defined types logging by implementing operator<< +struct my_type +{ + int i; + template friend OStream &operator<<(OStream &os, const my_type &c) + { + return os << "[my_type i=" << c.i << "]"; + } +}; + +#include "spdlog/fmt/ostr.h" // must be included +void user_defined_example() +{ + spd::get("console")->info("user defined type: {}", my_type{14}); +} + +// +// custom error handler +// +void err_handler_example() +{ + // can be set globaly or per logger(logger->set_error_handler(..)) + spdlog::set_error_handler([](const std::string &msg) { std::cerr << "my err handler: " << msg << std::endl; }); + spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3); +} diff --git a/example/multisink.cpp b/example/multisink.cpp index fe6539b5..d634bc36 100644 --- a/example/multisink.cpp +++ b/example/multisink.cpp @@ -4,7 +4,7 @@ #include namespace spd = spdlog; -int main(int, char*[]) +int main(int, char *[]) { bool enable_debug = true; try @@ -13,24 +13,24 @@ int main(int, char*[]) // This means that the same log_msg is forwarded to multiple sinks; // Each sink can have it's own log level and a message will be logged. std::vector sinks; - sinks.push_back( std::make_shared() ); - sinks.push_back( std::make_shared("./log_regular_file.txt") ); - sinks.push_back( std::make_shared("./log_debug_file.txt") ); + sinks.push_back(std::make_shared()); + sinks.push_back(std::make_shared("./log_regular_file.txt")); + sinks.push_back(std::make_shared("./log_debug_file.txt")); - spdlog::logger console_multisink("multisink", sinks.begin(), sinks.end() ); - console_multisink.set_level( spdlog::level::warn); + spdlog::logger console_multisink("multisink", sinks.begin(), sinks.end()); + console_multisink.set_level(spdlog::level::warn); - sinks[0]->set_level( spdlog::level::trace); // console. Allow everything. Default value - sinks[1]->set_level( spdlog::level::trace); // regular file. Allow everything. Default value - sinks[2]->set_level( spdlog::level::off); // regular file. Ignore everything. + sinks[0]->set_level(spdlog::level::trace); // console. Allow everything. Default value + sinks[1]->set_level(spdlog::level::trace); // regular file. Allow everything. Default value + sinks[2]->set_level(spdlog::level::off); // regular file. Ignore everything. console_multisink.warn("warn: will print only on console and regular file"); - if( enable_debug ) + if (enable_debug) { - console_multisink.set_level( spdlog::level::debug); // level of the logger - sinks[1]->set_level( spdlog::level::debug); // regular file - sinks[2]->set_level( spdlog::level::debug); // debug file + console_multisink.set_level(spdlog::level::debug); // level of the logger + sinks[1]->set_level(spdlog::level::debug); // regular file + sinks[2]->set_level(spdlog::level::debug); // debug file } console_multisink.debug("Debug: you should see this on console and both files"); @@ -38,10 +38,9 @@ int main(int, char*[]) spdlog::drop_all(); } // Exceptions will only be thrown upon failed logger or sink construction (not during logging) - catch (const spd::spdlog_ex& ex) + catch (const spd::spdlog_ex &ex) { std::cout << "Log init failed: " << ex.what() << std::endl; return 1; } } - diff --git a/example/utils.h b/example/utils.h index b260f724..6d6ee85d 100644 --- a/example/utils.h +++ b/example/utils.h @@ -5,15 +5,13 @@ #pragma once -#include #include #include +#include -namespace utils -{ +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; @@ -22,8 +20,7 @@ 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; @@ -32,4 +29,4 @@ inline std::string format(const double & value) return ss.str(); } -} +} // namespace utils diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index be577a3b..78765972 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -20,48 +20,39 @@ #include #include -#include #include +#include -namespace spdlog -{ +namespace spdlog { -namespace details -{ +namespace details { class async_log_helper; } class async_logger SPDLOG_FINAL : public logger { public: - template - async_logger(const std::string& logger_name, - const It& begin, - const It& end, - size_t queue_size, - const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, - const std::function& worker_warmup_cb = nullptr, - const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), - const std::function& worker_teardown_cb = nullptr); + template + async_logger(const std::string &logger_name, const It &begin, const It &end, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); - async_logger(const std::string& logger_name, - sinks_init_list sinks, - size_t queue_size, - const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, - const std::function& worker_warmup_cb = nullptr, - const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), - const std::function& worker_teardown_cb = nullptr); + async_logger(const std::string &logger_name, sinks_init_list sinks, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); - async_logger(const std::string& logger_name, - sink_ptr single_sink, - size_t queue_size, - const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, - const std::function& worker_warmup_cb = nullptr, - const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), - const std::function& worker_teardown_cb = nullptr); + async_logger(const std::string &logger_name, sink_ptr single_sink, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); - //Wait for the queue to be empty, and flush synchronously - //Warning: this can potentially last forever as we wait it to complete + // Wait for the queue to be empty, and flush synchronously + // Warning: this can potentially last forever as we wait it to complete void flush() override; // Error handler @@ -69,13 +60,13 @@ public: log_err_handler error_handler() override; protected: - void _sink_it(details::log_msg& msg) override; + void _sink_it(details::log_msg &msg) override; void _set_formatter(spdlog::formatter_ptr msg_formatter) override; - void _set_pattern(const std::string& pattern, pattern_time_type pattern_time) override; + void _set_pattern(const std::string &pattern, pattern_time_type pattern_time) override; private: std::unique_ptr _async_log_helper; }; -} +} // namespace spdlog #include "details/async_logger_impl.h" diff --git a/include/spdlog/details/async_log_helper.h b/include/spdlog/details/async_log_helper.h index 6faf2f7c..78058975 100644 --- a/include/spdlog/details/async_log_helper.h +++ b/include/spdlog/details/async_log_helper.h @@ -13,11 +13,11 @@ #pragma once #include "../common.h" -#include "../sinks/sink.h" -#include "../details/mpmc_bounded_q.h" #include "../details/log_msg.h" +#include "../details/mpmc_bounded_q.h" #include "../details/os.h" #include "../formatter.h" +#include "../sinks/sink.h" #include #include @@ -28,10 +28,7 @@ #include #include -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { class async_log_helper { @@ -57,24 +54,25 @@ class async_log_helper async_msg() = default; ~async_msg() = default; - explicit async_msg(async_msg_type m_type) : - level(level::info), - thread_id(0), - msg_type(m_type), - msg_id(0) - {} - -async_msg(async_msg&& other) SPDLOG_NOEXCEPT : - logger_name(std::move(other.logger_name)), - level(std::move(other.level)), - time(std::move(other.time)), - thread_id(other.thread_id), - txt(std::move(other.txt)), - msg_type(std::move(other.msg_type)), - msg_id(other.msg_id) - {} - - async_msg& operator=(async_msg&& other) SPDLOG_NOEXCEPT + explicit async_msg(async_msg_type m_type) + : level(level::info) + , thread_id(0) + , msg_type(m_type) + , msg_id(0) + { + } + + async_msg(async_msg &&other) SPDLOG_NOEXCEPT : logger_name(std::move(other.logger_name)), + level(std::move(other.level)), + time(std::move(other.time)), + thread_id(other.thread_id), + txt(std::move(other.txt)), + msg_type(std::move(other.msg_type)), + msg_id(other.msg_id) + { + } + + async_msg &operator=(async_msg &&other) SPDLOG_NOEXCEPT { logger_name = std::move(other.logger_name); level = other.level; @@ -87,17 +85,17 @@ async_msg(async_msg&& other) SPDLOG_NOEXCEPT : } // never copy or assign. should only be moved.. - async_msg(const async_msg&) = delete; - async_msg& operator=(const async_msg& other) = delete; + async_msg(const async_msg &) = delete; + async_msg &operator=(const async_msg &other) = delete; // construct from log_msg - explicit async_msg(const details::log_msg& m): - level(m.level), - time(m.time), - thread_id(m.thread_id), - txt(m.raw.data(), m.raw.size()), - msg_type(async_msg_type::log), - msg_id(m.msg_id) + explicit async_msg(const details::log_msg &m) + : level(m.level) + , time(m.time) + , thread_id(m.thread_id) + , txt(m.raw.data(), m.raw.size()) + , msg_type(async_msg_type::log) + , msg_id(m.msg_id) { #ifndef SPDLOG_NO_NAME logger_name = *m.logger_name; @@ -122,22 +120,18 @@ public: using clock = std::chrono::steady_clock; - async_log_helper(formatter_ptr formatter, - std::vector sinks, - size_t queue_size, - const log_err_handler err_handler, - const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, - std::function worker_warmup_cb = nullptr, - const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), - std::function worker_teardown_cb = nullptr); + async_log_helper(formatter_ptr formatter, std::vector sinks, size_t queue_size, const log_err_handler err_handler, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, std::function worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + std::function worker_teardown_cb = nullptr); - void log(const details::log_msg& msg); + void log(const details::log_msg &msg); // stop logging and join the back thread ~async_log_helper(); - async_log_helper(const async_log_helper&) = delete; - async_log_helper& operator=(const async_log_helper&) = delete; + async_log_helper(const async_log_helper &) = delete; + async_log_helper &operator=(const async_log_helper &) = delete; void set_formatter(formatter_ptr msg_formatter); @@ -173,49 +167,41 @@ private: // worker thread std::thread _worker_thread; - void push_msg(async_msg&& new_msg); + void push_msg(async_msg &&new_msg); // worker thread main loop void worker_loop(); // pop next message from the queue and process it. will set the last_pop to the pop time // return false if termination of the queue is required - bool process_next_msg(log_clock::time_point& last_pop, log_clock::time_point& last_flush); + bool process_next_msg(log_clock::time_point &last_pop, log_clock::time_point &last_flush); - void handle_flush_interval(log_clock::time_point& now, log_clock::time_point& last_flush); + void handle_flush_interval(log_clock::time_point &now, log_clock::time_point &last_flush); // sleep,yield or return immediately using the time passed since last message as a hint - static void sleep_or_yield(const spdlog::log_clock::time_point& now, const log_clock::time_point& last_op_time); + static void sleep_or_yield(const spdlog::log_clock::time_point &now, const log_clock::time_point &last_op_time); // wait until the queue is empty void wait_empty_q(); - }; -} -} +}} // namespace spdlog::details /////////////////////////////////////////////////////////////////////////////// // async_sink class implementation /////////////////////////////////////////////////////////////////////////////// -inline spdlog::details::async_log_helper::async_log_helper( - formatter_ptr formatter, - std::vector sinks, - size_t queue_size, - log_err_handler err_handler, - const async_overflow_policy overflow_policy, - std::function worker_warmup_cb, - const std::chrono::milliseconds& flush_interval_ms, - std::function worker_teardown_cb): - _formatter(std::move(formatter)), - _sinks(std::move(sinks)), - _q(queue_size), - _err_handler(std::move(err_handler)), - _flush_requested(false), - _terminate_requested(false), - _overflow_policy(overflow_policy), - _worker_warmup_cb(std::move(worker_warmup_cb)), - _flush_interval_ms(flush_interval_ms), - _worker_teardown_cb(std::move(worker_teardown_cb)) +inline spdlog::details::async_log_helper::async_log_helper(formatter_ptr formatter, std::vector sinks, size_t queue_size, + log_err_handler err_handler, const async_overflow_policy overflow_policy, std::function worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, std::function worker_teardown_cb) + : _formatter(std::move(formatter)) + , _sinks(std::move(sinks)) + , _q(queue_size) + , _err_handler(std::move(err_handler)) + , _flush_requested(false) + , _terminate_requested(false) + , _overflow_policy(overflow_policy) + , _worker_warmup_cb(std::move(worker_warmup_cb)) + , _flush_interval_ms(flush_interval_ms) + , _worker_teardown_cb(std::move(worker_teardown_cb)) { _worker_thread = std::thread(&async_log_helper::worker_loop, this); } @@ -234,14 +220,13 @@ inline spdlog::details::async_log_helper::~async_log_helper() } } - -//Try to push and block until succeeded (if the policy is not to discard when the queue is full) -inline void spdlog::details::async_log_helper::log(const details::log_msg& msg) +// Try to push and block until succeeded (if the policy is not to discard when the queue is full) +inline void spdlog::details::async_log_helper::log(const details::log_msg &msg) { push_msg(async_msg(msg)); } -inline void spdlog::details::async_log_helper::push_msg(details::async_log_helper::async_msg&& new_msg) +inline void spdlog::details::async_log_helper::push_msg(details::async_log_helper::async_msg &&new_msg) { if (!_q.enqueue(std::move(new_msg)) && _overflow_policy != async_overflow_policy::discard_log_msg) { @@ -251,8 +236,7 @@ inline void spdlog::details::async_log_helper::push_msg(details::async_log_helpe { now = details::os::now(); sleep_or_yield(now, last_op_time); - } - while (!_q.enqueue(std::move(new_msg))); + } while (!_q.enqueue(std::move(new_msg))); } } @@ -261,12 +245,13 @@ inline void spdlog::details::async_log_helper::flush(bool wait_for_q) { push_msg(async_msg(async_msg_type::flush)); if (wait_for_q) - wait_empty_q(); //return when queue is empty + wait_empty_q(); // return when queue is empty } inline void spdlog::details::async_log_helper::worker_loop() { - if (_worker_warmup_cb) _worker_warmup_cb(); + if (_worker_warmup_cb) + _worker_warmup_cb(); auto last_pop = details::os::now(); auto last_flush = last_pop; auto active = true; @@ -280,19 +265,18 @@ inline void spdlog::details::async_log_helper::worker_loop() { _err_handler(ex.what()); } - catch(...) + catch (...) { _err_handler("Unknown exeption in async logger worker loop."); } } - if (_worker_teardown_cb) _worker_teardown_cb(); - - + if (_worker_teardown_cb) + _worker_teardown_cb(); } // process next message in the queue // return true if this thread should still be active (while no terminate msg was received) -inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_point& last_pop, log_clock::time_point& last_flush) +inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_point &last_pop, log_clock::time_point &last_flush) { async_msg incoming_async_msg; @@ -334,9 +318,10 @@ inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_ } // flush all sinks if _flush_interval_ms has expired -inline void spdlog::details::async_log_helper::handle_flush_interval(log_clock::time_point& now, log_clock::time_point& last_flush) +inline void spdlog::details::async_log_helper::handle_flush_interval(log_clock::time_point &now, log_clock::time_point &last_flush) { - auto should_flush = _flush_requested || (_flush_interval_ms != std::chrono::milliseconds::zero() && now - last_flush >= _flush_interval_ms); + auto should_flush = + _flush_requested || (_flush_interval_ms != std::chrono::milliseconds::zero() && now - last_flush >= _flush_interval_ms); if (should_flush) { for (auto &s : _sinks) @@ -352,10 +337,11 @@ inline void spdlog::details::async_log_helper::set_formatter(formatter_ptr msg_f } // spin, yield or sleep. use the time passed since last message as a hint -inline void spdlog::details::async_log_helper::sleep_or_yield(const spdlog::log_clock::time_point& now, const spdlog::log_clock::time_point& last_op_time) +inline void spdlog::details::async_log_helper::sleep_or_yield( + const spdlog::log_clock::time_point &now, const spdlog::log_clock::time_point &last_op_time) { - using std::chrono::milliseconds; using std::chrono::microseconds; + using std::chrono::milliseconds; auto time_since_op = now - last_op_time; diff --git a/include/spdlog/details/async_logger_impl.h b/include/spdlog/details/async_logger_impl.h index 72bd4f98..ca458740 100644 --- a/include/spdlog/details/async_logger_impl.h +++ b/include/spdlog/details/async_logger_impl.h @@ -8,49 +8,39 @@ // Async Logger implementation // Use an async_sink (queue per logger) to perform the logging in a worker thread -#include "../details/async_log_helper.h" #include "../async_logger.h" +#include "../details/async_log_helper.h" -#include -#include #include +#include #include +#include -template -inline spdlog::async_logger::async_logger(const std::string& logger_name, - const It& begin, - const It& end, - size_t queue_size, - const async_overflow_policy overflow_policy, - const std::function& worker_warmup_cb, - const std::chrono::milliseconds& flush_interval_ms, - const std::function& worker_teardown_cb) : - logger(logger_name, begin, end), - _async_log_helper(new details::async_log_helper(_formatter, _sinks, queue_size, _err_handler, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb)) +template +inline spdlog::async_logger::async_logger(const std::string &logger_name, const It &begin, const It &end, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) + : logger(logger_name, begin, end) + , _async_log_helper(new details::async_log_helper( + _formatter, _sinks, queue_size, _err_handler, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb)) { } -inline spdlog::async_logger::async_logger(const std::string& logger_name, - sinks_init_list sinks_list, - size_t queue_size, - const async_overflow_policy overflow_policy, - const std::function& worker_warmup_cb, - const std::chrono::milliseconds& flush_interval_ms, - const std::function& worker_teardown_cb) : - async_logger(logger_name, sinks_list.begin(), sinks_list.end(), queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) {} - -inline spdlog::async_logger::async_logger(const std::string& logger_name, - sink_ptr single_sink, - size_t queue_size, - const async_overflow_policy overflow_policy, - const std::function& worker_warmup_cb, - const std::chrono::milliseconds& flush_interval_ms, - const std::function& worker_teardown_cb) : - async_logger(logger_name, +inline spdlog::async_logger::async_logger(const std::string &logger_name, sinks_init_list sinks_list, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) + : async_logger(logger_name, sinks_list.begin(), sinks_list.end(), queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, + worker_teardown_cb) { - std::move(single_sink) -}, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) {} +} +inline spdlog::async_logger::async_logger(const std::string &logger_name, sink_ptr single_sink, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) + : async_logger( + logger_name, {std::move(single_sink)}, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) +{ +} inline void spdlog::async_logger::flush() { @@ -62,28 +52,25 @@ inline void spdlog::async_logger::set_error_handler(spdlog::log_err_handler err_ { _err_handler = err_handler; _async_log_helper->set_error_handler(err_handler); - } inline spdlog::log_err_handler spdlog::async_logger::error_handler() { return _err_handler; } - inline void spdlog::async_logger::_set_formatter(spdlog::formatter_ptr msg_formatter) { _formatter = msg_formatter; _async_log_helper->set_formatter(_formatter); } -inline void spdlog::async_logger::_set_pattern(const std::string& pattern, pattern_time_type pattern_time) +inline void spdlog::async_logger::_set_pattern(const std::string &pattern, pattern_time_type pattern_time) { _formatter = std::make_shared(pattern, pattern_time); _async_log_helper->set_formatter(_formatter); } - -inline void spdlog::async_logger::_sink_it(details::log_msg& msg) +inline void spdlog::async_logger::_sink_it(details::log_msg &msg) { try { @@ -98,10 +85,9 @@ inline void spdlog::async_logger::_sink_it(details::log_msg& msg) { _err_handler(ex.what()); } - catch(...) + catch (...) { _err_handler("Unknown exception in logger " + _name); throw; } - } diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index d7ccf59b..0d24a91b 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -9,20 +9,17 @@ // When failing to open a file, retry several times(5) with small delay between the tries(10 ms) // Throw spdlog_ex exception on errors -#include "../details/os.h" #include "../details/log_msg.h" +#include "../details/os.h" +#include #include #include #include #include #include -#include -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { class file_helper { @@ -33,16 +30,15 @@ public: explicit file_helper() = default; - file_helper(const file_helper&) = delete; - file_helper& operator=(const file_helper&) = delete; + file_helper(const file_helper &) = delete; + file_helper &operator=(const file_helper &) = delete; ~file_helper() { close(); } - - void open(const filename_t& fname, bool truncate = false) + void open(const filename_t &fname, bool truncate = false) { close(); auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab"); @@ -63,7 +59,6 @@ public: if (_filename.empty()) throw spdlog_ex("Failed re opening file - was not opened before"); open(_filename, truncate); - } void flush() @@ -80,7 +75,7 @@ public: } } - void write(const log_msg& msg) + void write(const log_msg &msg) { size_t msg_size = msg.formatted.size(); auto data = msg.formatted.data(); @@ -97,12 +92,12 @@ public: return os::filesize(_fd); } - const filename_t& filename() const + const filename_t &filename() const { return _filename; } - static bool file_exists(const filename_t& fname) + static bool file_exists(const filename_t &fname) { return os::file_exists(fname); } @@ -120,7 +115,7 @@ public: // ".mylog" => (".mylog". "") // "my_folder/.mylog" => ("my_folder/.mylog", "") // "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt") - static std::tuple split_by_extenstion(const spdlog::filename_t& fname) + static std::tuple split_by_extenstion(const spdlog::filename_t &fname) { auto ext_index = fname.rfind('.'); @@ -138,8 +133,7 @@ public: } private: - FILE* _fd{ nullptr }; + FILE *_fd{nullptr}; filename_t _filename; }; -} -} +}} // namespace spdlog::details diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 8b441cab..a1e8b2ee 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -11,16 +11,13 @@ #include #include -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { struct log_msg { log_msg() = default; - log_msg(const std::string *loggers_name, level::level_enum lvl) : - logger_name(loggers_name), - level(lvl) + log_msg(const std::string *loggers_name, level::level_enum lvl) + : logger_name(loggers_name) + , level(lvl) { #ifndef SPDLOG_NO_DATETIME time = os::now(); @@ -31,18 +28,16 @@ struct log_msg #endif } - log_msg(const log_msg& other) = delete; - log_msg& operator=(log_msg&& other) = delete; - log_msg(log_msg&& other) = delete; - + log_msg(const log_msg &other) = delete; + log_msg &operator=(log_msg &&other) = delete; + log_msg(log_msg &&other) = delete; - const std::string *logger_name{ nullptr }; + const std::string *logger_name{nullptr}; level::level_enum level; log_clock::time_point time; size_t thread_id; fmt::MemoryWriter raw; fmt::MemoryWriter formatted; - size_t msg_id{ 0 }; + size_t msg_id{0}; }; -} -} +}} // namespace spdlog::details diff --git a/include/spdlog/details/logger_impl.h b/include/spdlog/details/logger_impl.h index 11cbc7e4..3b64543d 100644 --- a/include/spdlog/details/logger_impl.h +++ b/include/spdlog/details/logger_impl.h @@ -13,54 +13,47 @@ // create logger with given name, sinks and the default pattern formatter // all other ctors will call this one -template -inline spdlog::logger::logger(std::string logger_name, const It& begin, const It& end): - _name(std::move(logger_name)), - _sinks(begin, end), - _formatter(std::make_shared("%+")), - _level(level::info), - _flush_level(level::off), - _last_err_time(0), - _msg_counter(1) // message counter will start from 1. 0-message id will be reserved for controll messages -{ - _err_handler = [this](const std::string &msg) - { - this->_default_err_handler(msg); - }; +template +inline spdlog::logger::logger(std::string logger_name, const It &begin, const It &end) + : _name(std::move(logger_name)) + , _sinks(begin, end) + , _formatter(std::make_shared("%+")) + , _level(level::info) + , _flush_level(level::off) + , _last_err_time(0) + , _msg_counter(1) // message counter will start from 1. 0-message id will be reserved for controll messages +{ + _err_handler = [this](const std::string &msg) { this->_default_err_handler(msg); }; } // ctor with sinks as init list -inline spdlog::logger::logger(const std::string& logger_name, sinks_init_list sinks_list): - logger(logger_name, sinks_list.begin(), sinks_list.end()) -{} - +inline spdlog::logger::logger(const std::string &logger_name, sinks_init_list sinks_list) + : logger(logger_name, sinks_list.begin(), sinks_list.end()) +{ +} // ctor with single sink -inline spdlog::logger::logger(const std::string& logger_name, spdlog::sink_ptr single_sink): - logger(logger_name, +inline spdlog::logger::logger(const std::string &logger_name, spdlog::sink_ptr single_sink) + : logger(logger_name, {std::move(single_sink)}) { - std::move(single_sink) -}) -{} - +} inline spdlog::logger::~logger() = default; - inline void spdlog::logger::set_formatter(spdlog::formatter_ptr msg_formatter) { _set_formatter(std::move(msg_formatter)); } -inline void spdlog::logger::set_pattern(const std::string& pattern, pattern_time_type pattern_time) +inline void spdlog::logger::set_pattern(const std::string &pattern, pattern_time_type pattern_time) { _set_pattern(pattern, pattern_time); } -template -inline void spdlog::logger::log(level::level_enum lvl, const char* fmt, const Args&... args) +template inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) { - if (!should_log(lvl)) return; + if (!should_log(lvl)) + return; try { @@ -77,17 +70,17 @@ inline void spdlog::logger::log(level::level_enum lvl, const char* fmt, const Ar { _err_handler(ex.what()); } - catch(...) + catch (...) { _err_handler("Unknown exception in logger " + _name); throw; } } -template -inline void spdlog::logger::log(level::level_enum lvl, const char* msg) +template inline void spdlog::logger::log(level::level_enum lvl, const char *msg) { - if (!should_log(lvl)) return; + if (!should_log(lvl)) + return; try { details::log_msg log_msg(&_name, lvl); @@ -105,10 +98,10 @@ inline void spdlog::logger::log(level::level_enum lvl, const char* msg) } } -template -inline void spdlog::logger::log(level::level_enum lvl, const T& msg) +template inline void spdlog::logger::log(level::level_enum lvl, const T &msg) { - if (!should_log(lvl)) return; + if (!should_log(lvl)) + return; try { details::log_msg log_msg(&_name, lvl); @@ -126,98 +119,78 @@ inline void spdlog::logger::log(level::level_enum lvl, const T& msg) } } - -template -inline void spdlog::logger::trace(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::trace(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::trace, fmt, arg1, args...); } -template -inline void spdlog::logger::debug(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::debug(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::debug, fmt, arg1, args...); } -template -inline void spdlog::logger::info(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::info(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::info, fmt, arg1, args...); } -template -inline void spdlog::logger::warn(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::warn(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::warn, fmt, arg1, args...); } -template -inline void spdlog::logger::error(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::error(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::err, fmt, arg1, args...); } -template -inline void spdlog::logger::critical(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::critical(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::critical, fmt, arg1, args...); } - -template -inline void spdlog::logger::trace(const T& msg) +template inline void spdlog::logger::trace(const T &msg) { log(level::trace, msg); } -template -inline void spdlog::logger::debug(const T& msg) +template inline void spdlog::logger::debug(const T &msg) { log(level::debug, msg); } - -template -inline void spdlog::logger::info(const T& msg) +template inline void spdlog::logger::info(const T &msg) { log(level::info, msg); } - -template -inline void spdlog::logger::warn(const T& msg) +template inline void spdlog::logger::warn(const T &msg) { log(level::warn, msg); } -template -inline void spdlog::logger::error(const T& msg) +template inline void spdlog::logger::error(const T &msg) { log(level::err, msg); } -template -inline void spdlog::logger::critical(const T& msg) +template inline void spdlog::logger::critical(const T &msg) { log(level::critical, msg); } - - #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT #include #include -template -inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* msg) +template inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *msg) { - std::wstring_convert > conv; + std::wstring_convert> conv; log(lvl, conv.to_bytes(msg)); } -template -inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) { fmt::WMemoryWriter wWriter; @@ -225,51 +198,42 @@ inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* fmt, const log(lvl, wWriter.c_str()); } -template -inline void spdlog::logger::trace(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args) { log(level::trace, fmt, args...); } -template -inline void spdlog::logger::debug(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::debug(const wchar_t *fmt, const Args &... args) { log(level::debug, fmt, args...); } -template -inline void spdlog::logger::info(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::info(const wchar_t *fmt, const Args &... args) { log(level::info, fmt, args...); } - -template -inline void spdlog::logger::warn(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::warn(const wchar_t *fmt, const Args &... args) { log(level::warn, fmt, args...); } -template -inline void spdlog::logger::error(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::error(const wchar_t *fmt, const Args &... args) { log(level::err, fmt, args...); } -template -inline void spdlog::logger::critical(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::critical(const wchar_t *fmt, const Args &... args) { log(level::critical, fmt, args...); } #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT - - // // name and level // -inline const std::string& spdlog::logger::name() const +inline const std::string &spdlog::logger::name() const { return _name; } @@ -307,7 +271,7 @@ inline bool spdlog::logger::should_log(spdlog::level::level_enum msg_level) cons // // protected virtual called at end of each user log call (if enabled) by the line_logger // -inline void spdlog::logger::_sink_it(details::log_msg& msg) +inline void spdlog::logger::_sink_it(details::log_msg &msg) { #if defined(SPDLOG_ENABLE_MESSAGE_COUNTER) _incr_msg_counter(msg); @@ -315,17 +279,17 @@ inline void spdlog::logger::_sink_it(details::log_msg& msg) _formatter->format(msg); for (auto &sink : _sinks) { - if( sink->should_log( msg.level)) + if (sink->should_log(msg.level)) { sink->log(msg); } } - if(_should_flush_on(msg)) + if (_should_flush_on(msg)) flush(); } -inline void spdlog::logger::_set_pattern(const std::string& pattern, pattern_time_type pattern_time) +inline void spdlog::logger::_set_pattern(const std::string &pattern, pattern_time_type pattern_time) { _formatter = std::make_shared(pattern, pattern_time); } @@ -337,7 +301,7 @@ inline void spdlog::logger::_set_formatter(formatter_ptr msg_formatter) inline void spdlog::logger::flush() { - for (auto& sink : _sinks) + for (auto &sink : _sinks) sink->flush(); } @@ -366,8 +330,7 @@ inline void spdlog::logger::_incr_msg_counter(details::log_msg &msg) msg.msg_id = _msg_counter.fetch_add(1, std::memory_order_relaxed); } -inline const std::vector& spdlog::logger::sinks() const +inline const std::vector &spdlog::logger::sinks() const { return _sinks; } - diff --git a/include/spdlog/details/mpmc_bounded_q.h b/include/spdlog/details/mpmc_bounded_q.h index 6187f3b9..567f292f 100644 --- a/include/spdlog/details/mpmc_bounded_q.h +++ b/include/spdlog/details/mpmc_bounded_q.h @@ -48,23 +48,19 @@ Distributed under the MIT License (http://opensource.org/licenses/MIT) #include #include -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { -template -class mpmc_bounded_queue +template class mpmc_bounded_queue { public: using item_type = T; explicit mpmc_bounded_queue(size_t buffer_size) - :max_size_(buffer_size), - buffer_(new cell_t[buffer_size]), - buffer_mask_(buffer_size - 1) + : max_size_(buffer_size) + , buffer_(new cell_t[buffer_size]) + , buffer_mask_(buffer_size - 1) { - //queue size must be power of two + // queue size must be power of two if (!((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0))) throw spdlog_ex("async logger queue size must be power of two"); @@ -79,12 +75,12 @@ public: delete[] buffer_; } - mpmc_bounded_queue(mpmc_bounded_queue const&) = delete; - void operator=(mpmc_bounded_queue const&) = delete; + mpmc_bounded_queue(mpmc_bounded_queue const &) = delete; + void operator=(mpmc_bounded_queue const &) = delete; - bool enqueue(T&& data) + bool enqueue(T &&data) { - cell_t* cell; + cell_t *cell; size_t pos = enqueue_pos_.load(std::memory_order_relaxed); for (;;) { @@ -110,15 +106,14 @@ public: return true; } - bool dequeue(T& data) + bool dequeue(T &data) { - cell_t* cell; + cell_t *cell; size_t pos = dequeue_pos_.load(std::memory_order_relaxed); for (;;) { cell = &buffer_[pos & buffer_mask_]; - size_t seq = - cell->sequence_.load(std::memory_order_acquire); + size_t seq = cell->sequence_.load(std::memory_order_acquire); intptr_t dif = static_cast(seq) - static_cast(pos + 1); if (dif == 0) { @@ -144,32 +139,30 @@ public: front = enqueue_pos_.load(std::memory_order_acquire); back = dequeue_pos_.load(std::memory_order_acquire); front1 = enqueue_pos_.load(std::memory_order_relaxed); - } - while (front != front1); + } while (front != front1); return back == front; } private: struct cell_t { - std::atomic sequence_; - T data_; + std::atomic sequence_; + T data_; }; size_t const max_size_; - static size_t const cacheline_size = 64; + static size_t const cacheline_size = 64; using cacheline_pad_t = char[cacheline_size]; - cacheline_pad_t pad0_; - cell_t* const buffer_; - size_t const buffer_mask_; - cacheline_pad_t pad1_; - std::atomic enqueue_pos_; - cacheline_pad_t pad2_; - std::atomic dequeue_pos_; - cacheline_pad_t pad3_; + cacheline_pad_t pad0_; + cell_t *const buffer_; + size_t const buffer_mask_; + cacheline_pad_t pad1_; + std::atomic enqueue_pos_; + cacheline_pad_t pad2_; + std::atomic dequeue_pos_; + cacheline_pad_t pad3_; }; -} // ns details -} // ns spdlog +}} // namespace spdlog::details diff --git a/include/spdlog/details/null_mutex.h b/include/spdlog/details/null_mutex.h index 82b0ed84..5f4ce46a 100644 --- a/include/spdlog/details/null_mutex.h +++ b/include/spdlog/details/null_mutex.h @@ -8,10 +8,7 @@ #include // null, no cost dummy "mutex" and dummy "atomic" int -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { struct null_mutex { void lock() {} @@ -27,8 +24,10 @@ struct null_atomic_int int value; null_atomic_int() = default; - explicit null_atomic_int(int val) : value(val) - {} + explicit null_atomic_int(int val) + : value(val) + { + } int load(std::memory_order) const { @@ -41,5 +40,4 @@ struct null_atomic_int } }; -} -} +}} // namespace spdlog::details diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 4de7b9f8..271348da 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -6,30 +6,30 @@ #include "../common.h" +#include +#include #include +#include +#include #include #include #include -#include -#include -#include -#include -#include #include #include +#include #ifdef _WIN32 #ifndef NOMINMAX -#define NOMINMAX //prevent windows redefining min/max +#define NOMINMAX // prevent windows redefining min/max #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif -#include +#include // _get_osfhandle and _isatty support #include // _get_pid support -#include // _get_osfhandle and _isatty support +#include #ifdef __MINGW32__ #include @@ -37,8 +37,8 @@ #else // unix -#include #include +#include #ifdef __linux__ #include //Use gettid() syscall under linux to get thread id @@ -47,19 +47,13 @@ #include //Use thr_self() syscall under FreeBSD to get thread id #endif -#endif //unix +#endif // unix -#ifndef __has_feature // Clang - feature checking macros. -#define __has_feature(x) 0 // Compatibility with non-clang compilers. +#ifndef __has_feature // Clang - feature checking macros. +#define __has_feature(x) 0 // Compatibility with non-clang compilers. #endif - -namespace spdlog -{ -namespace details -{ -namespace os -{ +namespace spdlog { namespace details { namespace os { inline spdlog::log_clock::time_point now() { @@ -68,14 +62,11 @@ inline spdlog::log_clock::time_point now() 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(); #endif - } inline std::tm localtime(const std::time_t &time_tt) { @@ -114,24 +105,19 @@ inline std::tm gmtime() std::time_t now_t = time(nullptr); return gmtime(now_t); } -inline bool operator==(const std::tm& tm1, const std::tm& tm2) +inline bool operator==(const std::tm &tm1, const std::tm &tm2) { - return (tm1.tm_sec == tm2.tm_sec && - tm1.tm_min == tm2.tm_min && - tm1.tm_hour == tm2.tm_hour && - tm1.tm_mday == tm2.tm_mday && - tm1.tm_mon == tm2.tm_mon && - tm1.tm_year == tm2.tm_year && - tm1.tm_isdst == tm2.tm_isdst); + return (tm1.tm_sec == tm2.tm_sec && tm1.tm_min == tm2.tm_min && tm1.tm_hour == tm2.tm_hour && tm1.tm_mday == tm2.tm_mday && + tm1.tm_mon == tm2.tm_mon && tm1.tm_year == tm2.tm_year && tm1.tm_isdst == tm2.tm_isdst); } -inline bool operator!=(const std::tm& tm1, const std::tm& tm2) +inline bool operator!=(const std::tm &tm1, const std::tm &tm2) { return !(tm1 == tm2); } // eol definition -#if !defined (SPDLOG_EOL) +#if !defined(SPDLOG_EOL) #ifdef _WIN32 #define SPDLOG_EOL "\r\n" #else @@ -139,9 +125,7 @@ inline bool operator!=(const std::tm& tm1, const std::tm& tm2) #endif #endif -SPDLOG_CONSTEXPR static const char* default_eol = SPDLOG_EOL; - - +SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL; // folder separator #ifdef _WIN32 @@ -150,7 +134,6 @@ SPDLOG_CONSTEXPR static const char folder_sep = '\\'; SPDLOG_CONSTEXPR static const char folder_sep = '/'; #endif - inline void prevent_child_fd(FILE *f) { @@ -167,9 +150,8 @@ inline void prevent_child_fd(FILE *f) #endif } - -//fopen_s on non windows for writing -inline bool fopen_s(FILE** fp, const filename_t& filename, const filename_t& mode) +// fopen_s on non windows for writing +inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode) { #ifdef _WIN32 #ifdef SPDLOG_WCHAR_FILENAMES @@ -177,7 +159,7 @@ inline bool fopen_s(FILE** fp, const filename_t& filename, const filename_t& mod #else *fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYWR); #endif -#else //unix +#else // unix *fp = fopen((filename.c_str()), mode.c_str()); #endif @@ -188,7 +170,6 @@ inline bool fopen_s(FILE** fp, const filename_t& filename, const filename_t& mod return *fp == nullptr; } - inline int remove(const filename_t &filename) { #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) @@ -198,7 +179,7 @@ inline int remove(const filename_t &filename) #endif } -inline int rename(const filename_t& filename1, const filename_t& filename2) +inline int rename(const filename_t &filename1, const filename_t &filename2) { #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) return _wrename(filename1.c_str(), filename2.c_str()); @@ -207,9 +188,8 @@ inline int rename(const filename_t& filename1, const filename_t& filename2) #endif } - -//Return if file exists -inline bool file_exists(const filename_t& filename) +// Return if file exists +inline bool file_exists(const filename_t &filename) { #ifdef _WIN32 #ifdef SPDLOG_WCHAR_FILENAMES @@ -218,28 +198,25 @@ inline bool file_exists(const filename_t& filename) auto attribs = GetFileAttributesA(filename.c_str()); #endif return (attribs != INVALID_FILE_ATTRIBUTES && !(attribs & FILE_ATTRIBUTE_DIRECTORY)); -#else //common linux/unix all have the stat system call +#else // common linux/unix all have the stat system call struct stat buffer; return (stat(filename.c_str(), &buffer) == 0); #endif } - - - -//Return file size according to open FILE* object +// Return file size according to open FILE* object inline size_t filesize(FILE *f) { if (f == nullptr) throw spdlog_ex("Failed getting file size. fd is null"); -#if defined ( _WIN32) && !defined(__CYGWIN__) +#if defined(_WIN32) && !defined(__CYGWIN__) int fd = _fileno(f); -#if _WIN64 //64 bits +#if _WIN64 // 64 bits struct _stat64 st; if (_fstat64(fd, &st) == 0) return st.st_size; -#else //windows 32 bits +#else // windows 32 bits long ret = _filelength(fd); if (ret >= 0) return static_cast(ret); @@ -247,9 +224,9 @@ inline size_t filesize(FILE *f) #else // unix int fd = fileno(f); - //64 bits(but not in osx or cygwin, where fstat64 is deprecated) + // 64 bits(but not in osx or cygwin, where fstat64 is deprecated) #if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__) - struct stat64 st ; + struct stat64 st; if (fstat64(fd, &st) == 0) return static_cast(st.st_size); #else // unix 32 bits or cygwin @@ -261,11 +238,8 @@ inline size_t filesize(FILE *f) throw spdlog_ex("Failed getting file size from fd", errno); } - - - -//Return utc offset in minutes or throw spdlog_ex on failure -inline int utc_minutes_offset(const std::tm& tm = details::os::localtime()) +// Return utc offset in minutes or throw spdlog_ex on failure +inline int utc_minutes_offset(const std::tm &tm = details::os::localtime()) { #ifdef _WIN32 @@ -291,23 +265,22 @@ inline int utc_minutes_offset(const std::tm& tm = details::os::localtime()) // 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris struct helper { - static long int calculate_gmt_offset(const std::tm & localtm = details::os::localtime(), const std::tm & gmtm = details::os::gmtime()) + static long int calculate_gmt_offset(const std::tm &localtm = details::os::localtime(), const std::tm &gmtm = details::os::gmtime()) { int local_year = localtm.tm_year + (1900 - 1); int gmt_year = gmtm.tm_year + (1900 - 1); long int days = ( - // difference in day of year - localtm.tm_yday - gmtm.tm_yday + // difference in day of year + localtm.tm_yday - + gmtm.tm_yday - // + intervening leap days - + ((local_year >> 2) - (gmt_year >> 2)) - - (local_year / 100 - gmt_year / 100) - + ((local_year / 100 >> 2) - (gmt_year / 100 >> 2)) + // + intervening leap days + + ((local_year >> 2) - (gmt_year >> 2)) - (local_year / 100 - gmt_year / 100) + + ((local_year / 100 >> 2) - (gmt_year / 100 >> 2)) - // + difference in years * 365 */ - + (long int)(local_year - gmt_year) * 365 - ); + // + difference in years * 365 */ + + (long int)(local_year - gmt_year) * 365); long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour); long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min); @@ -326,16 +299,16 @@ inline int utc_minutes_offset(const std::tm& tm = details::os::localtime()) #endif } -//Return current thread id as size_t -//It exists because the std::this_thread::get_id() is much slower(especially under VS 2013) +// Return current thread id as size_t +// It exists because the std::this_thread::get_id() is much slower(especially under VS 2013) inline size_t _thread_id() { #ifdef _WIN32 return static_cast(::GetCurrentThreadId()); #elif __linux__ -# if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21) -# define SYS_gettid __NR_gettid -# endif +#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21) +#define SYS_gettid __NR_gettid +#endif return static_cast(syscall(SYS_gettid)); #elif __FreeBSD__ long tid; @@ -345,25 +318,23 @@ inline size_t _thread_id() uint64_t tid; pthread_threadid_np(nullptr, &tid); return static_cast(tid); -#else //Default to standard C++11 (other Unix) +#else // Default to standard C++11 (other Unix) return static_cast(std::hash()(std::this_thread::get_id())); #endif } -//Return current thread id as size_t (from thread local storage) +// Return current thread id as size_t (from thread local storage) inline size_t thread_id() { -#if defined(SPDLOG_DISABLE_TID_CACHING) || (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt ) || (defined(__clang__) && !__has_feature(cxx_thread_local)) +#if defined(SPDLOG_DISABLE_TID_CACHING) || (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt) || \ + (defined(__clang__) && !__has_feature(cxx_thread_local)) return _thread_id(); #else // cache thread id in tls static thread_local const size_t tid = _thread_id(); return tid; #endif - - } - // This is avoid msvc issue in sleep_for that happens if the clock changes. // See https://github.com/gabime/spdlog/issues/609 inline void sleep_for_millis(int milliseconds) @@ -377,21 +348,21 @@ inline void sleep_for_millis(int milliseconds) // wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined) #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) -#define SPDLOG_FILENAME_T(s) L ## s -inline std::string filename_to_str(const filename_t& filename) +#define SPDLOG_FILENAME_T(s) L##s +inline std::string filename_to_str(const filename_t &filename) { std::wstring_convert, wchar_t> c; return c.to_bytes(filename); } #else #define SPDLOG_FILENAME_T(s) s -inline std::string filename_to_str(const filename_t& filename) +inline std::string filename_to_str(const filename_t &filename) { return filename; } #endif -inline std::string errno_to_string(char[256], char* res) +inline std::string errno_to_string(char[256], char *res) { return std::string(res); } @@ -417,17 +388,17 @@ inline std::string errno_str(int err_num) else return "Unknown error"; -#elif defined(__FreeBSD__) || defined(__APPLE__) || defined(ANDROID) || defined(__SUNPRO_CC) || \ - ((_POSIX_C_SOURCE >= 200112L) && ! defined(_GNU_SOURCE)) // posix version +#elif defined(__FreeBSD__) || defined(__APPLE__) || defined(ANDROID) || defined(__SUNPRO_CC) || \ + ((_POSIX_C_SOURCE >= 200112L) && !defined(_GNU_SOURCE)) // posix version if (strerror_r(err_num, buf, buf_size) == 0) return std::string(buf); else return "Unknown error"; -#else // gnu version (might not use the given buf, so its retval pointer must be used) +#else // gnu version (might not use the given buf, so its retval pointer must be used) auto err = strerror_r(err_num, buf, buf_size); // let compiler choose type - return errno_to_string(buf, err); // use overloading to select correct stringify function + return errno_to_string(buf, err); // use overloading to select correct stringify function #endif } @@ -439,10 +410,8 @@ inline int pid() #else return static_cast(::getpid()); #endif - } - // Determine if the terminal supports colors // Source: https://github.com/agauniyal/rang/ inline bool is_color_terminal() @@ -450,11 +419,8 @@ inline bool is_color_terminal() #ifdef _WIN32 return true; #else - static constexpr const char* Terms[] = - { - "ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", - "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm" - }; + static constexpr const char *Terms[] = { + "ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"}; const char *env_p = std::getenv("TERM"); if (env_p == nullptr) @@ -462,19 +428,15 @@ inline bool is_color_terminal() return false; } - static const bool result = std::any_of( - std::begin(Terms), std::end(Terms), [&](const char* term) - { - return std::strstr(env_p, term) != nullptr; - }); + static const bool result = + std::any_of(std::begin(Terms), std::end(Terms), [&](const char *term) { return std::strstr(env_p, term) != nullptr; }); return result; #endif } - // Detrmine if the terminal attached // Source: https://github.com/agauniyal/rang/ -inline bool in_terminal(FILE* file) +inline bool in_terminal(FILE *file) { #ifdef _WIN32 @@ -483,6 +445,4 @@ inline bool in_terminal(FILE* file) return isatty(fileno(file)) != 0; #endif } -} //os -} //details -} //spdlog +}}} // namespace spdlog::details::os diff --git a/include/spdlog/details/pattern_formatter_impl.h b/include/spdlog/details/pattern_formatter_impl.h index b5ee6d02..670538d5 100644 --- a/include/spdlog/details/pattern_formatter_impl.h +++ b/include/spdlog/details/pattern_formatter_impl.h @@ -5,11 +5,12 @@ #pragma once -#include "../formatter.h" #include "../details/log_msg.h" #include "../details/os.h" #include "../fmt/fmt.h" +#include "../formatter.h" +#include #include #include #include @@ -18,17 +19,13 @@ #include #include #include -#include -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { class flag_formatter { public: virtual ~flag_formatter() = default; - virtual void format(details::log_msg& msg, const std::tm& tm_time) = 0; + virtual void format(details::log_msg &msg, const std::tm &tm_time) = 0; }; /////////////////////////////////////////////////////////////////////// @@ -36,7 +33,7 @@ public: /////////////////////////////////////////////////////////////////////// class name_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << *msg.logger_name; } @@ -45,7 +42,7 @@ class name_formatter : public flag_formatter // log level appender class level_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << level::to_str(msg.level); } @@ -54,7 +51,7 @@ class level_formatter : public flag_formatter // short log level appender class short_level_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << level::to_short_str(msg.level); } @@ -64,74 +61,75 @@ class short_level_formatter : public flag_formatter // Date time pattern appenders /////////////////////////////////////////////////////////////////////// -static const char* ampm(const tm& t) +static const char *ampm(const tm &t) { return t.tm_hour >= 12 ? "PM" : "AM"; } -static int to12h(const tm& t) +static int to12h(const tm &t) { return t.tm_hour > 12 ? t.tm_hour - 12 : t.tm_hour; } -//Abbreviated weekday name -static const std::string days[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; +// Abbreviated weekday name +static const std::string days[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; class a_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << days[tm_time.tm_wday]; } }; -//Full weekday name -static const std::string full_days[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; +// Full weekday name +static const std::string full_days[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; class A_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << full_days[tm_time.tm_wday]; } }; -//Abbreviated month -static const std::string months[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" }; +// Abbreviated month +static const std::string months[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"}; class b_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << months[tm_time.tm_mon]; } }; -//Full month name -static const std::string full_months[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; +// Full month name +static const std::string full_months[]{ + "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; class B_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << full_months[tm_time.tm_mon]; } }; -//write 2 ints separated by sep with padding of 2 -static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, char sep) +// write 2 ints separated by sep with padding of 2 +static fmt::MemoryWriter &pad_n_join(fmt::MemoryWriter &w, int v1, int v2, char sep) { w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0'); return w; } -//write 3 ints separated by sep with padding of 2 -static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, int v3, char sep) +// write 3 ints separated by sep with padding of 2 +static fmt::MemoryWriter &pad_n_join(fmt::MemoryWriter &w, int v1, int v2, int v3, char sep) { w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0') << sep << fmt::pad(v3, 2, '0'); return w; } -//Date and time representation (Thu Aug 23 15:35:46 2014) +// Date and time representation (Thu Aug 23 15:35:46 2014) class c_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << days[tm_time.tm_wday] << ' ' << months[tm_time.tm_mon] << ' ' << tm_time.tm_mday << ' '; pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << tm_time.tm_year + 1900; @@ -141,7 +139,7 @@ class c_formatter SPDLOG_FINAL : public flag_formatter // year - 2 digit class C_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_year % 100, 2, '0'); } @@ -150,7 +148,7 @@ class C_formatter SPDLOG_FINAL : public flag_formatter // Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01 class D_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { pad_n_join(msg.formatted, tm_time.tm_mon + 1, tm_time.tm_mday, tm_time.tm_year % 100, '/'); } @@ -159,7 +157,7 @@ class D_formatter SPDLOG_FINAL : public flag_formatter // year - 4 digit class Y_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << tm_time.tm_year + 1900; } @@ -168,7 +166,7 @@ class Y_formatter SPDLOG_FINAL : public flag_formatter // month 1-12 class m_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_mon + 1, 2, '0'); } @@ -177,7 +175,7 @@ class m_formatter SPDLOG_FINAL : public flag_formatter // day of month 1-31 class d_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_mday, 2, '0'); } @@ -186,7 +184,7 @@ class d_formatter SPDLOG_FINAL : public flag_formatter // hours in 24 format 0-23 class H_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_hour, 2, '0'); } @@ -195,7 +193,7 @@ class H_formatter SPDLOG_FINAL : public flag_formatter // hours in 12 format 1-12 class I_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(to12h(tm_time), 2, '0'); } @@ -204,7 +202,7 @@ class I_formatter SPDLOG_FINAL : public flag_formatter // minutes 0-59 class M_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_min, 2, '0'); } @@ -213,7 +211,7 @@ class M_formatter SPDLOG_FINAL : public flag_formatter // seconds 0-59 class S_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_sec, 2, '0'); } @@ -222,7 +220,7 @@ class S_formatter SPDLOG_FINAL : public flag_formatter // milliseconds class e_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { auto duration = msg.time.time_since_epoch(); auto millis = std::chrono::duration_cast(duration).count() % 1000; @@ -233,7 +231,7 @@ class e_formatter SPDLOG_FINAL : public flag_formatter // microseconds class f_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { auto duration = msg.time.time_since_epoch(); auto micros = std::chrono::duration_cast(duration).count() % 1000000; @@ -244,7 +242,7 @@ class f_formatter SPDLOG_FINAL : public flag_formatter // nanoseconds class F_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { auto duration = msg.time.time_since_epoch(); auto ns = std::chrono::duration_cast(duration).count() % 1000000000; @@ -254,7 +252,7 @@ class F_formatter SPDLOG_FINAL : public flag_formatter class E_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { auto duration = msg.time.time_since_epoch(); auto seconds = std::chrono::duration_cast(duration).count(); @@ -265,7 +263,7 @@ class E_formatter SPDLOG_FINAL : public flag_formatter // AM/PM class p_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << ampm(tm_time); } @@ -274,7 +272,7 @@ class p_formatter SPDLOG_FINAL : public flag_formatter // 12 hour clock 02:55:02 pm class r_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { pad_n_join(msg.formatted, to12h(tm_time), tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << ampm(tm_time); } @@ -283,7 +281,7 @@ class r_formatter SPDLOG_FINAL : public flag_formatter // 24-hour HH:MM time, equivalent to %H:%M class R_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, ':'); } @@ -292,7 +290,7 @@ class R_formatter SPDLOG_FINAL : public flag_formatter // ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S class T_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':'); } @@ -305,10 +303,10 @@ public: const std::chrono::seconds cache_refresh = std::chrono::seconds(5); z_formatter() = default; - z_formatter(const z_formatter&) = delete; - z_formatter& operator=(const z_formatter&) = delete; + z_formatter(const z_formatter &) = delete; + z_formatter &operator=(const z_formatter &) = delete; - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { #ifdef _WIN32 int total_minutes = get_cached_offset(msg, tm_time); @@ -334,12 +332,13 @@ public: msg.formatted << sign; pad_n_join(msg.formatted, h, m, ':'); } + private: - log_clock::time_point _last_update{ std::chrono::seconds(0) }; - int _offset_minutes{ 0 }; + log_clock::time_point _last_update{std::chrono::seconds(0)}; + int _offset_minutes{0}; std::mutex _mutex; - int get_cached_offset(const log_msg& msg, const std::tm& tm_time) + int get_cached_offset(const log_msg &msg, const std::tm &tm_time) { std::lock_guard l(_mutex); if (msg.time - _last_update >= cache_refresh) @@ -354,7 +353,7 @@ private: // Thread id class t_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << msg.thread_id; } @@ -363,7 +362,7 @@ class t_formatter SPDLOG_FINAL : public flag_formatter // Current pid class pid_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << details::os::pid(); } @@ -372,7 +371,7 @@ class pid_formatter SPDLOG_FINAL : public flag_formatter // message counter formatter class i_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << fmt::pad(msg.msg_id, 6, '0'); } @@ -380,7 +379,7 @@ class i_formatter SPDLOG_FINAL : public flag_formatter class v_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size()); } @@ -389,18 +388,20 @@ class v_formatter SPDLOG_FINAL : public flag_formatter class ch_formatter SPDLOG_FINAL : public flag_formatter { public: - explicit ch_formatter(char ch): _ch(ch) - {} - void format(details::log_msg& msg, const std::tm&) override + explicit ch_formatter(char ch) + : _ch(ch) + { + } + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << _ch; } + private: char _ch; }; - -//aggregate user chars to display as is +// aggregate user chars to display as is class aggregate_formatter SPDLOG_FINAL : public flag_formatter { public: @@ -410,10 +411,11 @@ public: { _str += ch; } - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << _str; } + private: std::string _str; }; @@ -422,7 +424,7 @@ private: // pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v class full_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { #ifndef SPDLOG_NO_DATETIME auto duration = msg.time.time_since_epoch(); @@ -441,7 +443,6 @@ class full_formatter SPDLOG_FINAL : public flag_formatter level::to_str(msg.level), msg.raw.str());*/ - // Faster (albeit uglier) way to format the line (5.6 million lines/sec under 10 threads) msg.formatted << '[' << static_cast(tm_time.tm_year + 1900) << '-' << fmt::pad(static_cast(tm_time.tm_mon + 1), 2, '0') << '-' @@ -451,7 +452,7 @@ class full_formatter SPDLOG_FINAL : public flag_formatter << fmt::pad(static_cast(tm_time.tm_sec), 2, '0') << '.' << fmt::pad(static_cast(millis), 3, '0') << "] "; - //no datetime needed + // no datetime needed #else (void)tm_time; #endif @@ -465,21 +466,18 @@ class full_formatter SPDLOG_FINAL : public flag_formatter } }; - - -} -} +}} // namespace spdlog::details /////////////////////////////////////////////////////////////////////////////// // pattern_formatter inline impl /////////////////////////////////////////////////////////////////////////////// -inline spdlog::pattern_formatter::pattern_formatter(const std::string& pattern, pattern_time_type pattern_time, std::string eol) : - _eol(std::move(eol)), - _pattern_time(pattern_time) +inline spdlog::pattern_formatter::pattern_formatter(const std::string &pattern, pattern_time_type pattern_time, std::string eol) + : _eol(std::move(eol)) + , _pattern_time(pattern_time) { compile_pattern(pattern); } -inline void spdlog::pattern_formatter::compile_pattern(const std::string& pattern) +inline void spdlog::pattern_formatter::compile_pattern(const std::string &pattern) { auto end = pattern.end(); std::unique_ptr user_chars; @@ -487,7 +485,7 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string& patter { if (*it == '%') { - if (user_chars) //append user chars found so far + if (user_chars) // append user chars found so far _formatters.push_back(std::move(user_chars)); if (++it != end) handle_flag(*it); @@ -501,11 +499,10 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string& patter user_chars->add_ch(*it); } } - if (user_chars) //append raw chars found so far + if (user_chars) // append raw chars found so far { _formatters.push_back(std::move(user_chars)); } - } inline void spdlog::pattern_formatter::handle_flag(char flag) { @@ -524,105 +521,105 @@ inline void spdlog::pattern_formatter::handle_flag(char flag) _formatters.emplace_back(new details::short_level_formatter()); break; - case('t'): + case ('t'): _formatters.emplace_back(new details::t_formatter()); break; - case('v'): + case ('v'): _formatters.emplace_back(new details::v_formatter()); break; - case('a'): + case ('a'): _formatters.emplace_back(new details::a_formatter()); break; - case('A'): + case ('A'): _formatters.emplace_back(new details::A_formatter()); break; - case('b'): - case('h'): + case ('b'): + case ('h'): _formatters.emplace_back(new details::b_formatter()); break; - case('B'): + case ('B'): _formatters.emplace_back(new details::B_formatter()); break; - case('c'): + case ('c'): _formatters.emplace_back(new details::c_formatter()); break; - case('C'): + case ('C'): _formatters.emplace_back(new details::C_formatter()); break; - case('Y'): + case ('Y'): _formatters.emplace_back(new details::Y_formatter()); break; - case('D'): - case('x'): + case ('D'): + case ('x'): _formatters.emplace_back(new details::D_formatter()); break; - case('m'): + case ('m'): _formatters.emplace_back(new details::m_formatter()); break; - case('d'): + case ('d'): _formatters.emplace_back(new details::d_formatter()); break; - case('H'): + case ('H'): _formatters.emplace_back(new details::H_formatter()); break; - case('I'): + case ('I'): _formatters.emplace_back(new details::I_formatter()); break; - case('M'): + case ('M'): _formatters.emplace_back(new details::M_formatter()); break; - case('S'): + case ('S'): _formatters.emplace_back(new details::S_formatter()); break; - case('e'): + case ('e'): _formatters.emplace_back(new details::e_formatter()); break; - case('f'): + case ('f'): _formatters.emplace_back(new details::f_formatter()); break; - case('F'): + case ('F'): _formatters.emplace_back(new details::F_formatter()); break; - case('E'): + case ('E'): _formatters.emplace_back(new details::E_formatter()); break; - case('p'): + case ('p'): _formatters.emplace_back(new details::p_formatter()); break; - case('r'): + case ('r'): _formatters.emplace_back(new details::r_formatter()); break; - case('R'): + case ('R'): _formatters.emplace_back(new details::R_formatter()); break; - case('T'): - case('X'): + case ('T'): + case ('X'): _formatters.emplace_back(new details::T_formatter()); break; - case('z'): + case ('z'): _formatters.emplace_back(new details::z_formatter()); break; @@ -634,19 +631,18 @@ inline void spdlog::pattern_formatter::handle_flag(char flag) _formatters.emplace_back(new details::pid_formatter()); break; - case ('i'): _formatters.emplace_back(new details::i_formatter()); break; - default: //Unknown flag appears as is + default: // Unknown flag appears as is _formatters.emplace_back(new details::ch_formatter('%')); _formatters.emplace_back(new details::ch_formatter(flag)); break; } } -inline std::tm spdlog::pattern_formatter::get_time(details::log_msg& msg) +inline std::tm spdlog::pattern_formatter::get_time(details::log_msg &msg) { if (_pattern_time == pattern_time_type::local) { @@ -655,7 +651,7 @@ inline std::tm spdlog::pattern_formatter::get_time(details::log_msg& msg) return details::os::gmtime(log_clock::to_time_t(msg.time)); } -inline void spdlog::pattern_formatter::format(details::log_msg& msg) +inline void spdlog::pattern_formatter::format(details::log_msg &msg) { #ifndef SPDLOG_NO_DATETIME @@ -667,6 +663,6 @@ inline void spdlog::pattern_formatter::format(details::log_msg& msg) { f->format(msg, tm_time); } - //write eol + // write eol msg.formatted.write(_eol.data(), _eol.size()); } diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 6bd8bb2d..300e4fd7 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -10,10 +10,10 @@ // If user requests a non existing logger, nullptr will be returned // This class is thread safe -#include "../details/null_mutex.h" -#include "../logger.h" #include "../async_logger.h" #include "../common.h" +#include "../details/null_mutex.h" +#include "../logger.h" #include #include @@ -22,16 +22,12 @@ #include #include -namespace spdlog -{ -namespace details -{ -template -class registry_t +namespace spdlog { namespace details { +template class registry_t { public: - registry_t(const registry_t&) = delete; - registry_t& operator=(const registry_t&) = delete; + registry_t(const registry_t &) = delete; + registry_t &operator=(const registry_t &) = delete; void register_logger(std::shared_ptr logger) { @@ -41,21 +37,21 @@ public: _loggers[logger_name] = logger; } - std::shared_ptr get(const std::string& logger_name) + std::shared_ptr get(const std::string &logger_name) { std::lock_guard lock(_mutex); auto found = _loggers.find(logger_name); return found == _loggers.end() ? nullptr : found->second; } - template - std::shared_ptr create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end) + template std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end) { std::lock_guard lock(_mutex); throw_if_exists(logger_name); std::shared_ptr new_logger; if (_async_mode) - new_logger = std::make_shared(logger_name, sinks_begin, sinks_end, _async_q_size, _overflow_policy, _worker_warmup_cb, _flush_interval_ms, _worker_teardown_cb); + new_logger = std::make_shared(logger_name, sinks_begin, sinks_end, _async_q_size, _overflow_policy, + _worker_warmup_cb, _flush_interval_ms, _worker_teardown_cb); else new_logger = std::make_shared(logger_name, sinks_begin, sinks_end); @@ -68,18 +64,21 @@ public: new_logger->set_level(_level); new_logger->flush_on(_flush_level); - - //Add to registry + // Add to registry _loggers[logger_name] = new_logger; return new_logger; } - template - std::shared_ptr create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb, const It& sinks_begin, const It& sinks_end) + template + std::shared_ptr create_async(const std::string &logger_name, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb, const It &sinks_begin, + const It &sinks_end) { std::lock_guard lock(_mutex); throw_if_exists(logger_name); - auto new_logger = std::make_shared(logger_name, sinks_begin, sinks_end, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb); + auto new_logger = std::make_shared( + logger_name, sinks_begin, sinks_end, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb); if (_formatter) new_logger->set_formatter(_formatter); @@ -90,7 +89,7 @@ public: new_logger->set_level(_level); new_logger->flush_on(_flush_level); - //Add to registry + // Add to registry _loggers[logger_name] = new_logger; return new_logger; } @@ -102,7 +101,7 @@ public: fun(l.second); } - void drop(const std::string& logger_name) + void drop(const std::string &logger_name) { std::lock_guard lock(_mutex); _loggers.erase(logger_name); @@ -114,46 +113,51 @@ public: _loggers.clear(); } - std::shared_ptr create(const std::string& logger_name, sinks_init_list sinks) + std::shared_ptr create(const std::string &logger_name, sinks_init_list sinks) { return create(logger_name, sinks.begin(), sinks.end()); } - std::shared_ptr create(const std::string& logger_name, sink_ptr sink) + std::shared_ptr create(const std::string &logger_name, sink_ptr sink) { - return create(logger_name, { sink }); + return create(logger_name, {sink}); } - std::shared_ptr create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb, sinks_init_list sinks) + std::shared_ptr create_async(const std::string &logger_name, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb, sinks_init_list sinks) { - return create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks.begin(), sinks.end()); + return create_async( + logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks.begin(), sinks.end()); } - std::shared_ptr create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb, sink_ptr sink) + std::shared_ptr create_async(const std::string &logger_name, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb, sink_ptr sink) { - return create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, { sink }); + return create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, {sink}); } void formatter(formatter_ptr f) { std::lock_guard lock(_mutex); _formatter = f; - for (auto& l : _loggers) + for (auto &l : _loggers) l.second->set_formatter(_formatter); } - void set_pattern(const std::string& pattern) + void set_pattern(const std::string &pattern) { std::lock_guard lock(_mutex); _formatter = std::make_shared(pattern); - for (auto& l : _loggers) + for (auto &l : _loggers) l.second->set_formatter(_formatter); } void set_level(level::level_enum log_level) { std::lock_guard lock(_mutex); - for (auto& l : _loggers) + for (auto &l : _loggers) l.second->set_level(log_level); _level = log_level; } @@ -161,19 +165,20 @@ public: void flush_on(level::level_enum log_level) { std::lock_guard lock(_mutex); - for (auto& l : _loggers) + for (auto &l : _loggers) l.second->flush_on(log_level); _flush_level = log_level; } void set_error_handler(log_err_handler handler) { - for (auto& l : _loggers) + for (auto &l : _loggers) l.second->set_error_handler(handler); _err_handler = handler; } - void set_async_mode(size_t q_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb) + void set_async_mode(size_t q_size, const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) { std::lock_guard lock(_mutex); _async_mode = true; @@ -190,7 +195,7 @@ public: _async_mode = false; } - static registry_t& instance() + static registry_t &instance() { static registry_t s_instance; return s_instance; @@ -206,7 +211,7 @@ private: } Mutex _mutex; - std::unordered_map > _loggers; + std::unordered_map> _loggers; formatter_ptr _formatter; level::level_enum _level = level::info; level::level_enum _flush_level = level::off; @@ -225,5 +230,4 @@ using registry = registry_t; using registry = registry_t; #endif -} -} +}} // namespace spdlog::details diff --git a/include/spdlog/details/spdlog_impl.h b/include/spdlog/details/spdlog_impl.h index 003aff16..114498b1 100644 --- a/include/spdlog/details/spdlog_impl.h +++ b/include/spdlog/details/spdlog_impl.h @@ -8,10 +8,10 @@ // // Global registry functions // -#include "../spdlog.h" #include "../details/registry.h" #include "../sinks/file_sinks.h" #include "../sinks/stdout_sinks.h" +#include "../spdlog.h" #ifdef SPDLOG_ENABLE_SYSLOG #include "../sinks/syslog_sink.h" #endif @@ -22,7 +22,6 @@ #include "../sinks/ansicolor_sink.h" #endif - #ifdef __ANDROID__ #include "../sinks/android_sink.h" #endif @@ -37,7 +36,7 @@ inline void spdlog::register_logger(std::shared_ptr logger) return details::registry::instance().register_logger(std::move(logger)); } -inline std::shared_ptr spdlog::get(const std::string& name) +inline std::shared_ptr spdlog::get(const std::string &name) { return details::registry::instance().get(name); } @@ -48,58 +47,61 @@ inline void spdlog::drop(const std::string &name) } // Create multi/single threaded simple file logger -inline std::shared_ptr spdlog::basic_logger_mt(const std::string& logger_name, const filename_t& filename, bool truncate) +inline std::shared_ptr spdlog::basic_logger_mt(const std::string &logger_name, const filename_t &filename, bool truncate) { return create(logger_name, filename, truncate); } -inline std::shared_ptr spdlog::basic_logger_st(const std::string& logger_name, const filename_t& filename, bool truncate) +inline std::shared_ptr spdlog::basic_logger_st(const std::string &logger_name, const filename_t &filename, bool truncate) { return create(logger_name, filename, truncate); } // Create multi/single threaded rotating file logger -inline std::shared_ptr spdlog::rotating_logger_mt(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files) +inline std::shared_ptr spdlog::rotating_logger_mt( + const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files) { return create(logger_name, filename, max_file_size, max_files); } -inline std::shared_ptr spdlog::rotating_logger_st(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files) +inline std::shared_ptr spdlog::rotating_logger_st( + const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files) { return create(logger_name, filename, max_file_size, max_files); } // Create file logger which creates new file at midnight): -inline std::shared_ptr spdlog::daily_logger_mt(const std::string& logger_name, const filename_t& filename, int hour, int minute) +inline std::shared_ptr spdlog::daily_logger_mt( + const std::string &logger_name, const filename_t &filename, int hour, int minute) { return create(logger_name, filename, hour, minute); } -inline std::shared_ptr spdlog::daily_logger_st(const std::string& logger_name, const filename_t& filename, int hour, int minute) +inline std::shared_ptr spdlog::daily_logger_st( + const std::string &logger_name, const filename_t &filename, int hour, int minute) { return create(logger_name, filename, hour, minute); } - // // stdout/stderr loggers // -inline std::shared_ptr spdlog::stdout_logger_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_logger_mt(const std::string &logger_name) { return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stdout_sink_mt::instance()); } -inline std::shared_ptr spdlog::stdout_logger_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_logger_st(const std::string &logger_name) { return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stdout_sink_st::instance()); } -inline std::shared_ptr spdlog::stderr_logger_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_logger_mt(const std::string &logger_name) { return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stderr_sink_mt::instance()); } -inline std::shared_ptr spdlog::stderr_logger_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_logger_st(const std::string &logger_name) { return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stderr_sink_st::instance()); } @@ -109,52 +111,51 @@ inline std::shared_ptr spdlog::stderr_logger_st(const std::strin // #if defined _WIN32 && !defined(__cplusplus_winrt) -inline std::shared_ptr spdlog::stdout_color_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_color_mt(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr spdlog::stdout_color_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_color_st(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr spdlog::stderr_color_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_color_mt(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } - -inline std::shared_ptr spdlog::stderr_color_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_color_st(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -#else //ansi terminal colors +#else // ansi terminal colors -inline std::shared_ptr spdlog::stdout_color_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_color_mt(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr spdlog::stdout_color_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_color_st(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr spdlog::stderr_color_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_color_mt(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr spdlog::stderr_color_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_color_st(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); @@ -163,60 +164,70 @@ inline std::shared_ptr spdlog::stderr_color_st(const std::string #ifdef SPDLOG_ENABLE_SYSLOG // Create syslog logger -inline std::shared_ptr spdlog::syslog_logger(const std::string& logger_name, const std::string& syslog_ident, int syslog_option, int syslog_facility) +inline std::shared_ptr spdlog::syslog_logger( + const std::string &logger_name, const std::string &syslog_ident, int syslog_option, int syslog_facility) { return create(logger_name, syslog_ident, syslog_option, syslog_facility); } #endif #ifdef __ANDROID__ -inline std::shared_ptr spdlog::android_logger(const std::string& logger_name, const std::string& tag) +inline std::shared_ptr spdlog::android_logger(const std::string &logger_name, const std::string &tag) { return create(logger_name, tag); } #endif // Create and register a logger a single sink -inline std::shared_ptr spdlog::create(const std::string& logger_name, const spdlog::sink_ptr& sink) +inline std::shared_ptr spdlog::create(const std::string &logger_name, const spdlog::sink_ptr &sink) { return details::registry::instance().create(logger_name, sink); } -//Create logger with multiple sinks -inline std::shared_ptr spdlog::create(const std::string& logger_name, spdlog::sinks_init_list sinks) +// Create logger with multiple sinks +inline std::shared_ptr spdlog::create(const std::string &logger_name, spdlog::sinks_init_list sinks) { return details::registry::instance().create(logger_name, sinks); } template -inline std::shared_ptr spdlog::create(const std::string& logger_name, Args... args) +inline std::shared_ptr spdlog::create(const std::string &logger_name, Args... args) { sink_ptr sink = std::make_shared(args...); - return details::registry::instance().create(logger_name, { sink }); + return details::registry::instance().create(logger_name, {sink}); } -template -inline std::shared_ptr spdlog::create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end) +template +inline std::shared_ptr spdlog::create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end) { return details::registry::instance().create(logger_name, sinks_begin, sinks_end); } // Create and register an async logger with a single sink -inline std::shared_ptr spdlog::create_async(const std::string& logger_name, const sink_ptr& sink, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb) +inline std::shared_ptr spdlog::create_async(const std::string &logger_name, const sink_ptr &sink, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) { - return details::registry::instance().create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sink); + return details::registry::instance().create_async( + logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sink); } // Create and register an async logger with multiple sinks -inline std::shared_ptr spdlog::create_async(const std::string& logger_name, sinks_init_list sinks, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb ) +inline std::shared_ptr spdlog::create_async(const std::string &logger_name, sinks_init_list sinks, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) { - return details::registry::instance().create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks); + return details::registry::instance().create_async( + logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks); } -template -inline std::shared_ptr spdlog::create_async(const std::string& logger_name, const It& sinks_begin, const It& sinks_end, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb) +template +inline std::shared_ptr spdlog::create_async(const std::string &logger_name, const It &sinks_begin, const It &sinks_end, + size_t queue_size, const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) { - return details::registry::instance().create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks_begin, sinks_end); + return details::registry::instance().create_async( + logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks_begin, sinks_end); } inline void spdlog::set_formatter(spdlog::formatter_ptr f) @@ -224,7 +235,7 @@ inline void spdlog::set_formatter(spdlog::formatter_ptr f) details::registry::instance().formatter(std::move(f)); } -inline void spdlog::set_pattern(const std::string& format_string) +inline void spdlog::set_pattern(const std::string &format_string) { return details::registry::instance().set_pattern(format_string); } @@ -244,7 +255,9 @@ inline void spdlog::set_error_handler(log_err_handler handler) return details::registry::instance().set_error_handler(std::move(handler)); } -inline void spdlog::set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb) +inline void spdlog::set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy, + const std::function &worker_warmup_cb, const std::chrono::milliseconds &flush_interval_ms, + const std::function &worker_teardown_cb) { details::registry::instance().set_async_mode(queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb); } diff --git a/include/spdlog/fmt/bundled/format.h b/include/spdlog/fmt/bundled/format.h index 971c58e2..bc84c7b5 100644 --- a/include/spdlog/fmt/bundled/format.h +++ b/include/spdlog/fmt/bundled/format.h @@ -38,273 +38,264 @@ #include #include #include +#include // for std::pair #include -#include // for std::pair #undef FMT_INCLUDE // The fmt library version in the form major * 10000 + minor * 100 + patch. #define FMT_VERSION 40100 #if defined(__has_include) -# define FMT_HAS_INCLUDE(x) __has_include(x) +#define FMT_HAS_INCLUDE(x) __has_include(x) #else -# define FMT_HAS_INCLUDE(x) 0 +#define FMT_HAS_INCLUDE(x) 0 #endif -#if (FMT_HAS_INCLUDE() && __cplusplus > 201402L) || \ - (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) -# include -# define FMT_HAS_STRING_VIEW 1 +#if (FMT_HAS_INCLUDE() && __cplusplus > 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) +#include +#define FMT_HAS_STRING_VIEW 1 #else -# define FMT_HAS_STRING_VIEW 0 +#define FMT_HAS_STRING_VIEW 0 #endif #if defined _SECURE_SCL && _SECURE_SCL -# define FMT_SECURE_SCL _SECURE_SCL +#define FMT_SECURE_SCL _SECURE_SCL #else -# define FMT_SECURE_SCL 0 +#define FMT_SECURE_SCL 0 #endif #if FMT_SECURE_SCL -# include +#include #endif #ifdef _MSC_VER -# define FMT_MSC_VER _MSC_VER +#define FMT_MSC_VER _MSC_VER #else -# define FMT_MSC_VER 0 +#define FMT_MSC_VER 0 #endif #if FMT_MSC_VER && FMT_MSC_VER <= 1500 typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; -typedef __int64 intmax_t; +typedef __int64 intmax_t; #else #include #endif #if !defined(FMT_HEADER_ONLY) && defined(_WIN32) -# ifdef FMT_EXPORT -# define FMT_API __declspec(dllexport) -# elif defined(FMT_SHARED) -# define FMT_API __declspec(dllimport) -# endif +#ifdef FMT_EXPORT +#define FMT_API __declspec(dllexport) +#elif defined(FMT_SHARED) +#define FMT_API __declspec(dllimport) +#endif #endif #ifndef FMT_API -# define FMT_API +#define FMT_API #endif #ifdef __GNUC__ -# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -# define FMT_GCC_EXTENSION __extension__ -# if FMT_GCC_VERSION >= 406 -# pragma GCC diagnostic push +#define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#define FMT_GCC_EXTENSION __extension__ +#if FMT_GCC_VERSION >= 406 +#pragma GCC diagnostic push // Disable the warning about "long long" which is sometimes reported even // when using __extension__. -# pragma GCC diagnostic ignored "-Wlong-long" +#pragma GCC diagnostic ignored "-Wlong-long" // Disable the warning about declaration shadowing because it affects too // many valid cases. -# pragma GCC diagnostic ignored "-Wshadow" +#pragma GCC diagnostic ignored "-Wshadow" // Disable the warning about implicit conversions that may change the sign of // an integer; silencing it otherwise would require many explicit casts. -# pragma GCC diagnostic ignored "-Wsign-conversion" -# endif -# if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__ -# define FMT_HAS_GXX_CXX11 1 -# endif +#pragma GCC diagnostic ignored "-Wsign-conversion" +#endif +#if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__ +#define FMT_HAS_GXX_CXX11 1 +#endif #else -# define FMT_GCC_VERSION 0 -# define FMT_GCC_EXTENSION -# define FMT_HAS_GXX_CXX11 0 +#define FMT_GCC_VERSION 0 +#define FMT_GCC_EXTENSION +#define FMT_HAS_GXX_CXX11 0 #endif #if defined(__INTEL_COMPILER) -# define FMT_ICC_VERSION __INTEL_COMPILER +#define FMT_ICC_VERSION __INTEL_COMPILER #elif defined(__ICL) -# define FMT_ICC_VERSION __ICL +#define FMT_ICC_VERSION __ICL #endif #if defined(__clang__) && !defined(FMT_ICC_VERSION) -# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wdocumentation-unknown-command" -# pragma clang diagnostic ignored "-Wpadded" +#define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#pragma clang diagnostic ignored "-Wpadded" #endif #ifdef __GNUC_LIBSTD__ -# define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__) +#define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__) #endif #ifdef __has_feature -# define FMT_HAS_FEATURE(x) __has_feature(x) +#define FMT_HAS_FEATURE(x) __has_feature(x) #else -# define FMT_HAS_FEATURE(x) 0 +#define FMT_HAS_FEATURE(x) 0 #endif #ifdef __has_builtin -# define FMT_HAS_BUILTIN(x) __has_builtin(x) +#define FMT_HAS_BUILTIN(x) __has_builtin(x) #else -# define FMT_HAS_BUILTIN(x) 0 +#define FMT_HAS_BUILTIN(x) 0 #endif #ifdef __has_cpp_attribute -# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) #else -# define FMT_HAS_CPP_ATTRIBUTE(x) 0 +#define FMT_HAS_CPP_ATTRIBUTE(x) 0 #endif #if FMT_HAS_CPP_ATTRIBUTE(maybe_unused) -# define FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED +#define FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED // VC++ 1910 support /std: option and that will set _MSVC_LANG macro // Clang with Microsoft CodeGen doesn't define _MSVC_LANG macro #elif defined(_MSVC_LANG) && _MSVC_LANG > 201402 && _MSC_VER >= 1910 -# define FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED +#define FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED #endif #ifdef FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED -# define FMT_MAYBE_UNUSED [[maybe_unused]] +#define FMT_MAYBE_UNUSED [[maybe_unused]] // g++/clang++ also support [[gnu::unused]]. However, we don't use it. #elif defined(__GNUC__) -# define FMT_MAYBE_UNUSED __attribute__((unused)) +#define FMT_MAYBE_UNUSED __attribute__((unused)) #else -# define FMT_MAYBE_UNUSED +#define FMT_MAYBE_UNUSED #endif // Use the compiler's attribute noreturn #if defined(__MINGW32__) || defined(__MINGW64__) -# define FMT_NORETURN __attribute__((noreturn)) +#define FMT_NORETURN __attribute__((noreturn)) #elif FMT_HAS_CPP_ATTRIBUTE(noreturn) && __cplusplus >= 201103L -# define FMT_NORETURN [[noreturn]] +#define FMT_NORETURN [[noreturn]] #else -# define FMT_NORETURN +#define FMT_NORETURN #endif #ifndef FMT_USE_VARIADIC_TEMPLATES // Variadic templates are available in GCC since version 4.4 // (http://gcc.gnu.org/projects/cxx0x.html) and in Visual C++ // since version 2013. -# define FMT_USE_VARIADIC_TEMPLATES \ - (FMT_HAS_FEATURE(cxx_variadic_templates) || \ - (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800) +#define FMT_USE_VARIADIC_TEMPLATES \ + (FMT_HAS_FEATURE(cxx_variadic_templates) || (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800) #endif #ifndef FMT_USE_RVALUE_REFERENCES // Don't use rvalue references when compiling with clang and an old libstdc++ // as the latter doesn't provide std::move. -# if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402 -# define FMT_USE_RVALUE_REFERENCES 0 -# else -# define FMT_USE_RVALUE_REFERENCES \ - (FMT_HAS_FEATURE(cxx_rvalue_references) || \ - (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1600) -# endif +#if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402 +#define FMT_USE_RVALUE_REFERENCES 0 +#else +#define FMT_USE_RVALUE_REFERENCES \ + (FMT_HAS_FEATURE(cxx_rvalue_references) || (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1600) +#endif #endif #if __cplusplus >= 201103L || FMT_MSC_VER >= 1700 -# define FMT_USE_ALLOCATOR_TRAITS 1 +#define FMT_USE_ALLOCATOR_TRAITS 1 #else -# define FMT_USE_ALLOCATOR_TRAITS 0 +#define FMT_USE_ALLOCATOR_TRAITS 0 #endif // Check if exceptions are disabled. #if defined(__GNUC__) && !defined(__EXCEPTIONS) -# define FMT_EXCEPTIONS 0 +#define FMT_EXCEPTIONS 0 #endif #if FMT_MSC_VER && !_HAS_EXCEPTIONS -# define FMT_EXCEPTIONS 0 +#define FMT_EXCEPTIONS 0 #endif #ifndef FMT_EXCEPTIONS -# define FMT_EXCEPTIONS 1 +#define FMT_EXCEPTIONS 1 #endif #ifndef FMT_THROW -# if FMT_EXCEPTIONS -# define FMT_THROW(x) throw x -# else -# define FMT_THROW(x) assert(false) -# endif +#if FMT_EXCEPTIONS +#define FMT_THROW(x) throw x +#else +#define FMT_THROW(x) assert(false) +#endif #endif // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature). #ifndef FMT_USE_NOEXCEPT -# define FMT_USE_NOEXCEPT 0 +#define FMT_USE_NOEXCEPT 0 #endif -#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \ - (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ - FMT_MSC_VER >= 1900 -# define FMT_DETECTED_NOEXCEPT noexcept +#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900 +#define FMT_DETECTED_NOEXCEPT noexcept #else -# define FMT_DETECTED_NOEXCEPT throw() +#define FMT_DETECTED_NOEXCEPT throw() #endif #ifndef FMT_NOEXCEPT -# if FMT_EXCEPTIONS -# define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT -# else -# define FMT_NOEXCEPT -# endif +#if FMT_EXCEPTIONS +#define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT +#else +#define FMT_NOEXCEPT +#endif #endif // This is needed because GCC still uses throw() in its headers when exceptions // are disabled. #if FMT_GCC_VERSION -# define FMT_DTOR_NOEXCEPT FMT_DETECTED_NOEXCEPT +#define FMT_DTOR_NOEXCEPT FMT_DETECTED_NOEXCEPT #else -# define FMT_DTOR_NOEXCEPT FMT_NOEXCEPT +#define FMT_DTOR_NOEXCEPT FMT_NOEXCEPT #endif #ifndef FMT_OVERRIDE -# if (defined(FMT_USE_OVERRIDE) && FMT_USE_OVERRIDE) || FMT_HAS_FEATURE(cxx_override) || \ - (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ - FMT_MSC_VER >= 1900 -# define FMT_OVERRIDE override -# else -# define FMT_OVERRIDE -# endif +#if (defined(FMT_USE_OVERRIDE) && FMT_USE_OVERRIDE) || FMT_HAS_FEATURE(cxx_override) || (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ + FMT_MSC_VER >= 1900 +#define FMT_OVERRIDE override +#else +#define FMT_OVERRIDE +#endif #endif #ifndef FMT_NULL -# if FMT_HAS_FEATURE(cxx_nullptr) || \ - (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ - FMT_MSC_VER >= 1600 -# define FMT_NULL nullptr -# else -# define FMT_NULL NULL -# endif +#if FMT_HAS_FEATURE(cxx_nullptr) || (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1600 +#define FMT_NULL nullptr +#else +#define FMT_NULL NULL +#endif #endif // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #ifndef FMT_USE_DELETED_FUNCTIONS -# define FMT_USE_DELETED_FUNCTIONS 0 +#define FMT_USE_DELETED_FUNCTIONS 0 #endif -#if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || \ - (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800 -# define FMT_DELETED_OR_UNDEFINED = delete -# define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&) = delete; \ - TypeName& operator=(const TypeName&) = delete +#if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || \ + FMT_MSC_VER >= 1800 +#define FMT_DELETED_OR_UNDEFINED = delete +#define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName &) = delete; \ + TypeName &operator=(const TypeName &) = delete #else -# define FMT_DELETED_OR_UNDEFINED -# define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&); \ - TypeName& operator=(const TypeName&) +#define FMT_DELETED_OR_UNDEFINED +#define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName &); \ + TypeName &operator=(const TypeName &) #endif #ifndef FMT_USE_DEFAULTED_FUNCTIONS -# define FMT_USE_DEFAULTED_FUNCTIONS 0 +#define FMT_USE_DEFAULTED_FUNCTIONS 0 #endif #ifndef FMT_DEFAULTED_COPY_CTOR -# if FMT_USE_DEFAULTED_FUNCTIONS || FMT_HAS_FEATURE(cxx_defaulted_functions) || \ - (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800 -# define FMT_DEFAULTED_COPY_CTOR(TypeName) \ - TypeName(const TypeName&) = default; -# else -# define FMT_DEFAULTED_COPY_CTOR(TypeName) -# endif +#if FMT_USE_DEFAULTED_FUNCTIONS || FMT_HAS_FEATURE(cxx_defaulted_functions) || (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || \ + FMT_MSC_VER >= 1800 +#define FMT_DEFAULTED_COPY_CTOR(TypeName) TypeName(const TypeName &) = default; +#else +#define FMT_DEFAULTED_COPY_CTOR(TypeName) +#endif #endif #ifndef FMT_USE_USER_DEFINED_LITERALS @@ -312,41 +303,39 @@ typedef __int64 intmax_t; // makes the fmt::literals implementation easier. However, an explicit check // for variadic templates is added here just in case. // For Intel's compiler both it and the system gcc/msc must support UDLs. -# if FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES && \ - (FMT_HAS_FEATURE(cxx_user_literals) || \ - (FMT_GCC_VERSION >= 407 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900) && \ - (!defined(FMT_ICC_VERSION) || FMT_ICC_VERSION >= 1500) -# define FMT_USE_USER_DEFINED_LITERALS 1 -# else -# define FMT_USE_USER_DEFINED_LITERALS 0 -# endif +#if FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES && \ + (FMT_HAS_FEATURE(cxx_user_literals) || (FMT_GCC_VERSION >= 407 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900) && \ + (!defined(FMT_ICC_VERSION) || FMT_ICC_VERSION >= 1500) +#define FMT_USE_USER_DEFINED_LITERALS 1 +#else +#define FMT_USE_USER_DEFINED_LITERALS 0 +#endif #endif #ifndef FMT_USE_EXTERN_TEMPLATES -# define FMT_USE_EXTERN_TEMPLATES \ - (FMT_CLANG_VERSION >= 209 || (FMT_GCC_VERSION >= 303 && FMT_HAS_GXX_CXX11)) +#define FMT_USE_EXTERN_TEMPLATES (FMT_CLANG_VERSION >= 209 || (FMT_GCC_VERSION >= 303 && FMT_HAS_GXX_CXX11)) #endif #ifdef FMT_HEADER_ONLY // If header only do not use extern templates. -# undef FMT_USE_EXTERN_TEMPLATES -# define FMT_USE_EXTERN_TEMPLATES 0 +#undef FMT_USE_EXTERN_TEMPLATES +#define FMT_USE_EXTERN_TEMPLATES 0 #endif #ifndef FMT_ASSERT -# define FMT_ASSERT(condition, message) assert((condition) && message) +#define FMT_ASSERT(condition, message) assert((condition) && message) #endif // __builtin_clz is broken in clang with Microsoft CodeGen: // https://github.com/fmtlib/fmt/issues/519 #ifndef _MSC_VER -# if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz) -# define FMT_BUILTIN_CLZ(n) __builtin_clz(n) -# endif +#if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz) +#define FMT_BUILTIN_CLZ(n) __builtin_clz(n) +#endif -# if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll) -# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) -# endif +#if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll) +#define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) +#endif #endif // Some compilers masquerade as both MSVC and GCC-likes or @@ -354,16 +343,14 @@ typedef __int64 intmax_t; // only define FMT_BUILTIN_CLZ using the MSVC intrinsics // if the clz and clzll builtins are not available. #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(_MANAGED) -# include // _BitScanReverse, _BitScanReverse64 +#include // _BitScanReverse, _BitScanReverse64 -namespace fmt -{ -namespace internal -{ +namespace fmt { +namespace internal { // avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning -# ifndef __clang__ -# pragma intrinsic(_BitScanReverse) -# endif +#ifndef __clang__ +#pragma intrinsic(_BitScanReverse) +#endif inline uint32_t clz(uint32_t x) { unsigned long r = 0; @@ -373,46 +360,43 @@ inline uint32_t clz(uint32_t x) // Static analysis complains about using uninitialized data // "r", but the only way that can happen is if "x" is 0, // which the callers guarantee to not happen. -# pragma warning(suppress: 6102) +#pragma warning(suppress : 6102) return 31 - r; } -# define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n) +#define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n) // avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning -# if defined(_WIN64) && !defined(__clang__) -# pragma intrinsic(_BitScanReverse64) -# endif +#if defined(_WIN64) && !defined(__clang__) +#pragma intrinsic(_BitScanReverse64) +#endif inline uint32_t clzll(uint64_t x) { unsigned long r = 0; -# ifdef _WIN64 +#ifdef _WIN64 _BitScanReverse64(&r, x); -# else +#else // Scan the high 32 bits. if (_BitScanReverse(&r, static_cast(x >> 32))) return 63 - (r + 32); // Scan the low 32 bits. _BitScanReverse(&r, static_cast(x)); -# endif +#endif assert(x != 0); // Static analysis complains about using uninitialized data // "r", but the only way that can happen is if "x" is 0, // which the callers guarantee to not happen. -# pragma warning(suppress: 6102) +#pragma warning(suppress : 6102) return 63 - r; } -# define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) -} +#define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) } +} // namespace fmt #endif -namespace fmt -{ -namespace internal -{ +namespace fmt { namespace internal { struct DummyInt { int data[2]; @@ -452,34 +436,27 @@ inline DummyInt _isnan(...) // A helper function to suppress bogus "conditional expression is constant" // warnings. -template -inline T const_check(T value) +template inline T const_check(T value) { return value; } -} -} // namespace fmt +}} // namespace fmt::internal -namespace std -{ +namespace std { // Standard permits specialization of std::numeric_limits. This specialization // is used to resolve ambiguity between isinf and std::isinf in glibc: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891 // and the same for isnan and signbit. -template <> -class numeric_limits : - public std::numeric_limits +template <> class numeric_limits : public std::numeric_limits { public: // Portable version of isinf. - template - static bool isinfinity(T x) + template static bool isinfinity(T x) { using namespace fmt::internal; // The resolution "priority" is: // isinf macro > std::isinf > ::isinf > fmt::internal::isinf - if (const_check(sizeof(isinf(x)) == sizeof(bool) || - sizeof(isinf(x)) == sizeof(int))) + if (const_check(sizeof(isinf(x)) == sizeof(bool) || sizeof(isinf(x)) == sizeof(int))) { return isinf(x) != 0; } @@ -487,12 +464,10 @@ public: } // Portable version of isnan. - template - static bool isnotanumber(T x) + template static bool isnotanumber(T x) { using namespace fmt::internal; - if (const_check(sizeof(isnan(x)) == sizeof(bool) || - sizeof(isnan(x)) == sizeof(int))) + if (const_check(sizeof(isnan(x)) == sizeof(bool) || sizeof(isnan(x)) == sizeof(int))) { return isnan(x) != 0; } @@ -503,23 +478,23 @@ public: static bool isnegative(double x) { using namespace fmt::internal; - if (const_check(sizeof(signbit(x)) == sizeof(bool) || - sizeof(signbit(x)) == sizeof(int))) + if (const_check(sizeof(signbit(x)) == sizeof(bool) || sizeof(signbit(x)) == sizeof(int))) { return signbit(x) != 0; } - if (x < 0) return true; - if (!isnotanumber(x)) return false; + if (x < 0) + return true; + if (!isnotanumber(x)) + return false; int dec = 0, sign = 0; - char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail. + char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail. _ecvt_s(buffer, sizeof(buffer), x, 0, &dec, &sign); return sign != 0; } }; -} // namespace std +} // namespace std -namespace fmt -{ +namespace fmt { // Fix the warning about long long on older versions of GCC // that don't support the diagnostic pragma. @@ -530,23 +505,18 @@ FMT_GCC_EXTENSION typedef unsigned long long ULongLong; using std::move; #endif -template -class BasicWriter; +template class BasicWriter; typedef BasicWriter Writer; typedef BasicWriter WWriter; -template -class ArgFormatter; +template class ArgFormatter; struct FormatSpec; -template -class BasicPrintfArgFormatter; +template class BasicPrintfArgFormatter; -template > -class BasicFormatter; +template > class BasicFormatter; /** \rst @@ -573,8 +543,7 @@ class BasicFormatter; format(std::string("{}"), 42); \endrst */ -template -class BasicStringRef +template class BasicStringRef { private: const Char *data_; @@ -582,7 +551,11 @@ private: public: /** Constructs a string reference object from a C string and a size. */ - BasicStringRef(const Char *s, std::size_t size) : data_(s), size_(size) {} + BasicStringRef(const Char *s, std::size_t size) + : data_(s) + , size_(size) + { + } /** \rst @@ -591,7 +564,10 @@ public: \endrst */ BasicStringRef(const Char *s) - : data_(s), size_(std::char_traits::length(s)) {} + : data_(s) + , size_(std::char_traits::length(s)) + { + } /** \rst @@ -599,9 +575,11 @@ public: \endrst */ template - BasicStringRef( - const std::basic_string, Allocator> &s) - : data_(s.c_str()), size_(s.size()) {} + BasicStringRef(const std::basic_string, Allocator> &s) + : data_(s.c_str()) + , size_(s.size()) + { + } #if FMT_HAS_STRING_VIEW /** @@ -609,9 +587,11 @@ public: Constructs a string reference from a ``std::basic_string_view`` object. \endrst */ - BasicStringRef( - const std::basic_string_view> &s) - : data_(s.data()), size_(s.size()) {} + BasicStringRef(const std::basic_string_view> &s) + : data_(s.data()) + , size_(s.size()) + { + } /** \rst @@ -710,15 +690,17 @@ typedef BasicStringRef WStringRef; format(std::string("{}"), 42); \endrst */ -template -class BasicCStringRef +template class BasicCStringRef { private: const Char *data_; public: /** Constructs a string reference object from a C string. */ - BasicCStringRef(const Char *s) : data_(s) {} + BasicCStringRef(const Char *s) + : data_(s) + { + } /** \rst @@ -726,9 +708,10 @@ public: \endrst */ template - BasicCStringRef( - const std::basic_string, Allocator> &s) - : data_(s.c_str()) {} + BasicCStringRef(const std::basic_string, Allocator> &s) + : data_(s.c_str()) + { + } /** Returns the pointer to a C string. */ const Char *c_str() const @@ -745,24 +728,29 @@ class FormatError : public std::runtime_error { public: explicit FormatError(CStringRef message) - : std::runtime_error(message.c_str()) {} - FormatError(const FormatError &ferr) : std::runtime_error(ferr) {} + : std::runtime_error(message.c_str()) + { + } + FormatError(const FormatError &ferr) + : std::runtime_error(ferr) + { + } FMT_API ~FormatError() FMT_DTOR_NOEXCEPT FMT_OVERRIDE; }; -namespace internal -{ +namespace internal { // MakeUnsigned::Type gives an unsigned type corresponding to integer type T. -template -struct MakeUnsigned +template struct MakeUnsigned { typedef T Type; }; -#define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \ - template <> \ - struct MakeUnsigned { typedef U Type; } +#define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \ + template <> struct MakeUnsigned \ + { \ + typedef U Type; \ + } FMT_SPECIALIZE_MAKE_UNSIGNED(char, unsigned char); FMT_SPECIALIZE_MAKE_UNSIGNED(signed char, unsigned char); @@ -772,8 +760,7 @@ FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long); FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong); // Casts nonnegative integer to unsigned. -template -inline typename MakeUnsigned::Type to_unsigned(Int value) +template inline typename MakeUnsigned::Type to_unsigned(Int value) { FMT_ASSERT(value >= 0, "negative value"); return static_cast::Type>(value); @@ -781,31 +768,31 @@ inline typename MakeUnsigned::Type to_unsigned(Int value) // The number of characters to store in the MemoryBuffer object itself // to avoid dynamic memory allocation. -enum { INLINE_BUFFER_SIZE = 500 }; +enum +{ + INLINE_BUFFER_SIZE = 500 +}; #if FMT_SECURE_SCL // Use checked iterator to avoid warnings on MSVC. -template -inline stdext::checked_array_iterator make_ptr(T *ptr, std::size_t size) +template inline stdext::checked_array_iterator make_ptr(T *ptr, std::size_t size) { - return stdext::checked_array_iterator(ptr, size); + return stdext::checked_array_iterator(ptr, size); } #else -template -inline T *make_ptr(T *ptr, std::size_t) +template inline T *make_ptr(T *ptr, std::size_t) { return ptr; } #endif -} // namespace internal +} // namespace internal /** \rst A buffer supporting a subset of ``std::vector``'s operations. \endrst */ -template -class Buffer +template class Buffer { private: FMT_DISALLOW_COPY_AND_ASSIGN(Buffer); @@ -816,7 +803,11 @@ protected: std::size_t capacity_; Buffer(T *ptr = FMT_NULL, std::size_t capacity = 0) - : ptr_(ptr), size_(0), capacity_(capacity) {} + : ptr_(ptr) + , size_(0) + , capacity_(capacity) + { + } /** \rst @@ -862,7 +853,10 @@ public: grow(capacity); } - void clear() FMT_NOEXCEPT { size_ = 0; } + void clear() FMT_NOEXCEPT + { + size_ = 0; + } void push_back(const T &value) { @@ -872,8 +866,7 @@ public: } /** Appends data to the end of the buffer. */ - template - void append(const U *begin, const U *end); + template void append(const U *begin, const U *end); T &operator[](std::size_t index) { @@ -885,26 +878,21 @@ public: } }; -template -template -void Buffer::append(const U *begin, const U *end) +template template void Buffer::append(const U *begin, const U *end) { FMT_ASSERT(end >= begin, "negative value"); std::size_t new_size = size_ + static_cast(end - begin); if (new_size > capacity_) grow(new_size); - std::uninitialized_copy(begin, end, - internal::make_ptr(ptr_, capacity_) + size_); + std::uninitialized_copy(begin, end, internal::make_ptr(ptr_, capacity_) + size_); size_ = new_size; } -namespace internal -{ +namespace internal { // A memory buffer for trivially copyable/constructible types with the first // SIZE elements stored in the object itself. -template > -class MemoryBuffer : private Allocator, public Buffer +template > class MemoryBuffer : private Allocator, public Buffer { private: T data_[SIZE]; @@ -912,7 +900,8 @@ private: // Deallocate memory allocated by the buffer. void deallocate() { - if (this->ptr_ != data_) Allocator::deallocate(this->ptr_, this->capacity_); + if (this->ptr_ != data_) + Allocator::deallocate(this->ptr_, this->capacity_); } protected: @@ -920,8 +909,14 @@ protected: public: explicit MemoryBuffer(const Allocator &alloc = Allocator()) - : Allocator(alloc), Buffer(data_, SIZE) {} - ~MemoryBuffer() FMT_OVERRIDE { deallocate(); } + : Allocator(alloc) + , Buffer(data_, SIZE) + { + } + ~MemoryBuffer() FMT_OVERRIDE + { + deallocate(); + } #if FMT_USE_RVALUE_REFERENCES private: @@ -935,8 +930,7 @@ private: if (other.ptr_ == other.data_) { this->ptr_ = data_; - std::uninitialized_copy(other.data_, other.data_ + this->size_, - make_ptr(data_, this->capacity_)); + std::uninitialized_copy(other.data_, other.data_ + this->size_, make_ptr(data_, this->capacity_)); } else { @@ -969,21 +963,18 @@ public: } }; -template -void MemoryBuffer::grow(std::size_t size) +template void MemoryBuffer::grow(std::size_t size) { std::size_t new_capacity = this->capacity_ + this->capacity_ / 2; if (size > new_capacity) new_capacity = size; #if FMT_USE_ALLOCATOR_TRAITS - T *new_ptr = - std::allocator_traits::allocate(*this, new_capacity, FMT_NULL); + T *new_ptr = std::allocator_traits::allocate(*this, new_capacity, FMT_NULL); #else T *new_ptr = this->allocate(new_capacity, FMT_NULL); #endif // The following code doesn't throw, so the raw pointer above doesn't leak. - std::uninitialized_copy(this->ptr_, this->ptr_ + this->size_, - make_ptr(new_ptr, new_capacity)); + std::uninitialized_copy(this->ptr_, this->ptr_ + this->size_, make_ptr(new_ptr, new_capacity)); std::size_t old_capacity = this->capacity_; T *old_ptr = this->ptr_; this->capacity_ = new_capacity; @@ -996,22 +987,23 @@ void MemoryBuffer::grow(std::size_t size) } // A fixed-size buffer. -template -class FixedBuffer : public fmt::Buffer +template class FixedBuffer : public fmt::Buffer { public: - FixedBuffer(Char *array, std::size_t size) : fmt::Buffer(array, size) {} + FixedBuffer(Char *array, std::size_t size) + : fmt::Buffer(array, size) + { + } protected: FMT_API void grow(std::size_t size) FMT_OVERRIDE; }; -template -class BasicCharTraits +template class BasicCharTraits { public: #if FMT_SECURE_SCL - typedef stdext::checked_array_iterator CharPtr; + typedef stdext::checked_array_iterator CharPtr; #else typedef Char *CharPtr; #endif @@ -1021,11 +1013,9 @@ public: } }; -template -class CharTraits; +template class CharTraits; -template <> -class CharTraits : public BasicCharTraits +template <> class CharTraits : public BasicCharTraits { private: // Conversion from wchar_t to char is not allowed. @@ -1039,21 +1029,17 @@ public: // Formats a floating-point number. template - FMT_API static int format_float(char *buffer, std::size_t size, - const char *format, unsigned width, int precision, T value); + FMT_API static int format_float(char *buffer, std::size_t size, const char *format, unsigned width, int precision, T value); }; #if FMT_USE_EXTERN_TEMPLATES -extern template int CharTraits::format_float -(char *buffer, std::size_t size, - const char* format, unsigned width, int precision, double value); -extern template int CharTraits::format_float -(char *buffer, std::size_t size, - const char* format, unsigned width, int precision, long double value); +extern template int CharTraits::format_float( + char *buffer, std::size_t size, const char *format, unsigned width, int precision, double value); +extern template int CharTraits::format_float( + char *buffer, std::size_t size, const char *format, unsigned width, int precision, long double value); #endif -template <> -class CharTraits : public BasicCharTraits +template <> class CharTraits : public BasicCharTraits { public: static wchar_t convert(char value) @@ -1066,35 +1052,28 @@ public: } template - FMT_API static int format_float(wchar_t *buffer, std::size_t size, - const wchar_t *format, unsigned width, int precision, T value); + FMT_API static int format_float(wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, T value); }; #if FMT_USE_EXTERN_TEMPLATES -extern template int CharTraits::format_float -(wchar_t *buffer, std::size_t size, - const wchar_t* format, unsigned width, int precision, double value); -extern template int CharTraits::format_float -(wchar_t *buffer, std::size_t size, - const wchar_t* format, unsigned width, int precision, long double value); +extern template int CharTraits::format_float( + wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, double value); +extern template int CharTraits::format_float( + wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, long double value); #endif // Checks if a number is negative - used to avoid warnings. -template -struct SignChecker +template struct SignChecker { - template - static bool is_negative(T value) + template static bool is_negative(T value) { return value < 0; } }; -template <> -struct SignChecker +template <> struct SignChecker { - template - static bool is_negative(T) + template static bool is_negative(T) { return false; } @@ -1102,40 +1081,34 @@ struct SignChecker // Returns true if value is negative, false otherwise. // Same as (value < 0) but doesn't produce warnings if T is an unsigned type. -template -inline bool is_negative(T value) +template inline bool is_negative(T value) { return SignChecker::is_signed>::is_negative(value); } // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise. -template -struct TypeSelector +template struct TypeSelector { typedef uint32_t Type; }; -template <> -struct TypeSelector +template <> struct TypeSelector { typedef uint64_t Type; }; -template -struct IntTraits +template struct IntTraits { // Smallest of uint32_t and uint64_t that is large enough to represent // all values of T. - typedef typename - TypeSelector::digits <= 32>::Type MainType; + typedef typename TypeSelector::digits <= 32>::Type MainType; }; FMT_API FMT_NORETURN void report_unknown_type(char code, const char *type); // Static data is placed in this class template to allow header-only // configuration. -template -struct FMT_API BasicData +template struct FMT_API BasicData { static const uint32_t POWERS_OF_10_32[]; static const uint64_t POWERS_OF_10_64[]; @@ -1168,10 +1141,14 @@ inline unsigned count_digits(uint64_t n) // Integer division is slow so do it for a group of four digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. - if (n < 10) return count; - if (n < 100) return count + 1; - if (n < 1000) return count + 2; - if (n < 10000) return count + 3; + if (n < 10) + return count; + if (n < 100) + return count + 1; + if (n < 1000) + return count + 2; + if (n < 10000) + return count + 3; n /= 10000u; count += 4; } @@ -1190,8 +1167,7 @@ inline unsigned count_digits(uint32_t n) // A functor that doesn't add a thousands separator. struct NoThousandsSep { - template - void operator()(Char *) {} + template void operator()(Char *) {} }; // A functor that adds a thousands separator. @@ -1204,16 +1180,18 @@ private: unsigned digit_index_; public: - explicit ThousandsSep(fmt::StringRef sep) : sep_(sep), digit_index_(0) {} + explicit ThousandsSep(fmt::StringRef sep) + : sep_(sep) + , digit_index_(0) + { + } - template - void operator()(Char *&buffer) + template void operator()(Char *&buffer) { if (++digit_index_ % 3 != 0) return; buffer -= sep_.size(); - std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(), - internal::make_ptr(buffer, sep_.size())); + std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(), internal::make_ptr(buffer, sep_.size())); } }; @@ -1221,8 +1199,7 @@ public: // thousands_sep is a functor that is called after writing each char to // add a thousands separator if necessary. template -inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, - ThousandsSep thousands_sep) +inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, ThousandsSep thousands_sep) { buffer += num_digits; while (value >= 100) @@ -1248,17 +1225,16 @@ inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, *--buffer = Data::DIGITS[index]; } -template -inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) +template inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) { format_decimal(buffer, value, num_digits, NoThousandsSep()); return; } #ifndef _WIN32 -# define FMT_USE_WINDOWS_H 0 +#define FMT_USE_WINDOWS_H 0 #elif !defined(FMT_USE_WINDOWS_H) -# define FMT_USE_WINDOWS_H 1 +#define FMT_USE_WINDOWS_H 1 #endif // Define FMT_USE_WINDOWS_H to 0 to disable use of windows.h. @@ -1324,22 +1300,19 @@ public: FMT_API int convert(WStringRef s); }; -FMT_API void format_windows_error(fmt::Writer &out, int error_code, - fmt::StringRef message) FMT_NOEXCEPT; +FMT_API void format_windows_error(fmt::Writer &out, int error_code, fmt::StringRef message) FMT_NOEXCEPT; #endif // A formatting argument value. struct Value { - template - struct StringValue + template struct StringValue { const Char *value; std::size_t size; }; - typedef void (*FormatFunc)( - void *formatter, const void *arg, void *format_str_ptr); + typedef void (*FormatFunc)(void *formatter, const void *arg, void *format_str_ptr); struct CustomValue { @@ -1365,12 +1338,25 @@ struct Value enum Type { - NONE, NAMED_ARG, + NONE, + NAMED_ARG, // Integer types should go first, - INT, UINT, LONG_LONG, ULONG_LONG, BOOL, CHAR, LAST_INTEGER_TYPE = CHAR, + INT, + UINT, + LONG_LONG, + ULONG_LONG, + BOOL, + CHAR, + LAST_INTEGER_TYPE = CHAR, // followed by floating-point types. - DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE, - CSTRING, STRING, WSTRING, POINTER, CUSTOM + DOUBLE, + LONG_DOUBLE, + LAST_NUMERIC_TYPE = LONG_DOUBLE, + CSTRING, + STRING, + WSTRING, + POINTER, + CUSTOM }; }; @@ -1381,25 +1367,22 @@ struct Arg : Value Type type; }; -template -struct NamedArg; -template -struct NamedArgWithType; +template struct NamedArg; +template struct NamedArgWithType; -template -struct Null {}; +template struct Null +{ +}; // A helper class template to enable or disable overloads taking wide // characters and strings in MakeValue. -template -struct WCharHelper +template struct WCharHelper { typedef Null Supported; typedef T Unsupported; }; -template -struct WCharHelper +template struct WCharHelper { typedef T Supported; typedef Null Unsupported; @@ -1408,27 +1391,29 @@ struct WCharHelper typedef char Yes[1]; typedef char No[2]; -template -T &get(); +template T &get(); // These are non-members to workaround an overload resolution bug in bcc32. Yes &convert(fmt::ULongLong); No &convert(...); -template -struct ConvertToIntImpl +template struct ConvertToIntImpl { - enum { value = ENABLE_CONVERSION }; + enum + { + value = ENABLE_CONVERSION + }; }; -template -struct ConvertToIntImpl2 +template struct ConvertToIntImpl2 { - enum { value = false }; + enum + { + value = false + }; }; -template -struct ConvertToIntImpl2 +template struct ConvertToIntImpl2 { enum { @@ -1437,63 +1422,74 @@ struct ConvertToIntImpl2 }; }; -template -struct ConvertToInt +template struct ConvertToInt { enum { enable_conversion = sizeof(fmt::internal::convert(get())) == sizeof(Yes) }; - enum { value = ConvertToIntImpl2::value }; + enum + { + value = ConvertToIntImpl2::value + }; }; -#define FMT_DISABLE_CONVERSION_TO_INT(Type) \ - template <> \ - struct ConvertToInt { enum { value = 0 }; } +#define FMT_DISABLE_CONVERSION_TO_INT(Type) \ + template <> struct ConvertToInt \ + { \ + enum \ + { \ + value = 0 \ + }; \ + } // Silence warnings about convering float to int. FMT_DISABLE_CONVERSION_TO_INT(float); FMT_DISABLE_CONVERSION_TO_INT(double); FMT_DISABLE_CONVERSION_TO_INT(long double); -template -struct EnableIf {}; +template struct EnableIf +{ +}; -template -struct EnableIf +template struct EnableIf { typedef T type; }; -template -struct Conditional +template struct Conditional { typedef T type; }; -template -struct Conditional +template struct Conditional { typedef F type; }; // For bcc32 which doesn't understand ! in template arguments. -template -struct Not +template struct Not { - enum { value = 0 }; + enum + { + value = 0 + }; }; -template <> -struct Not +template <> struct Not { - enum { value = 1 }; + enum + { + value = 1 + }; }; -template -struct FalseType +template struct FalseType { - enum { value = 0 }; + enum + { + value = 0 + }; }; template struct LConvCheck @@ -1504,9 +1500,7 @@ template struct LConvCheck // Returns the thousands separator for the current locale. // We check if ``lconv`` contains ``thousands_sep`` because on Android // ``lconv`` is stubbed as an empty struct. -template -inline StringRef thousands_sep( - LConv *lc, LConvCheck = 0) +template inline StringRef thousands_sep(LConv *lc, LConvCheck = 0) { return lc->thousands_sep; } @@ -1519,36 +1513,31 @@ inline fmt::StringRef thousands_sep(...) #define FMT_CONCAT(a, b) a##b #if FMT_GCC_VERSION >= 303 -# define FMT_UNUSED __attribute__((unused)) +#define FMT_UNUSED __attribute__((unused)) #else -# define FMT_UNUSED +#define FMT_UNUSED #endif #ifndef FMT_USE_STATIC_ASSERT -# define FMT_USE_STATIC_ASSERT 0 +#define FMT_USE_STATIC_ASSERT 0 #endif -#if FMT_USE_STATIC_ASSERT || FMT_HAS_FEATURE(cxx_static_assert) || \ - (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1600 -# define FMT_STATIC_ASSERT(cond, message) static_assert(cond, message) +#if FMT_USE_STATIC_ASSERT || FMT_HAS_FEATURE(cxx_static_assert) || (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1600 +#define FMT_STATIC_ASSERT(cond, message) static_assert(cond, message) #else -# define FMT_CONCAT_(a, b) FMT_CONCAT(a, b) -# define FMT_STATIC_ASSERT(cond, message) \ - typedef int FMT_CONCAT_(Assert, __LINE__)[(cond) ? 1 : -1] FMT_UNUSED +#define FMT_CONCAT_(a, b) FMT_CONCAT(a, b) +#define FMT_STATIC_ASSERT(cond, message) typedef int FMT_CONCAT_(Assert, __LINE__)[(cond) ? 1 : -1] FMT_UNUSED #endif -template -void format_arg(Formatter&, ...) +template void format_arg(Formatter &, ...) { - FMT_STATIC_ASSERT(FalseType::value, - "Cannot format argument. To enable the use of ostream " - "operator<< include fmt/ostream.h. Otherwise provide " - "an overload of format_arg."); + FMT_STATIC_ASSERT(FalseType::value, "Cannot format argument. To enable the use of ostream " + "operator<< include fmt/ostream.h. Otherwise provide " + "an overload of format_arg."); } // Makes an Arg object from any type. -template -class MakeValue : public Arg +template class MakeValue : public Arg { public: typedef typename Formatter::Char Char; @@ -1559,10 +1548,8 @@ private: // "void *" or "const void *". In particular, this forbids formatting // of "[const] volatile char *" which is printed as bool by iostreams. // Do not implement! - template - MakeValue(const T *value); - template - MakeValue(T *value); + template MakeValue(const T *value); + template MakeValue(T *value); // The following methods are private to disallow formatting of wide // characters and strings into narrow strings as in @@ -1592,24 +1579,25 @@ private: } // Formats an argument of a custom type, such as a user-defined class. - template - static void format_custom_arg( - void *formatter, const void *arg, void *format_str_ptr) + template static void format_custom_arg(void *formatter, const void *arg, void *format_str_ptr) { - format_arg(*static_cast(formatter), - *static_cast(format_str_ptr), - *static_cast(arg)); + format_arg(*static_cast(formatter), *static_cast(format_str_ptr), *static_cast(arg)); } public: MakeValue() {} -#define FMT_MAKE_VALUE_(Type, field, TYPE, rhs) \ - MakeValue(Type value) { field = rhs; } \ - static uint64_t type(Type) { return Arg::TYPE; } +#define FMT_MAKE_VALUE_(Type, field, TYPE, rhs) \ + MakeValue(Type value) \ + { \ + field = rhs; \ + } \ + static uint64_t type(Type) \ + { \ + return Arg::TYPE; \ + } -#define FMT_MAKE_VALUE(Type, field, TYPE) \ - FMT_MAKE_VALUE_(Type, field, TYPE, value) +#define FMT_MAKE_VALUE(Type, field, TYPE) FMT_MAKE_VALUE_(Type, field, TYPE, value) FMT_MAKE_VALUE(bool, int_value, BOOL) FMT_MAKE_VALUE(short, int_value, INT) @@ -1640,8 +1628,7 @@ public: } static uint64_t type(unsigned long) { - return sizeof(unsigned long) == sizeof(unsigned) ? - Arg::UINT : Arg::ULONG_LONG; + return sizeof(unsigned long) == sizeof(unsigned) ? Arg::UINT : Arg::ULONG_LONG; } FMT_MAKE_VALUE(LongLong, long_long_value, LONG_LONG) @@ -1654,19 +1641,12 @@ public: FMT_MAKE_VALUE(char, int_value, CHAR) #if __cplusplus >= 201103L - template < - typename T, - typename = typename std::enable_if< - std::is_enum::value && ConvertToInt::value>::type> - MakeValue(T value) + template ::value && ConvertToInt::value>::type> MakeValue(T value) { int_value = value; } - template < - typename T, - typename = typename std::enable_if< - std::is_enum::value && ConvertToInt::value>::type> + template ::value && ConvertToInt::value>::type> static uint64_t type(T) { return Arg::INT; @@ -1684,9 +1664,15 @@ public: } #endif -#define FMT_MAKE_STR_VALUE(Type, TYPE) \ - MakeValue(Type value) { set_string(value); } \ - static uint64_t type(Type) { return Arg::TYPE; } +#define FMT_MAKE_STR_VALUE(Type, TYPE) \ + MakeValue(Type value) \ + { \ + set_string(value); \ + } \ + static uint64_t type(Type) \ + { \ + return Arg::TYPE; \ + } FMT_MAKE_VALUE(char *, string.value, CSTRING) FMT_MAKE_VALUE(const char *, string.value, CSTRING) @@ -1701,11 +1687,15 @@ public: FMT_MAKE_STR_VALUE(StringRef, STRING) FMT_MAKE_VALUE_(CStringRef, string.value, CSTRING, value.c_str()) -#define FMT_MAKE_WSTR_VALUE(Type, TYPE) \ - MakeValue(typename WCharHelper::Supported value) { \ - set_string(value); \ - } \ - static uint64_t type(Type) { return Arg::TYPE; } +#define FMT_MAKE_WSTR_VALUE(Type, TYPE) \ + MakeValue(typename WCharHelper::Supported value) \ + { \ + set_string(value); \ + } \ + static uint64_t type(Type) \ + { \ + return Arg::TYPE; \ + } FMT_MAKE_WSTR_VALUE(wchar_t *, WSTRING) FMT_MAKE_WSTR_VALUE(const wchar_t *, WSTRING) @@ -1718,49 +1708,39 @@ public: FMT_MAKE_VALUE(void *, pointer, POINTER) FMT_MAKE_VALUE(const void *, pointer, POINTER) - template - MakeValue(const T &value, - typename EnableIf::value>::value, int>::type = 0) + template MakeValue(const T &value, typename EnableIf::value>::value, int>::type = 0) { custom.value = &value; custom.format = &format_custom_arg; } - template - static typename EnableIf::value>::value, uint64_t>::type - type(const T &) + template static typename EnableIf::value>::value, uint64_t>::type type(const T &) { return Arg::CUSTOM; } // Additional template param `Char_` is needed here because make_type always // uses char. - template - MakeValue(const NamedArg &value) + template MakeValue(const NamedArg &value) { pointer = &value; } - template - MakeValue(const NamedArgWithType &value) + template MakeValue(const NamedArgWithType &value) { pointer = &value; } - template - static uint64_t type(const NamedArg &) + template static uint64_t type(const NamedArg &) { return Arg::NAMED_ARG; } - template - static uint64_t type(const NamedArgWithType &) + template static uint64_t type(const NamedArgWithType &) { return Arg::NAMED_ARG; } }; -template -class MakeArg : public Arg +template class MakeArg : public Arg { public: MakeArg() @@ -1776,34 +1756,42 @@ public: } }; -template -struct NamedArg : Arg +template struct NamedArg : Arg { BasicStringRef name; template NamedArg(BasicStringRef argname, const T &value) - : Arg(MakeArg< BasicFormatter >(value)), name(argname) {} + : Arg(MakeArg>(value)) + , name(argname) + { + } }; -template -struct NamedArgWithType : NamedArg +template struct NamedArgWithType : NamedArg { NamedArgWithType(BasicStringRef argname, const T &value) - : NamedArg(argname, value) {} + : NamedArg(argname, value) + { + } }; class RuntimeError : public std::runtime_error { protected: - RuntimeError() : std::runtime_error("") {} - RuntimeError(const RuntimeError &rerr) : std::runtime_error(rerr) {} + RuntimeError() + : std::runtime_error("") + { + } + RuntimeError(const RuntimeError &rerr) + : std::runtime_error(rerr) + { + } FMT_API ~RuntimeError() FMT_DTOR_NOEXCEPT FMT_OVERRIDE; }; -template -class ArgMap; -} // namespace internal +template class ArgMap; +} // namespace internal /** An argument list. */ class ArgList @@ -1828,19 +1816,30 @@ private: return type(types_, index); } - template - friend class internal::ArgMap; + template friend class internal::ArgMap; public: // Maximum number of arguments with packed types. - enum { MAX_PACKED_ARGS = 16 }; + enum + { + MAX_PACKED_ARGS = 16 + }; - ArgList() : types_(0) {} + ArgList() + : types_(0) + { + } ArgList(ULongLong types, const internal::Value *values) - : types_(types), values_(values) {} + : types_(types) + , values_(values) + { + } ArgList(ULongLong types, const internal::Arg *args) - : types_(types), args_(args) {} + : types_(types) + , args_(args) + { + } uint64_t types() const { @@ -1881,12 +1880,11 @@ public: { unsigned shift = index * 4; uint64_t mask = 0xf; - return static_cast( - (types & (mask << shift)) >> shift); + return static_cast((types & (mask << shift)) >> shift); } }; -#define FMT_DISPATCH(call) static_cast(this)->call +#define FMT_DISPATCH(call) static_cast(this)->call /** \rst @@ -1912,8 +1910,7 @@ public: }; \endrst */ -template -class ArgVisitor +template class ArgVisitor { private: typedef internal::Arg Arg; @@ -1964,8 +1961,7 @@ public: } /** Visits an argument of any integral type. **/ - template - Result visit_any_int(T) + template Result visit_any_int(T) { return FMT_DISPATCH(visit_unhandled_arg()); } @@ -1983,8 +1979,7 @@ public: } /** Visits a ``double`` or ``long double`` argument. **/ - template - Result visit_any_double(T) + template Result visit_any_double(T) { return FMT_DISPATCH(visit_unhandled_arg()); } @@ -2068,22 +2063,30 @@ public: enum Alignment { - ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC + ALIGN_DEFAULT, + ALIGN_LEFT, + ALIGN_RIGHT, + ALIGN_CENTER, + ALIGN_NUMERIC }; // Flags. enum { - SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8, - CHAR_FLAG = 0x10 // Argument has char type - used in error reporting. + SIGN_FLAG = 1, + PLUS_FLAG = 2, + MINUS_FLAG = 4, + HASH_FLAG = 8, + CHAR_FLAG = 0x10 // Argument has char type - used in error reporting. }; // An empty format specifier. -struct EmptySpec {}; +struct EmptySpec +{ +}; // A type specifier. -template -struct TypeSpec : EmptySpec +template struct TypeSpec : EmptySpec { Alignment align() const { @@ -2123,7 +2126,11 @@ struct WidthSpec // two specialization of WidthSpec and its subclasses. wchar_t fill_; - WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {} + WidthSpec(unsigned width, wchar_t fill) + : width_(width) + , fill_(fill) + { + } unsigned width() const { @@ -2141,7 +2148,10 @@ struct AlignSpec : WidthSpec Alignment align_; AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT) - : WidthSpec(width, fill), align_(align) {} + : WidthSpec(width, fill) + , align_(align) + { + } Alignment align() const { @@ -2155,10 +2165,12 @@ struct AlignSpec : WidthSpec }; // An alignment and type specifier. -template -struct AlignTypeSpec : AlignSpec +template struct AlignTypeSpec : AlignSpec { - AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {} + AlignTypeSpec(unsigned width, wchar_t fill) + : AlignSpec(width, fill) + { + } bool flag(unsigned) const { @@ -2181,9 +2193,13 @@ struct FormatSpec : AlignSpec int precision_; char type_; - FormatSpec( - unsigned width = 0, char type = 0, wchar_t fill = ' ') - : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {} + FormatSpec(unsigned width = 0, char type = 0, wchar_t fill = ' ') + : AlignSpec(width, fill) + , flags_(0) + , precision_(-1) + , type_(type) + { + } bool flag(unsigned f) const { @@ -2204,15 +2220,17 @@ struct FormatSpec : AlignSpec }; // An integer format specifier. -template , typename Char = char> -class IntFormatSpec : public SpecT +template , typename Char = char> class IntFormatSpec : public SpecT { private: T value_; public: IntFormatSpec(T val, const SpecT &spec = SpecT()) - : SpecT(spec), value_(val) {} + : SpecT(spec) + , value_(val) + { + } T value() const { @@ -2221,8 +2239,7 @@ public: }; // A string format specifier. -template -class StrFormatSpec : public AlignSpec +template class StrFormatSpec : public AlignSpec { private: const Char *str_; @@ -2230,7 +2247,8 @@ private: public: template StrFormatSpec(const Char *str, unsigned width, FillChar fill) - : AlignSpec(width, fill), str_(str) + : AlignSpec(width, fill) + , str_(str) { internal::CharTraits::convert(FillChar()); } @@ -2244,24 +2262,24 @@ public: /** Returns an integer format specifier to format the value in base 2. */ -IntFormatSpec > bin(int value); +IntFormatSpec> bin(int value); /** Returns an integer format specifier to format the value in base 8. */ -IntFormatSpec > oct(int value); +IntFormatSpec> oct(int value); /** Returns an integer format specifier to format the value in base 16 using lower-case letters for the digits above 9. */ -IntFormatSpec > hex(int value); +IntFormatSpec> hex(int value); /** Returns an integer formatter format specifier to format in base 16 using upper-case letters for the digits above 9. */ -IntFormatSpec > hexu(int value); +IntFormatSpec> hexu(int value); /** \rst @@ -2277,58 +2295,55 @@ IntFormatSpec > hexu(int value); \endrst */ -template -IntFormatSpec, Char> pad( - int value, unsigned width, Char fill = ' '); - -#define FMT_DEFINE_INT_FORMATTERS(TYPE) \ -inline IntFormatSpec > bin(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'b'>()); \ -} \ - \ -inline IntFormatSpec > oct(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'o'>()); \ -} \ - \ -inline IntFormatSpec > hex(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'x'>()); \ -} \ - \ -inline IntFormatSpec > hexu(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'X'>()); \ -} \ - \ -template \ -inline IntFormatSpec > pad( \ - IntFormatSpec > f, unsigned width) { \ - return IntFormatSpec >( \ - f.value(), AlignTypeSpec(width, ' ')); \ -} \ - \ -/* For compatibility with older compilers we provide two overloads for pad, */ \ -/* one that takes a fill character and one that doesn't. In the future this */ \ -/* can be replaced with one overload making the template argument Char */ \ -/* default to char (C++11). */ \ -template \ -inline IntFormatSpec, Char> pad( \ - IntFormatSpec, Char> f, \ - unsigned width, Char fill) { \ - return IntFormatSpec, Char>( \ - f.value(), AlignTypeSpec(width, fill)); \ -} \ - \ -inline IntFormatSpec > pad( \ - TYPE value, unsigned width) { \ - return IntFormatSpec >( \ - value, AlignTypeSpec<0>(width, ' ')); \ -} \ - \ -template \ -inline IntFormatSpec, Char> pad( \ - TYPE value, unsigned width, Char fill) { \ - return IntFormatSpec, Char>( \ - value, AlignTypeSpec<0>(width, fill)); \ -} +template IntFormatSpec, Char> pad(int value, unsigned width, Char fill = ' '); + +#define FMT_DEFINE_INT_FORMATTERS(TYPE) \ + inline IntFormatSpec> bin(TYPE value) \ + { \ + return IntFormatSpec>(value, TypeSpec<'b'>()); \ + } \ + \ + inline IntFormatSpec> oct(TYPE value) \ + { \ + return IntFormatSpec>(value, TypeSpec<'o'>()); \ + } \ + \ + inline IntFormatSpec> hex(TYPE value) \ + { \ + return IntFormatSpec>(value, TypeSpec<'x'>()); \ + } \ + \ + inline IntFormatSpec> hexu(TYPE value) \ + { \ + return IntFormatSpec>(value, TypeSpec<'X'>()); \ + } \ + \ + template \ + inline IntFormatSpec> pad(IntFormatSpec> f, unsigned width) \ + { \ + return IntFormatSpec>(f.value(), AlignTypeSpec(width, ' ')); \ + } \ + \ + /* For compatibility with older compilers we provide two overloads for pad, */ \ + /* one that takes a fill character and one that doesn't. In the future this */ \ + /* can be replaced with one overload making the template argument Char */ \ + /* default to char (C++11). */ \ + template \ + inline IntFormatSpec, Char> pad( \ + IntFormatSpec, Char> f, unsigned width, Char fill) \ + { \ + return IntFormatSpec, Char>(f.value(), AlignTypeSpec(width, fill)); \ + } \ + \ + inline IntFormatSpec> pad(TYPE value, unsigned width) \ + { \ + return IntFormatSpec>(value, AlignTypeSpec<0>(width, ' ')); \ + } \ + \ + template inline IntFormatSpec, Char> pad(TYPE value, unsigned width, Char fill) \ + { \ + return IntFormatSpec, Char>(value, AlignTypeSpec<0>(width, fill)); \ + } FMT_DEFINE_INT_FORMATTERS(int) FMT_DEFINE_INT_FORMATTERS(long) @@ -2349,28 +2364,22 @@ FMT_DEFINE_INT_FORMATTERS(ULongLong) \endrst */ -template -inline StrFormatSpec pad( - const Char *str, unsigned width, Char fill = ' ') +template inline StrFormatSpec pad(const Char *str, unsigned width, Char fill = ' ') { return StrFormatSpec(str, width, fill); } -inline StrFormatSpec pad( - const wchar_t *str, unsigned width, char fill = ' ') +inline StrFormatSpec pad(const wchar_t *str, unsigned width, char fill = ' ') { return StrFormatSpec(str, width, fill); } -namespace internal -{ +namespace internal { -template -class ArgMap +template class ArgMap { private: - typedef std::vector< - std::pair, internal::Arg> > MapType; + typedef std::vector, internal::Arg>> MapType; typedef typename MapType::value_type Pair; MapType map_; @@ -2381,8 +2390,7 @@ public: const internal::Arg *find(const fmt::BasicStringRef &name) const { // The list is unsorted, so just return the first matching name. - for (typename MapType::const_iterator it = map_.begin(), end = map_.end(); - it != end; ++it) + for (typename MapType::const_iterator it = map_.begin(), end = map_.end(); it != end; ++it) { if (it->first == name) return &it->second; @@ -2391,18 +2399,16 @@ public: } }; -template -void ArgMap::init(const ArgList &args) +template void ArgMap::init(const ArgList &args) { if (!map_.empty()) return; typedef internal::NamedArg NamedArg; const NamedArg *named_arg = FMT_NULL; - bool use_values = - args.type(ArgList::MAX_PACKED_ARGS - 1) == internal::Arg::NONE; + bool use_values = args.type(ArgList::MAX_PACKED_ARGS - 1) == internal::Arg::NONE; if (use_values) { - for (unsigned i = 0;/*nothing*/; ++i) + for (unsigned i = 0; /*nothing*/; ++i) { internal::Arg::Type arg_type = args.type(i); switch (arg_type) @@ -2410,7 +2416,7 @@ void ArgMap::init(const ArgList &args) case internal::Arg::NONE: return; case internal::Arg::NAMED_ARG: - named_arg = static_cast(args.values_[i].pointer); + named_arg = static_cast(args.values_[i].pointer); map_.push_back(Pair(named_arg->name, *named_arg)); break; default: @@ -2425,18 +2431,18 @@ void ArgMap::init(const ArgList &args) internal::Arg::Type arg_type = args.type(i); if (arg_type == internal::Arg::NAMED_ARG) { - named_arg = static_cast(args.args_[i].pointer); + named_arg = static_cast(args.args_[i].pointer); map_.push_back(Pair(named_arg->name, *named_arg)); } } - for (unsigned i = ArgList::MAX_PACKED_ARGS;/*nothing*/; ++i) + for (unsigned i = ArgList::MAX_PACKED_ARGS; /*nothing*/; ++i) { switch (args.args_[i].type) { case internal::Arg::NONE: return; case internal::Arg::NAMED_ARG: - named_arg = static_cast(args.args_[i].pointer); + named_arg = static_cast(args.args_[i].pointer); map_.push_back(Pair(named_arg->name, *named_arg)); break; default: @@ -2446,8 +2452,7 @@ void ArgMap::init(const ArgList &args) } } -template -class ArgFormatterBase : public ArgVisitor +template class ArgFormatterBase : public ArgVisitor { private: BasicWriter &writer_; @@ -2478,7 +2483,7 @@ protected: void write(bool value) { const char *str_value = value ? "true" : "false"; - Arg::StringValue str = { str_value, std::strlen(str_value) }; + Arg::StringValue str = {str_value, std::strlen(str_value)}; writer_.write_str(str, spec_); } @@ -2492,16 +2497,17 @@ public: typedef Spec SpecType; ArgFormatterBase(BasicWriter &w, Spec &s) - : writer_(w), spec_(s) {} + : writer_(w) + , spec_(s) + { + } - template - void visit_any_int(T value) + template void visit_any_int(T value) { writer_.write_int(value, spec_); } - template - void visit_any_double(T value) + template void visit_any_double(T value) { writer_.write_double(value, spec_); } @@ -2540,13 +2546,11 @@ public: } else if (spec_.align_ == ALIGN_CENTER) { - out = writer_.fill_padding(out, spec_.width_, - internal::const_check(CHAR_SIZE), fill); + out = writer_.fill_padding(out, spec_.width_, internal::const_check(CHAR_SIZE), fill); } else { - std::uninitialized_fill_n(out + CHAR_SIZE, - spec_.width_ - CHAR_SIZE, fill); + std::uninitialized_fill_n(out + CHAR_SIZE, spec_.width_ - CHAR_SIZE, fill); } } else @@ -2632,14 +2636,13 @@ protected: return true; } - template - void write(BasicWriter &w, const Char *start, const Char *end) + template void write(BasicWriter &w, const Char *start, const Char *end) { if (start != end) w << BasicStringRef(start, internal::to_unsigned(end - start)); } }; -} // namespace internal +} // namespace internal /** \rst @@ -2674,10 +2677,12 @@ public: to the part of the format string being parsed for custom argument types. \endrst */ - BasicArgFormatter(BasicFormatter &formatter, - Spec &spec, const Char *fmt) - : internal::ArgFormatterBase(formatter.writer(), spec), - formatter_(formatter), format_(fmt) {} + BasicArgFormatter(BasicFormatter &formatter, Spec &spec, const Char *fmt) + : internal::ArgFormatterBase(formatter.writer(), spec) + , formatter_(formatter) + , format_(fmt) + { + } /** Formats an argument of a custom (user-defined) type. */ void visit_custom(internal::Arg::CustomValue c) @@ -2687,21 +2692,18 @@ public: }; /** The default argument formatter. */ -template -class ArgFormatter : - public BasicArgFormatter, Char, FormatSpec> +template class ArgFormatter : public BasicArgFormatter, Char, FormatSpec> { public: /** Constructs an argument formatter object. */ - ArgFormatter(BasicFormatter &formatter, - FormatSpec &spec, const Char *fmt) - : BasicArgFormatter, - Char, FormatSpec>(formatter, spec, fmt) {} + ArgFormatter(BasicFormatter &formatter, FormatSpec &spec, const Char *fmt) + : BasicArgFormatter, Char, FormatSpec>(formatter, spec, fmt) + { + } }; /** This template formats data and writes the output to a writer. */ -template -class BasicFormatter : private internal::FormatterBase +template class BasicFormatter : private internal::FormatterBase { public: /** The character type for the output. */ @@ -2734,7 +2736,10 @@ public: \endrst */ BasicFormatter(const ArgList &args, BasicWriter &w) - : internal::FormatterBase(args), writer_(w) {} + : internal::FormatterBase(args) + , writer_(w) + { + } /** Returns a reference to the writer associated with this formatter. */ BasicWriter &writer() @@ -2751,75 +2756,67 @@ public: // Generates a comma-separated list with results of applying f to // numbers 0..n-1. -# define FMT_GEN(n, f) FMT_GEN##n(f) -# define FMT_GEN1(f) f(0) -# define FMT_GEN2(f) FMT_GEN1(f), f(1) -# define FMT_GEN3(f) FMT_GEN2(f), f(2) -# define FMT_GEN4(f) FMT_GEN3(f), f(3) -# define FMT_GEN5(f) FMT_GEN4(f), f(4) -# define FMT_GEN6(f) FMT_GEN5(f), f(5) -# define FMT_GEN7(f) FMT_GEN6(f), f(6) -# define FMT_GEN8(f) FMT_GEN7(f), f(7) -# define FMT_GEN9(f) FMT_GEN8(f), f(8) -# define FMT_GEN10(f) FMT_GEN9(f), f(9) -# define FMT_GEN11(f) FMT_GEN10(f), f(10) -# define FMT_GEN12(f) FMT_GEN11(f), f(11) -# define FMT_GEN13(f) FMT_GEN12(f), f(12) -# define FMT_GEN14(f) FMT_GEN13(f), f(13) -# define FMT_GEN15(f) FMT_GEN14(f), f(14) - -namespace internal -{ +#define FMT_GEN(n, f) FMT_GEN##n(f) +#define FMT_GEN1(f) f(0) +#define FMT_GEN2(f) FMT_GEN1(f), f(1) +#define FMT_GEN3(f) FMT_GEN2(f), f(2) +#define FMT_GEN4(f) FMT_GEN3(f), f(3) +#define FMT_GEN5(f) FMT_GEN4(f), f(4) +#define FMT_GEN6(f) FMT_GEN5(f), f(5) +#define FMT_GEN7(f) FMT_GEN6(f), f(6) +#define FMT_GEN8(f) FMT_GEN7(f), f(7) +#define FMT_GEN9(f) FMT_GEN8(f), f(8) +#define FMT_GEN10(f) FMT_GEN9(f), f(9) +#define FMT_GEN11(f) FMT_GEN10(f), f(10) +#define FMT_GEN12(f) FMT_GEN11(f), f(11) +#define FMT_GEN13(f) FMT_GEN12(f), f(12) +#define FMT_GEN14(f) FMT_GEN13(f), f(13) +#define FMT_GEN15(f) FMT_GEN14(f), f(14) + +namespace internal { inline uint64_t make_type() { return 0; } -template -inline uint64_t make_type(const T &arg) +template inline uint64_t make_type(const T &arg) { - return MakeValue< BasicFormatter >::type(arg); + return MakeValue>::type(arg); } -template - struct ArgArray; +template struct ArgArray; -template -struct ArgArray +template struct ArgArray { // '+' is used to silence GCC -Wduplicated-branches warning. typedef Value Type[N > 0 ? N : +1]; -template -static Value make(const T &value) -{ + template static Value make(const T &value) + { #ifdef __clang__ - Value result = MakeValue(value); - // Workaround a bug in Apple LLVM version 4.2 (clang-425.0.28) of clang: - // https://github.com/fmtlib/fmt/issues/276 - (void)result.custom.format; - return result; + Value result = MakeValue(value); + // Workaround a bug in Apple LLVM version 4.2 (clang-425.0.28) of clang: + // https://github.com/fmtlib/fmt/issues/276 + (void)result.custom.format; + return result; #else - return MakeValue(value); + return MakeValue(value); #endif -} - }; + } +}; -template -struct ArgArray +template struct ArgArray { typedef Arg Type[N + 1]; // +1 for the list end Arg::NONE - template - static Arg make(const T &value) + template static Arg make(const T &value) { return MakeArg(value); } }; #if FMT_USE_VARIADIC_TEMPLATES -template -inline uint64_t make_type(const Arg &first, const Args & ... tail) +template inline uint64_t make_type(const Arg &first, const Args &... tail) { return make_type(first) | (make_type(tail...) << 4); } @@ -2830,121 +2827,113 @@ struct ArgType { uint64_t type; - ArgType() : type(0) {} + ArgType() + : type(0) + { + } template - ArgType(const T &arg) : type(make_type(arg)) {} + ArgType(const T &arg) + : type(make_type(arg)) + { + } }; -# define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType() +#define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType() inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) { - return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) | - (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | (t7.type << 28) | - (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) | - (t12.type << 48) | (t13.type << 52) | (t14.type << 56); + return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) | (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | + (t7.type << 28) | (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) | (t12.type << 48) | (t13.type << 52) | + (t14.type << 56); } #endif -} // namespace internal +} // namespace internal -# define FMT_MAKE_TEMPLATE_ARG(n) typename T##n -# define FMT_MAKE_ARG_TYPE(n) T##n -# define FMT_MAKE_ARG(n) const T##n &v##n -# define FMT_ASSIGN_char(n) \ - arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter >(v##n) -# define FMT_ASSIGN_wchar_t(n) \ - arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter >(v##n) +#define FMT_MAKE_TEMPLATE_ARG(n) typename T##n +#define FMT_MAKE_ARG_TYPE(n) T##n +#define FMT_MAKE_ARG(n) const T##n &v##n +#define FMT_ASSIGN_char(n) arr[n] = fmt::internal::MakeValue>(v##n) +#define FMT_ASSIGN_wchar_t(n) arr[n] = fmt::internal::MakeValue>(v##n) #if FMT_USE_VARIADIC_TEMPLATES // Defines a variadic function returning void. -# define FMT_VARIADIC_VOID(func, arg_type) \ - template \ - void func(arg_type arg0, const Args & ... args) { \ - typedef fmt::internal::ArgArray ArgArray; \ - typename ArgArray::Type array{ \ - ArgArray::template make >(args)...}; \ - func(arg0, fmt::ArgList(fmt::internal::make_type(args...), array)); \ - } +#define FMT_VARIADIC_VOID(func, arg_type) \ + template void func(arg_type arg0, const Args &... args) \ + { \ + typedef fmt::internal::ArgArray ArgArray; \ + typename ArgArray::Type array{ArgArray::template make>(args)...}; \ + func(arg0, fmt::ArgList(fmt::internal::make_type(args...), array)); \ + } // Defines a variadic constructor. -# define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ - template \ - ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \ - typedef fmt::internal::ArgArray ArgArray; \ - typename ArgArray::Type array{ \ - ArgArray::template make >(args)...}; \ - func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(args...), array)); \ - } +#define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ + template ctor(arg0_type arg0, arg1_type arg1, const Args &... args) \ + { \ + typedef fmt::internal::ArgArray ArgArray; \ + typename ArgArray::Type array{ArgArray::template make>(args)...}; \ + func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(args...), array)); \ + } #else -# define FMT_MAKE_REF(n) \ - fmt::internal::MakeValue< fmt::BasicFormatter >(v##n) -# define FMT_MAKE_REF2(n) v##n +#define FMT_MAKE_REF(n) fmt::internal::MakeValue>(v##n) +#define FMT_MAKE_REF2(n) v##n // Defines a wrapper for a function taking one argument of type arg_type // and n additional arguments of arbitrary types. -# define FMT_WRAP1(func, arg_type, n) \ - template \ - inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ - const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ - func(arg1, fmt::ArgList( \ - fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ - } +#define FMT_WRAP1(func, arg_type, n) \ + template inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ + { \ + const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ + func(arg1, fmt::ArgList(fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ + } // Emulates a variadic function returning void on a pre-C++11 compiler. -# define FMT_VARIADIC_VOID(func, arg_type) \ - inline void func(arg_type arg) { func(arg, fmt::ArgList()); } \ - FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \ - FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \ - FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \ - FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \ - FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) - -# define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ - template \ - ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ - const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ - func(arg0, arg1, fmt::ArgList( \ - fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ - } +#define FMT_VARIADIC_VOID(func, arg_type) \ + inline void func(arg_type arg) \ + { \ + func(arg, fmt::ArgList()); \ + } \ + FMT_WRAP1(func, arg_type, 1) \ + FMT_WRAP1(func, arg_type, 2) \ + FMT_WRAP1(func, arg_type, 3) \ + FMT_WRAP1(func, arg_type, 4) FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) FMT_WRAP1(func, arg_type, 7) \ + FMT_WRAP1(func, arg_type, 8) FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) + +#define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ + template ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ + { \ + const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ + func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ + } // Emulates a variadic constructor on a pre-C++11 compiler. -# define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 10) +#define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 10) #endif // Generates a comma-separated list with results of applying f to pairs // (argument, index). #define FMT_FOR_EACH1(f, x0) f(x0, 0) -#define FMT_FOR_EACH2(f, x0, x1) \ - FMT_FOR_EACH1(f, x0), f(x1, 1) -#define FMT_FOR_EACH3(f, x0, x1, x2) \ - FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2) -#define FMT_FOR_EACH4(f, x0, x1, x2, x3) \ - FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3) -#define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \ - FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4) -#define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \ - FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5) -#define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \ - FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6) -#define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \ - FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7) -#define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \ - FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8) -#define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \ - FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9) +#define FMT_FOR_EACH2(f, x0, x1) FMT_FOR_EACH1(f, x0), f(x1, 1) +#define FMT_FOR_EACH3(f, x0, x1, x2) FMT_FOR_EACH2(f, x0, x1), f(x2, 2) +#define FMT_FOR_EACH4(f, x0, x1, x2, x3) FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3) +#define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4) +#define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5) +#define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6) +#define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7) +#define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8) +#define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9) /** An error returned by an operating system or a language runtime, @@ -2958,7 +2947,7 @@ private: protected: int error_code_; - typedef char Char; // For FMT_VARIADIC_CTOR. + typedef char Char; // For FMT_VARIADIC_CTOR. SystemError() {} @@ -3012,8 +3001,7 @@ public: may look like "Unknown error -1" and is platform-dependent. \endrst */ -FMT_API void format_system_error(fmt::Writer &out, int error_code, - fmt::StringRef message) FMT_NOEXCEPT; +FMT_API void format_system_error(fmt::Writer &out, int error_code, fmt::StringRef message) FMT_NOEXCEPT; /** \rst @@ -3033,8 +3021,7 @@ FMT_API void format_system_error(fmt::Writer &out, int error_code, \endrst */ -template -class BasicWriter +template class BasicWriter { private: // Output buffer. @@ -3059,8 +3046,7 @@ private: // Fills the padding around the content and returns the pointer to the // content area. - static CharPtr fill_padding(CharPtr buffer, - unsigned total_size, std::size_t content_size, wchar_t fill); + static CharPtr fill_padding(CharPtr buffer, unsigned total_size, std::size_t content_size, wchar_t fill); // Grows the buffer by n characters and returns a pointer to the newly // allocated area. @@ -3072,8 +3058,7 @@ private: } // Writes an unsigned decimal integer. - template - Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) + template Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) { unsigned num_digits = internal::count_digits(value); Char *ptr = get(grow_buffer(prefix_size + num_digits)); @@ -3082,8 +3067,7 @@ private: } // Writes a decimal integer. - template - void write_decimal(Int value) + template void write_decimal(Int value) { typedef typename internal::IntTraits::MainType MainType; MainType abs_value = static_cast(value); @@ -3099,8 +3083,7 @@ private: } // Prepare a buffer for integer formatting. - CharPtr prepare_int_buffer(unsigned num_digits, - const EmptySpec &, const char *prefix, unsigned prefix_size) + CharPtr prepare_int_buffer(unsigned num_digits, const EmptySpec &, const char *prefix, unsigned prefix_size) { unsigned size = prefix_size + num_digits; CharPtr p = grow_buffer(size); @@ -3108,33 +3091,25 @@ private: return p + size - 1; } - template - CharPtr prepare_int_buffer(unsigned num_digits, - const Spec &spec, const char *prefix, unsigned prefix_size); + template CharPtr prepare_int_buffer(unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size); // Formats an integer. - template - void write_int(T value, Spec spec); + template void write_int(T value, Spec spec); // Formats a floating-point number (double or long double). - template - void write_double(T value, const Spec &spec); + template void write_double(T value, const Spec &spec); // Writes a formatted string. - template - CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); + template CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); - template - void write_str(const internal::Arg::StringValue &str, - const Spec &spec); + template void write_str(const internal::Arg::StringValue &str, const Spec &spec); // This following methods are private to disallow writing wide characters // and strings to a char stream. If you want to print a wide string as a // pointer as std::ostream does, cast it to const void*. // Do not implement! void operator<<(typename internal::WCharHelper::Unsupported); - void operator<<( - typename internal::WCharHelper::Unsupported); + void operator<<(typename internal::WCharHelper::Unsupported); // Appends floating-point length specifier to the format string. // The second argument is only used for overload resolution. @@ -3143,20 +3118,20 @@ private: *format_ptr++ = 'L'; } - template - void append_float_length(Char *&, T) {} + template void append_float_length(Char *&, T) {} - template - friend class internal::ArgFormatterBase; + template friend class internal::ArgFormatterBase; - template - friend class BasicPrintfArgFormatter; + template friend class BasicPrintfArgFormatter; protected: /** Constructs a ``BasicWriter`` object. */ - explicit BasicWriter(Buffer &b) : buffer_(b) {} + explicit BasicWriter(Buffer &b) + : buffer_(b) + { + } public: /** @@ -3297,8 +3272,7 @@ public: return *this; } - BasicWriter &operator<<( - typename internal::WCharHelper::Supported value) + BasicWriter &operator<<(typename internal::WCharHelper::Supported value) { buffer_.push_back(value); return *this; @@ -3316,39 +3290,41 @@ public: return *this; } - BasicWriter &operator<<( - typename internal::WCharHelper::Supported value) + BasicWriter &operator<<(typename internal::WCharHelper::Supported value) { const char *str = value.data(); buffer_.append(str, str + value.size()); return *this; } - template - BasicWriter &operator<<(IntFormatSpec spec) + template BasicWriter &operator<<(IntFormatSpec spec) { internal::CharTraits::convert(FillChar()); write_int(spec.value(), spec); return *this; } - template - BasicWriter &operator<<(const StrFormatSpec &spec) + template BasicWriter &operator<<(const StrFormatSpec &spec) { const StrChar *s = spec.str(); write_str(s, std::char_traits::length(s), spec); return *this; } - void clear() FMT_NOEXCEPT { buffer_.clear(); } + void clear() FMT_NOEXCEPT + { + buffer_.clear(); + } - Buffer &buffer() FMT_NOEXCEPT { return buffer_; } + Buffer &buffer() FMT_NOEXCEPT + { + return buffer_; + } }; template template -typename BasicWriter::CharPtr BasicWriter::write_str( - const StrChar *s, std::size_t size, const AlignSpec &spec) +typename BasicWriter::CharPtr BasicWriter::write_str(const StrChar *s, std::size_t size, const AlignSpec &spec) { CharPtr out = CharPtr(); if (spec.width() > size) @@ -3379,8 +3355,7 @@ typename BasicWriter::CharPtr BasicWriter::write_str( template template -void BasicWriter::write_str( - const internal::Arg::StringValue &s, const Spec &spec) +void BasicWriter::write_str(const internal::Arg::StringValue &s, const Spec &spec) { // Check if StrChar is convertible to Char. internal::CharTraits::convert(StrChar()); @@ -3402,10 +3377,8 @@ void BasicWriter::write_str( } template -typename BasicWriter::CharPtr -BasicWriter::fill_padding( - CharPtr buffer, unsigned total_size, - std::size_t content_size, wchar_t fill) +typename BasicWriter::CharPtr BasicWriter::fill_padding( + CharPtr buffer, unsigned total_size, std::size_t content_size, wchar_t fill) { std::size_t padding = total_size - content_size; std::size_t left_padding = padding / 2; @@ -3413,17 +3386,14 @@ BasicWriter::fill_padding( std::uninitialized_fill_n(buffer, left_padding, fill_char); buffer += left_padding; CharPtr content = buffer; - std::uninitialized_fill_n(buffer + content_size, - padding - left_padding, fill_char); + std::uninitialized_fill_n(buffer + content_size, padding - left_padding, fill_char); return content; } template template -typename BasicWriter::CharPtr -BasicWriter::prepare_int_buffer( - unsigned num_digits, const Spec &spec, - const char *prefix, unsigned prefix_size) +typename BasicWriter::CharPtr BasicWriter::prepare_int_buffer( + unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size) { unsigned width = spec.width(); Alignment align = spec.align(); @@ -3434,8 +3404,7 @@ BasicWriter::prepare_int_buffer( // is specified. if (prefix_size > 0 && prefix[prefix_size - 1] == '0') --prefix_size; - unsigned number_size = - prefix_size + internal::to_unsigned(spec.precision()); + unsigned number_size = prefix_size + internal::to_unsigned(spec.precision()); AlignSpec subspec(number_size, '0', ALIGN_NUMERIC); if (number_size >= width) return prepare_int_buffer(num_digits, subspec, prefix, prefix_size); @@ -3446,8 +3415,7 @@ BasicWriter::prepare_int_buffer( CharPtr p = grow_buffer(fill_size); std::uninitialized_fill(p, p + fill_size, fill); } - CharPtr result = prepare_int_buffer( - num_digits, subspec, prefix, prefix_size); + CharPtr result = prepare_int_buffer(num_digits, subspec, prefix, prefix_size); if (align == ALIGN_LEFT) { CharPtr p = grow_buffer(fill_size); @@ -3496,9 +3464,7 @@ BasicWriter::prepare_int_buffer( return p - 1; } -template -template -void BasicWriter::write_int(T value, Spec spec) +template template void BasicWriter::write_int(T value, Spec spec) { unsigned prefix_size = 0; typedef typename internal::IntTraits::MainType UnsignedType; @@ -3538,18 +3504,14 @@ void BasicWriter::write_int(T value, Spec spec) do { ++num_digits; - } - while ((n >>= 4) != 0); - Char *p = get(prepare_int_buffer( - num_digits, spec, prefix, prefix_size)); + } while ((n >>= 4) != 0); + Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; - const char *digits = spec.type() == 'x' ? - "0123456789abcdef" : "0123456789ABCDEF"; + const char *digits = spec.type() == 'x' ? "0123456789abcdef" : "0123456789ABCDEF"; do { *p-- = digits[n & 0xf]; - } - while ((n >>= 4) != 0); + } while ((n >>= 4) != 0); break; } case 'b': @@ -3565,15 +3527,13 @@ void BasicWriter::write_int(T value, Spec spec) do { ++num_digits; - } - while ((n >>= 1) != 0); + } while ((n >>= 1) != 0); Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; do { *p-- = static_cast('0' + (n & 1)); - } - while ((n >>= 1) != 0); + } while ((n >>= 1) != 0); break; } case 'o': @@ -3585,15 +3545,13 @@ void BasicWriter::write_int(T value, Spec spec) do { ++num_digits; - } - while ((n >>= 3) != 0); + } while ((n >>= 3) != 0); Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; do { *p-- = static_cast('0' + (n & 7)); - } - while ((n >>= 3) != 0); + } while ((n >>= 3) != 0); break; } case 'n': @@ -3603,22 +3561,18 @@ void BasicWriter::write_int(T value, Spec spec) #if !(defined(ANDROID) || defined(__ANDROID__)) sep = internal::thousands_sep(std::localeconv()); #endif - unsigned size = static_cast( - num_digits + sep.size() * ((num_digits - 1) / 3)); + unsigned size = static_cast(num_digits + sep.size() * ((num_digits - 1) / 3)); CharPtr p = prepare_int_buffer(size, spec, prefix, prefix_size) + 1; internal::format_decimal(get(p), abs_value, 0, internal::ThousandsSep(sep)); break; } default: - internal::report_unknown_type( - spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer"); + internal::report_unknown_type(spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer"); break; } } -template -template -void BasicWriter::write_double(T value, const Spec &spec) +template template void BasicWriter::write_double(T value, const Spec &spec) { // Check type. char type = spec.type(); @@ -3707,7 +3661,10 @@ void BasicWriter::write_double(T value, const Spec &spec) } // Build format string. - enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg + enum + { + MAX_FORMAT_SIZE = 10 + }; // longest format: %#-*.*Lg Char format[MAX_FORMAT_SIZE]; Char *format_ptr = format; *format_ptr++ = '%'; @@ -3753,13 +3710,12 @@ void BasicWriter::write_double(T value, const Spec &spec) } #endif start = &buffer_[offset]; - int result = internal::CharTraits::format_float( - start, buffer_size, format, width_for_sprintf, spec.precision(), value); + int result = internal::CharTraits::format_float(start, buffer_size, format, width_for_sprintf, spec.precision(), value); if (result >= 0) { n = internal::to_unsigned(result); if (offset + n < buffer_.capacity()) - break; // The buffer is large enough - continue with formatting. + break; // The buffer is large enough - continue with formatting. buffer_.reserve(offset + n + 1); } else @@ -3771,8 +3727,7 @@ void BasicWriter::write_double(T value, const Spec &spec) } if (sign) { - if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) || - *start != ' ') + if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) || *start != ' ') { *(start - 1) = sign; sign = 0; @@ -3835,15 +3790,17 @@ void BasicWriter::write_double(T value, const Spec &spec) accessed as a C string with ``out.c_str()``. \endrst */ -template > -class BasicMemoryWriter : public BasicWriter +template > class BasicMemoryWriter : public BasicWriter { private: internal::MemoryBuffer buffer_; public: - explicit BasicMemoryWriter(const Allocator& alloc = Allocator()) - : BasicWriter(buffer_), buffer_(alloc) {} + explicit BasicMemoryWriter(const Allocator &alloc = Allocator()) + : BasicWriter(buffer_) + , buffer_(alloc) + { + } #if FMT_USE_RVALUE_REFERENCES /** @@ -3853,7 +3810,8 @@ public: \endrst */ BasicMemoryWriter(BasicMemoryWriter &&other) - : BasicWriter(buffer_), buffer_(std::move(other.buffer_)) + : BasicWriter(buffer_) + , buffer_(std::move(other.buffer_)) { } @@ -3893,8 +3851,7 @@ typedef BasicMemoryWriter WMemoryWriter; +--------------+---------------------------+ \endrst */ -template -class BasicArrayWriter : public BasicWriter +template class BasicArrayWriter : public BasicWriter { private: internal::FixedBuffer buffer_; @@ -3907,7 +3864,10 @@ public: \endrst */ BasicArrayWriter(Char *array, std::size_t size) - : BasicWriter(buffer_), buffer_(array, size) {} + : BasicWriter(buffer_) + , buffer_(array, size) + { + } /** \rst @@ -3917,7 +3877,10 @@ public: */ template explicit BasicArrayWriter(Char (&array)[SIZE]) - : BasicWriter(buffer_), buffer_(array, SIZE) {} + : BasicWriter(buffer_) + , buffer_(array, SIZE) + { + } }; typedef BasicArrayWriter ArrayWriter; @@ -3925,8 +3888,7 @@ typedef BasicArrayWriter WArrayWriter; // Reports a system error without throwing an exception. // Can be used to report errors from destructors. -FMT_API void report_system_error(int error_code, - StringRef message) FMT_NOEXCEPT; +FMT_API void report_system_error(int error_code, StringRef message) FMT_NOEXCEPT; #if FMT_USE_WINDOWS_H @@ -3974,12 +3936,21 @@ public: // Reports a Windows error without throwing an exception. // Can be used to report errors from destructors. -FMT_API void report_windows_error(int error_code, - StringRef message) FMT_NOEXCEPT; +FMT_API void report_windows_error(int error_code, StringRef message) FMT_NOEXCEPT; #endif -enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE }; +enum Color +{ + BLACK, + RED, + GREEN, + YELLOW, + BLUE, + MAGENTA, + CYAN, + WHITE +}; /** Formats a string and prints it to stdout using ANSI escape sequences @@ -4042,7 +4013,10 @@ class FormatInt private: // Buffer should be large enough to hold all digits (digits10 + 1), // a sign and a null character. - enum {BUFFER_SIZE = std::numeric_limits::digits10 + 3}; + enum + { + BUFFER_SIZE = std::numeric_limits::digits10 + 3 + }; mutable char buffer_[BUFFER_SIZE]; char *str_; @@ -4095,9 +4069,18 @@ public: { FormatSigned(value); } - explicit FormatInt(unsigned value) : str_(format_decimal(value)) {} - explicit FormatInt(unsigned long value) : str_(format_decimal(value)) {} - explicit FormatInt(ULongLong value) : str_(format_decimal(value)) {} + explicit FormatInt(unsigned value) + : str_(format_decimal(value)) + { + } + explicit FormatInt(unsigned long value) + : str_(format_decimal(value)) + { + } + explicit FormatInt(ULongLong value) + : str_(format_decimal(value)) + { + } /** Returns the number of characters written to the output buffer. */ std::size_t size() const @@ -4138,8 +4121,7 @@ public: // Formats a decimal integer value writing into buffer and returns // a pointer to the end of the formatted string. This function doesn't // write a terminating null character. -template -inline void format_decimal(char *&buffer, T value) +template inline void format_decimal(char *&buffer, T value) { typedef typename internal::IntTraits::MainType MainType; MainType abs_value = static_cast(value); @@ -4175,32 +4157,28 @@ inline void format_decimal(char *&buffer, T value) \endrst */ -template -inline internal::NamedArgWithType arg(StringRef name, const T &arg) +template inline internal::NamedArgWithType arg(StringRef name, const T &arg) { return internal::NamedArgWithType(name, arg); } -template -inline internal::NamedArgWithType arg(WStringRef name, const T &arg) +template inline internal::NamedArgWithType arg(WStringRef name, const T &arg) { return internal::NamedArgWithType(name, arg); } // The following two functions are deleted intentionally to disable // nested named arguments as in ``format("{}", arg("a", arg("b", 42)))``. -template -void arg(StringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; -template -void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; -} +template void arg(StringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; +template void arg(WStringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; +} // namespace fmt #if FMT_GCC_VERSION // Use the system_header pragma to suppress warnings about variadic macros // because suppressing -Wvariadic-macros with the diagnostic pragma doesn't // work. It is used at the end because we want to suppress as little warnings // as possible. -# pragma GCC system_header +#pragma GCC system_header #endif // This is used to work around VC++ bugs in handling variadic macros. @@ -4213,58 +4191,53 @@ void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; #define FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N #define FMT_RSEQ_N() 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 -#define FMT_FOR_EACH_(N, f, ...) \ - FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__)) -#define FMT_FOR_EACH(f, ...) \ - FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__)) +#define FMT_FOR_EACH_(N, f, ...) FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__)) +#define FMT_FOR_EACH(f, ...) FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__)) #define FMT_ADD_ARG_NAME(type, index) type arg##index #define FMT_GET_ARG_NAME(type, index) arg##index #if FMT_USE_VARIADIC_TEMPLATES -# define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ - template \ - ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ - const Args & ... args) Const { \ - typedef fmt::internal::ArgArray ArgArray; \ - typename ArgArray::Type array{ \ - ArgArray::template make >(args)...}; \ - call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), \ - fmt::ArgList(fmt::internal::make_type(args...), array)); \ - } +#define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ + template ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), const Args &... args) Const \ + { \ + typedef fmt::internal::ArgArray ArgArray; \ + typename ArgArray::Type array{ArgArray::template make>(args)...}; \ + call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList(fmt::internal::make_type(args...), array)); \ + } #else // Defines a wrapper for a function taking __VA_ARGS__ arguments // and n additional arguments of arbitrary types. -# define FMT_WRAP(Const, Char, ReturnType, func, call, n, ...) \ - template \ - inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ - FMT_GEN(n, FMT_MAKE_ARG)) Const { \ - fmt::internal::ArgArray::Type arr; \ - FMT_GEN(n, FMT_ASSIGN_##Char); \ - call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \ - fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), arr)); \ - } - -# define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ - inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) Const { \ - call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \ - } \ - FMT_WRAP(Const, Char, ReturnType, func, call, 1, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 2, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 3, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 4, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 5, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 6, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 7, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 8, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 9, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 10, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 11, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 12, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 13, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 14, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 15, __VA_ARGS__) -#endif // FMT_USE_VARIADIC_TEMPLATES +#define FMT_WRAP(Const, Char, ReturnType, func, call, n, ...) \ + template \ + inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), FMT_GEN(n, FMT_MAKE_ARG)) Const \ + { \ + fmt::internal::ArgArray::Type arr; \ + FMT_GEN(n, FMT_ASSIGN_##Char); \ + call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList(fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), arr)); \ + } + +#define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ + inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) Const \ + { \ + call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \ + } \ + FMT_WRAP(Const, Char, ReturnType, func, call, 1, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 2, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 3, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 4, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 5, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 6, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 7, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 8, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 9, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 10, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 11, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 12, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 13, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 14, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 15, __VA_ARGS__) +#endif // FMT_USE_VARIADIC_TEMPLATES /** \rst @@ -4293,21 +4266,17 @@ void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; } \endrst */ -#define FMT_VARIADIC(ReturnType, func, ...) \ - FMT_VARIADIC_(, char, ReturnType, func, return func, __VA_ARGS__) +#define FMT_VARIADIC(ReturnType, func, ...) FMT_VARIADIC_(, char, ReturnType, func, return func, __VA_ARGS__) -#define FMT_VARIADIC_CONST(ReturnType, func, ...) \ - FMT_VARIADIC_(const, char, ReturnType, func, return func, __VA_ARGS__) +#define FMT_VARIADIC_CONST(ReturnType, func, ...) FMT_VARIADIC_(const, char, ReturnType, func, return func, __VA_ARGS__) -#define FMT_VARIADIC_W(ReturnType, func, ...) \ - FMT_VARIADIC_(, wchar_t, ReturnType, func, return func, __VA_ARGS__) +#define FMT_VARIADIC_W(ReturnType, func, ...) FMT_VARIADIC_(, wchar_t, ReturnType, func, return func, __VA_ARGS__) -#define FMT_VARIADIC_CONST_W(ReturnType, func, ...) \ - FMT_VARIADIC_(const, wchar_t, ReturnType, func, return func, __VA_ARGS__) +#define FMT_VARIADIC_CONST_W(ReturnType, func, ...) FMT_VARIADIC_(const, wchar_t, ReturnType, func, return func, __VA_ARGS__) #define FMT_CAPTURE_ARG_(id, index) ::fmt::arg(#id, id) -#define FMT_CAPTURE_ARG_W_(id, index) ::fmt::arg(L###id, id) +#define FMT_CAPTURE_ARG_W_(id, index) ::fmt::arg(L## #id, id) /** \rst @@ -4327,26 +4296,22 @@ void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; #define FMT_CAPTURE_W(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_W_, __VA_ARGS__) -namespace fmt -{ +namespace fmt { FMT_VARIADIC(std::string, format, CStringRef) FMT_VARIADIC_W(std::wstring, format, WCStringRef) FMT_VARIADIC(void, print, CStringRef) FMT_VARIADIC(void, print, std::FILE *, CStringRef) FMT_VARIADIC(void, print_colored, Color, CStringRef) -namespace internal -{ -template -inline bool is_name_start(Char c) +namespace internal { +template inline bool is_name_start(Char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; } // Parses an unsigned integer advancing s to the end of the parsed input. // This function assumes that the first character of s is a digit. -template -unsigned parse_nonnegative_int(const Char *&s) +template unsigned parse_nonnegative_int(const Char *&s) { assert('0' <= *s && *s <= '9'); unsigned value = 0; @@ -4363,8 +4328,7 @@ unsigned parse_nonnegative_int(const Char *&s) } value = value * 10 + (*s - '0'); ++s; - } - while ('0' <= *s && *s <= '9'); + } while ('0' <= *s && *s <= '9'); // Convert to unsigned to prevent a warning. if (value > max_int) FMT_THROW(FormatError("number is too big")); @@ -4375,29 +4339,25 @@ inline void require_numeric_argument(const Arg &arg, char spec) { if (arg.type > Arg::LAST_NUMERIC_TYPE) { - std::string message = - fmt::format("format specifier '{}' requires numeric argument", spec); + std::string message = fmt::format("format specifier '{}' requires numeric argument", spec); FMT_THROW(fmt::FormatError(message)); } } -template -void check_sign(const Char *&s, const Arg &arg) +template void check_sign(const Char *&s, const Arg &arg) { char sign = static_cast(*s); require_numeric_argument(arg, sign); if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) { - FMT_THROW(FormatError(fmt::format( - "format specifier '{}' requires signed argument", sign))); + FMT_THROW(FormatError(fmt::format("format specifier '{}' requires signed argument", sign))); } ++s; } -} // namespace internal +} // namespace internal template -inline internal::Arg BasicFormatter::get_arg( - BasicStringRef arg_name, const char *&error) +inline internal::Arg BasicFormatter::get_arg(BasicStringRef arg_name, const char *&error) { if (check_no_auto_index(error)) { @@ -4410,22 +4370,18 @@ inline internal::Arg BasicFormatter::get_arg( return internal::Arg(); } -template -inline internal::Arg BasicFormatter::parse_arg_index(const Char *&s) +template inline internal::Arg BasicFormatter::parse_arg_index(const Char *&s) { const char *error = FMT_NULL; - internal::Arg arg = *s < '0' || *s > '9' ? - next_arg(error) : get_arg(internal::parse_nonnegative_int(s), error); + internal::Arg arg = *s < '0' || *s > '9' ? next_arg(error) : get_arg(internal::parse_nonnegative_int(s), error); if (error) { - FMT_THROW(FormatError( - *s != '}' && *s != ':' ? "invalid format string" : error)); + FMT_THROW(FormatError(*s != '}' && *s != ':' ? "invalid format string" : error)); } return arg; } -template -inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) +template inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) { assert(internal::is_name_start(*s)); const Char *start = s; @@ -4433,8 +4389,7 @@ inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) do { c = *++s; - } - while (internal::is_name_start(c) || ('0' <= c && c <= '9')); + } while (internal::is_name_start(c) || ('0' <= c && c <= '9')); const char *error = FMT_NULL; internal::Arg arg = get_arg(BasicStringRef(start, s - start), error); if (error) @@ -4443,8 +4398,7 @@ inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) } template -const Char *BasicFormatter::format( - const Char *&format_str, const internal::Arg &arg) +const Char *BasicFormatter::format(const Char *&format_str, const internal::Arg &arg) { using internal::Arg; const Char *s = format_str; @@ -4483,19 +4437,20 @@ const Char *BasicFormatter::format( { if (p != s) { - if (c == '}') break; + if (c == '}') + break; if (c == '{') FMT_THROW(FormatError("invalid fill character '{'")); s += 2; spec.fill_ = c; } - else ++s; + else + ++s; if (spec.align_ == ALIGN_NUMERIC) require_numeric_argument(arg, '='); break; } - } - while (--p >= s); + } while (--p >= s); } // Parse sign. @@ -4539,8 +4494,7 @@ const Char *BasicFormatter::format( else if (*s == '{') { ++s; - Arg width_arg = internal::is_name_start(*s) ? - parse_arg_name(s) : parse_arg_index(s); + Arg width_arg = internal::is_name_start(*s) ? parse_arg_name(s) : parse_arg_index(s); if (*s++ != '}') FMT_THROW(FormatError("invalid format string")); ULongLong value = 0; @@ -4583,8 +4537,7 @@ const Char *BasicFormatter::format( else if (*s == '{') { ++s; - Arg precision_arg = internal::is_name_start(*s) ? - parse_arg_name(s) : parse_arg_index(s); + Arg precision_arg = internal::is_name_start(*s) ? parse_arg_name(s) : parse_arg_index(s); if (*s++ != '}') FMT_THROW(FormatError("invalid format string")); ULongLong value = 0; @@ -4621,8 +4574,7 @@ const Char *BasicFormatter::format( if (arg.type <= Arg::LAST_INTEGER_TYPE || arg.type == Arg::POINTER) { FMT_THROW(FormatError( - fmt::format("precision not allowed in {} format specifier", - arg.type == Arg::POINTER ? "pointer" : "integer"))); + fmt::format("precision not allowed in {} format specifier", arg.type == Arg::POINTER ? "pointer" : "integer"))); } } @@ -4639,15 +4591,15 @@ const Char *BasicFormatter::format( return s; } -template -void BasicFormatter::format(BasicCStringRef format_str) +template void BasicFormatter::format(BasicCStringRef format_str) { const Char *s = format_str.c_str(); const Char *start = s; while (*s) { Char c = *s++; - if (c != '{' && c != '}') continue; + if (c != '{' && c != '}') + continue; if (*s == c) { write(writer_, start, s); @@ -4657,59 +4609,53 @@ void BasicFormatter::format(BasicCStringRef format_str) if (c == '}') FMT_THROW(FormatError("unmatched '}' in format string")); write(writer_, start, s - 1); - internal::Arg arg = internal::is_name_start(*s) ? - parse_arg_name(s) : parse_arg_index(s); + internal::Arg arg = internal::is_name_start(*s) ? parse_arg_name(s) : parse_arg_index(s); start = s = format(s, arg); } write(writer_, start, s); } -template -struct ArgJoin +template struct ArgJoin { It first; It last; BasicCStringRef sep; - ArgJoin(It first, It last, const BasicCStringRef& sep) : - first(first), - last(last), - sep(sep) {} + ArgJoin(It first, It last, const BasicCStringRef &sep) + : first(first) + , last(last) + , sep(sep) + { + } }; -template -ArgJoin join(It first, It last, const BasicCStringRef& sep) +template ArgJoin join(It first, It last, const BasicCStringRef &sep) { return ArgJoin(first, last, sep); } -template -ArgJoin join(It first, It last, const BasicCStringRef& sep) +template ArgJoin join(It first, It last, const BasicCStringRef &sep) { return ArgJoin(first, last, sep); } #if FMT_HAS_GXX_CXX11 -template -auto join(const Range& range, const BasicCStringRef& sep) --> ArgJoin +template auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin { return join(std::begin(range), std::end(range), sep); } template -auto join(const Range& range, const BasicCStringRef& sep) --> ArgJoin +auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin { return join(std::begin(range), std::end(range), sep); } #endif template -void format_arg(fmt::BasicFormatter &f, - const Char *&format_str, const ArgJoin& e) +void format_arg(fmt::BasicFormatter &f, const Char *&format_str, const ArgJoin &e) { - const Char* end = format_str; + const Char *end = format_str; if (*end == ':') ++end; while (*end && *end != '}') @@ -4720,45 +4666,38 @@ void format_arg(fmt::BasicFormatter &f, It it = e.first; if (it != e.last) { - const Char* save = format_str; - f.format(format_str, internal::MakeArg >(*it++)); + const Char *save = format_str; + f.format(format_str, internal::MakeArg>(*it++)); while (it != e.last) { f.writer().write(e.sep); format_str = save; - f.format(format_str, internal::MakeArg >(*it++)); + f.format(format_str, internal::MakeArg>(*it++)); } } format_str = end + 1; } -} // namespace fmt +} // namespace fmt #if FMT_USE_USER_DEFINED_LITERALS -namespace fmt -{ -namespace internal -{ +namespace fmt { +namespace internal { -template -struct UdlFormat +template struct UdlFormat { const Char *str; - template - auto operator()(Args && ... args) const - -> decltype(format(str, std::forward(args)...)) + template auto operator()(Args &&... args) const -> decltype(format(str, std::forward(args)...)) { return format(str, std::forward(args)...); } }; -template -struct UdlArg +template struct UdlArg { const Char *str; - template - NamedArgWithType operator=(T &&value) const + template NamedArgWithType operator=(T &&value) const { return {str, std::forward(value)}; } @@ -4766,8 +4705,7 @@ struct UdlArg } // namespace internal -inline namespace literals -{ +inline namespace literals { /** \rst @@ -4779,13 +4717,11 @@ inline namespace literals std::string message = "The answer is {}"_format(42); \endrst */ -inline internal::UdlFormat -operator"" _format(const char *s, std::size_t) +inline internal::UdlFormat operator"" _format(const char *s, std::size_t) { return {s}; } -inline internal::UdlFormat -operator"" _format(const wchar_t *s, std::size_t) +inline internal::UdlFormat operator"" _format(const wchar_t *s, std::size_t) { return {s}; } @@ -4800,35 +4736,33 @@ operator"" _format(const wchar_t *s, std::size_t) print("Elapsed time: {s:.2f} seconds", "s"_a=1.23); \endrst */ -inline internal::UdlArg -operator"" _a(const char *s, std::size_t) +inline internal::UdlArg operator"" _a(const char *s, std::size_t) { return {s}; } -inline internal::UdlArg -operator"" _a(const wchar_t *s, std::size_t) +inline internal::UdlArg operator"" _a(const wchar_t *s, std::size_t) { return {s}; } -} // inline namespace literals +} // namespace literals } // namespace fmt #endif // FMT_USE_USER_DEFINED_LITERALS // Restore warnings. #if FMT_GCC_VERSION >= 406 -# pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif #if defined(__clang__) && !defined(FMT_ICC_VERSION) -# pragma clang diagnostic pop +#pragma clang diagnostic pop #endif #ifdef FMT_HEADER_ONLY -# define FMT_FUNC inline -# include "format.cc" +#define FMT_FUNC inline +#include "format.cc" #else -# define FMT_FUNC +#define FMT_FUNC #endif -#endif // FMT_FORMAT_H_ +#endif // FMT_FORMAT_H_ diff --git a/include/spdlog/fmt/bundled/ostream.h b/include/spdlog/fmt/bundled/ostream.h index f1b09dfc..1a21f984 100644 --- a/include/spdlog/fmt/bundled/ostream.h +++ b/include/spdlog/fmt/bundled/ostream.h @@ -13,14 +13,11 @@ #include "format.h" #include -namespace fmt -{ +namespace fmt { -namespace internal -{ +namespace internal { -template -class FormatBuf : public std::basic_streambuf +template class FormatBuf : public std::basic_streambuf { private: typedef typename std::basic_streambuf::int_type int_type; @@ -29,7 +26,10 @@ private: Buffer &buffer_; public: - FormatBuf(Buffer &buffer) : buffer_(buffer) {} + FormatBuf(Buffer &buffer) + : buffer_(buffer) + { + } protected: // The put-area is actually always empty. This makes the implementation @@ -57,17 +57,15 @@ Yes &convert(std::ostream &); struct DummyStream : std::ostream { - DummyStream(); // Suppress a bogus warning in MSVC. + DummyStream(); // Suppress a bogus warning in MSVC. // Hide all operator<< overloads from std::ostream. - template - typename EnableIf::type operator<<(const T &); + template typename EnableIf::type operator<<(const T &); }; No &operator<<(std::ostream &, int); -template -struct ConvertToIntImpl +template struct ConvertToIntImpl { // Convert to int only if T doesn't have an overloaded operator<<. enum @@ -78,12 +76,11 @@ struct ConvertToIntImpl // Write the content of w to os. FMT_API void write(std::ostream &os, Writer &w); -} // namespace internal +} // namespace internal // Formats a value. template -void format_arg(BasicFormatter &f, - const Char *&format_str, const T &value) +void format_arg(BasicFormatter &f, const Char *&format_str, const T &value) { internal::MemoryBuffer buffer; @@ -93,7 +90,7 @@ void format_arg(BasicFormatter &f, output << value; BasicStringRef str(&buffer[0], buffer.size()); - typedef internal::MakeArg< BasicFormatter > MakeArg; + typedef internal::MakeArg> MakeArg; format_str = f.format(format_str, MakeArg(str)); } @@ -108,10 +105,10 @@ void format_arg(BasicFormatter &f, */ FMT_API void print(std::ostream &os, CStringRef format_str, ArgList args); FMT_VARIADIC(void, print, std::ostream &, CStringRef) -} // namespace fmt +} // namespace fmt #ifdef FMT_HEADER_ONLY -# include "ostream.cc" +#include "ostream.cc" #endif -#endif // FMT_OSTREAM_H_ +#endif // FMT_OSTREAM_H_ diff --git a/include/spdlog/fmt/bundled/posix.h b/include/spdlog/fmt/bundled/posix.h index 69327250..20af016c 100644 --- a/include/spdlog/fmt/bundled/posix.h +++ b/include/spdlog/fmt/bundled/posix.h @@ -12,60 +12,60 @@ #if defined(__MINGW32__) || defined(__CYGWIN__) // Workaround MinGW bug https://sourceforge.net/p/mingw/bugs/2024/. -# undef __STRICT_ANSI__ +#undef __STRICT_ANSI__ #endif #include -#include // for O_RDONLY -#include // for locale_t +#include // for O_RDONLY +#include // for locale_t #include -#include // for strtod_l +#include // for strtod_l #include #if defined __APPLE__ || defined(__FreeBSD__) -# include // for LC_NUMERIC_MASK on OS X +#include // for LC_NUMERIC_MASK on OS X #endif #include "format.h" #ifndef FMT_POSIX -# if defined(_WIN32) && !defined(__MINGW32__) +#if defined(_WIN32) && !defined(__MINGW32__) // Fix warnings about deprecated symbols. -# define FMT_POSIX(call) _##call -# else -# define FMT_POSIX(call) call -# endif +#define FMT_POSIX(call) _##call +#else +#define FMT_POSIX(call) call +#endif #endif // Calls to system functions are wrapped in FMT_SYSTEM for testability. #ifdef FMT_SYSTEM -# define FMT_POSIX_CALL(call) FMT_SYSTEM(call) +#define FMT_POSIX_CALL(call) FMT_SYSTEM(call) #else -# define FMT_SYSTEM(call) call -# ifdef _WIN32 +#define FMT_SYSTEM(call) call +#ifdef _WIN32 // Fix warnings about deprecated symbols. -# define FMT_POSIX_CALL(call) ::_##call -# else -# define FMT_POSIX_CALL(call) ::call -# endif +#define FMT_POSIX_CALL(call) ::_##call +#else +#define FMT_POSIX_CALL(call) ::call +#endif #endif // Retries the expression while it evaluates to error_result and errno // equals to EINTR. #ifndef _WIN32 -# define FMT_RETRY_VAL(result, expression, error_result) \ - do { \ - result = (expression); \ - } while (result == error_result && errno == EINTR) +#define FMT_RETRY_VAL(result, expression, error_result) \ + do \ + { \ + result = (expression); \ + } while (result == error_result && errno == EINTR) #else -# define FMT_RETRY_VAL(result, expression, error_result) result = (expression) +#define FMT_RETRY_VAL(result, expression, error_result) result = (expression) #endif #define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1) -namespace fmt -{ +namespace fmt { // An error code. class ErrorCode @@ -74,8 +74,7 @@ private: int value_; public: -explicit ErrorCode(int value = 0) FMT_NOEXCEPT : - value_(value) {} + explicit ErrorCode(int value = 0) FMT_NOEXCEPT : value_(value) {} int get() const FMT_NOEXCEPT { @@ -91,12 +90,14 @@ private: friend class File; - explicit BufferedFile(FILE *f) : file_(f) {} + explicit BufferedFile(FILE *f) + : file_(f) + { + } public: // Constructs a BufferedFile object which doesn't represent any file. -BufferedFile() FMT_NOEXCEPT : - file_(FMT_NULL) {} + BufferedFile() FMT_NOEXCEPT : file_(FMT_NULL) {} // Destroys the object closing the file it represents if any. FMT_API ~BufferedFile() FMT_NOEXCEPT; @@ -115,12 +116,10 @@ private: public: // A "move constructor" for moving from a temporary. -BufferedFile(Proxy p) FMT_NOEXCEPT : - file_(p.file) {} + BufferedFile(Proxy p) FMT_NOEXCEPT : file_(p.file) {} // A "move constructor" for moving from an lvalue. -BufferedFile(BufferedFile &f) FMT_NOEXCEPT : - file_(f.file_) + BufferedFile(BufferedFile &f) FMT_NOEXCEPT : file_(f.file_) { f.file_ = FMT_NULL; } @@ -156,13 +155,12 @@ private: FMT_DISALLOW_COPY_AND_ASSIGN(BufferedFile); public: -BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : - file_(other.file_) + BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : file_(other.file_) { other.file_ = FMT_NULL; } - BufferedFile& operator=(BufferedFile &&other) + BufferedFile &operator=(BufferedFile &&other) { close(); file_ = other.file_; @@ -185,7 +183,7 @@ BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : // We place parentheses around fileno to workaround a bug in some versions // of MinGW that define fileno as a macro. - FMT_API int (fileno)() const; + FMT_API int(fileno)() const; void print(CStringRef format_str, const ArgList &args) { @@ -203,10 +201,13 @@ BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : class File { private: - int fd_; // File descriptor. + int fd_; // File descriptor. // Constructs a File object with a given descriptor. - explicit File(int fd) : fd_(fd) {} + explicit File(int fd) + : fd_(fd) + { + } public: // Possible values for the oflag argument to the constructor. @@ -214,12 +215,11 @@ public: { RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only. WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only. - RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing. + RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing. }; // Constructs a File object which doesn't represent any file. -File() FMT_NOEXCEPT : - fd_(-1) {} + File() FMT_NOEXCEPT : fd_(-1) {} // Opens a file and constructs a File object representing this file. FMT_API File(CStringRef path, int oflag); @@ -238,12 +238,10 @@ private: public: // A "move constructor" for moving from a temporary. -File(Proxy p) FMT_NOEXCEPT : - fd_(p.fd) {} + File(Proxy p) FMT_NOEXCEPT : fd_(p.fd) {} // A "move constructor" for moving from an lvalue. -File(File &other) FMT_NOEXCEPT : - fd_(other.fd_) + File(File &other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; } @@ -279,13 +277,12 @@ private: FMT_DISALLOW_COPY_AND_ASSIGN(File); public: -File(File &&other) FMT_NOEXCEPT : - fd_(other.fd_) + File(File &&other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; } - File& operator=(File &&other) + File &operator=(File &&other) { close(); fd_ = other.fd_; @@ -340,9 +337,8 @@ File(File &&other) FMT_NOEXCEPT : // Returns the memory page size. long getpagesize(); -#if (defined(LC_NUMERIC_MASK) || defined(_MSC_VER)) && \ - !defined(__ANDROID__) && !defined(__CYGWIN__) -# define FMT_LOCALE +#if (defined(LC_NUMERIC_MASK) || defined(_MSC_VER)) && !defined(__ANDROID__) && !defined(__CYGWIN__) +#define FMT_LOCALE #endif #ifdef FMT_LOCALE @@ -350,10 +346,13 @@ long getpagesize(); class Locale { private: -# ifdef _MSC_VER +#ifdef _MSC_VER typedef _locale_t locale_t; - enum { LC_NUMERIC_MASK = LC_NUMERIC }; + enum + { + LC_NUMERIC_MASK = LC_NUMERIC + }; static locale_t newlocale(int category_mask, const char *locale, locale_t) { @@ -369,7 +368,7 @@ private: { return _strtod_l(nptr, endptr, locale); } -# endif +#endif locale_t locale_; @@ -378,7 +377,8 @@ private: public: typedef locale_t Type; - Locale() : locale_(newlocale(LC_NUMERIC_MASK, "C", FMT_NULL)) + Locale() + : locale_(newlocale(LC_NUMERIC_MASK, "C", FMT_NULL)) { if (!locale_) FMT_THROW(fmt::SystemError(errno, "cannot create locale")); @@ -403,12 +403,11 @@ public: return result; } }; -#endif // FMT_LOCALE -} // namespace fmt +#endif // FMT_LOCALE +} // namespace fmt #if !FMT_USE_RVALUE_REFERENCES -namespace std -{ +namespace std { // For compatibility with C++98. inline fmt::BufferedFile &move(fmt::BufferedFile &f) { @@ -418,7 +417,7 @@ inline fmt::File &move(fmt::File &f) { return f; } -} +} // namespace std #endif -#endif // FMT_POSIX_H_ +#endif // FMT_POSIX_H_ diff --git a/include/spdlog/fmt/bundled/printf.h b/include/spdlog/fmt/bundled/printf.h index 14242143..4f540048 100644 --- a/include/spdlog/fmt/bundled/printf.h +++ b/include/spdlog/fmt/bundled/printf.h @@ -10,23 +10,19 @@ #ifndef FMT_PRINTF_H_ #define FMT_PRINTF_H_ -#include // std::fill_n -#include // std::numeric_limits +#include // std::fill_n +#include // std::numeric_limits #include "ostream.h" -namespace fmt -{ -namespace internal -{ +namespace fmt { +namespace internal { // Checks if a value fits in int - used to avoid warnings about comparing // signed and unsigned integers. -template -struct IntChecker +template struct IntChecker { - template - static bool fits_in_int(T value) + template static bool fits_in_int(T value) { unsigned max = std::numeric_limits::max(); return value <= max; @@ -37,14 +33,11 @@ struct IntChecker } }; -template <> -struct IntChecker +template <> struct IntChecker { - template - static bool fits_in_int(T value) + template static bool fits_in_int(T value) { - return value >= std::numeric_limits::min() && - value <= std::numeric_limits::max(); + return value >= std::numeric_limits::min() && value <= std::numeric_limits::max(); } static bool fits_in_int(int) { @@ -60,8 +53,7 @@ public: FMT_THROW(FormatError("precision is not integer")); } - template - int visit_any_int(T value) + template int visit_any_int(T value) { if (!IntChecker::is_signed>::fits_in_int(value)) FMT_THROW(FormatError("number is too big")); @@ -73,8 +65,7 @@ public: class IsZeroInt : public ArgVisitor { public: - template - bool visit_any_int(T value) + template bool visit_any_int(T value) { return value == 0; } @@ -99,14 +90,12 @@ public: return 'p'; } - template - char visit_any_int(T) + template char visit_any_int(T) { return 'd'; } - template - char visit_any_double(T) + template char visit_any_double(T) { return 'g'; } @@ -117,24 +106,27 @@ public: } }; -template -struct is_same +template struct is_same { - enum { value = 0 }; + enum + { + value = 0 + }; }; -template -struct is_same +template struct is_same { - enum { value = 1 }; + enum + { + value = 1 + }; }; // An argument visitor that converts an integer argument to T for printf, // if T is an integral type. If T is void, the argument is converted to // corresponding signed or unsigned type depending on the type specifier: // 'd' and 'i' - signed, other - unsigned) -template -class ArgConverter : public ArgVisitor, void> +template class ArgConverter : public ArgVisitor, void> { private: internal::Arg &arg_; @@ -144,7 +136,10 @@ private: public: ArgConverter(internal::Arg &arg, wchar_t type) - : arg_(arg), type_(type) {} + : arg_(arg) + , type_(type) + { + } void visit_bool(bool value) { @@ -158,8 +153,7 @@ public: visit_any_int(value); } - template - void visit_any_int(U value) + template void visit_any_int(U value) { bool is_signed = type_ == 'd' || type_ == 'i'; if (type_ == 's') @@ -168,8 +162,7 @@ public: } using internal::Arg; - typedef typename internal::Conditional< - is_same::value, U, T>::type TargetType; + typedef typename internal::Conditional::value, U, T>::type TargetType; if (const_check(sizeof(TargetType) <= sizeof(int))) { // Extra casts are used to silence warnings. @@ -198,8 +191,7 @@ public: else { arg_.type = Arg::ULONG_LONG; - arg_.ulong_long_value = - static_cast::Type>(value); + arg_.ulong_long_value = static_cast::Type>(value); } } } @@ -214,10 +206,12 @@ private: FMT_DISALLOW_COPY_AND_ASSIGN(CharConverter); public: - explicit CharConverter(internal::Arg &arg) : arg_(arg) {} + explicit CharConverter(internal::Arg &arg) + : arg_(arg) + { + } - template - void visit_any_int(T value) + template void visit_any_int(T value) { arg_.type = internal::Arg::CHAR; arg_.int_value = static_cast(value); @@ -234,15 +228,17 @@ private: FMT_DISALLOW_COPY_AND_ASSIGN(WidthHandler); public: - explicit WidthHandler(FormatSpec &spec) : spec_(spec) {} + explicit WidthHandler(FormatSpec &spec) + : spec_(spec) + { + } void report_unhandled_arg() { FMT_THROW(FormatError("width is not integer")); } - template - unsigned visit_any_int(T value) + template unsigned visit_any_int(T value) { typedef typename internal::IntTraits::MainType UnsignedType; UnsignedType width = static_cast(value); @@ -257,7 +253,7 @@ public: return static_cast(width); } }; -} // namespace internal +} // namespace internal /** \rst @@ -276,9 +272,7 @@ public: superclass will be called. \endrst */ -template -class BasicPrintfArgFormatter : - public internal::ArgFormatterBase +template class BasicPrintfArgFormatter : public internal::ArgFormatterBase { private: void write_null_pointer() @@ -298,7 +292,9 @@ public: \endrst */ BasicPrintfArgFormatter(BasicWriter &w, Spec &s) - : internal::ArgFormatterBase(w, s) {} + : internal::ArgFormatterBase(w, s) + { + } /** Formats an argument of type ``bool``. */ void visit_bool(bool value) @@ -371,19 +367,18 @@ public: }; /** The default printf argument formatter. */ -template -class PrintfArgFormatter : - public BasicPrintfArgFormatter, Char, FormatSpec> +template class PrintfArgFormatter : public BasicPrintfArgFormatter, Char, FormatSpec> { public: /** Constructs an argument formatter object. */ PrintfArgFormatter(BasicWriter &w, FormatSpec &s) - : BasicPrintfArgFormatter, Char, FormatSpec>(w, s) {} + : BasicPrintfArgFormatter, Char, FormatSpec>(w, s) + { + } }; /** This template formats data and writes the output to a writer. */ -template > -class PrintfFormatter : private internal::FormatterBase +template > class PrintfFormatter : private internal::FormatterBase { private: BasicWriter &writer_; @@ -392,9 +387,7 @@ private: // Returns the argument with specified index or, if arg_index is equal // to the maximum unsigned value, the next argument. - internal::Arg get_arg( - const Char *s, - unsigned arg_index = (std::numeric_limits::max)()); + internal::Arg get_arg(const Char *s, unsigned arg_index = (std::numeric_limits::max)()); // Parses argument index, flags and width and returns the argument index. unsigned parse_header(const Char *&s, FormatSpec &spec); @@ -408,14 +401,16 @@ public: \endrst */ explicit PrintfFormatter(const ArgList &al, BasicWriter &w) - : FormatterBase(al), writer_(w) {} + : FormatterBase(al) + , writer_(w) + { + } /** Formats stored arguments and writes the output to the writer. */ void format(BasicCStringRef format_str); }; -template -void PrintfFormatter::parse_flags(FormatSpec &spec, const Char *&s) +template void PrintfFormatter::parse_flags(FormatSpec &spec, const Char *&s) { for (;;) { @@ -443,22 +438,17 @@ void PrintfFormatter::parse_flags(FormatSpec &spec, const Char *&s) } } -template -internal::Arg PrintfFormatter::get_arg(const Char *s, - unsigned arg_index) +template internal::Arg PrintfFormatter::get_arg(const Char *s, unsigned arg_index) { (void)s; const char *error = FMT_NULL; - internal::Arg arg = arg_index == std::numeric_limits::max() ? - next_arg(error) : FormatterBase::get_arg(arg_index - 1, error); + internal::Arg arg = arg_index == std::numeric_limits::max() ? next_arg(error) : FormatterBase::get_arg(arg_index - 1, error); if (error) FMT_THROW(FormatError(!*s ? "invalid format string" : error)); return arg; } -template -unsigned PrintfFormatter::parse_header( - const Char *&s, FormatSpec &spec) +template unsigned PrintfFormatter::parse_header(const Char *&s, FormatSpec &spec) { unsigned arg_index = std::numeric_limits::max(); Char c = *s; @@ -467,7 +457,7 @@ unsigned PrintfFormatter::parse_header( // Parse an argument index (if followed by '$') or a width possibly // preceded with '0' flag(s). unsigned value = internal::parse_nonnegative_int(s); - if (*s == '$') // value is an argument index + if (*s == '$') // value is an argument index { ++s; arg_index = value; @@ -499,15 +489,15 @@ unsigned PrintfFormatter::parse_header( return arg_index; } -template -void PrintfFormatter::format(BasicCStringRef format_str) +template void PrintfFormatter::format(BasicCStringRef format_str) { const Char *start = format_str.c_str(); const Char *s = start; while (*s) { Char c = *s++; - if (c != '%') continue; + if (c != '%') + continue; if (*s == c) { write(writer_, start, s); @@ -550,7 +540,7 @@ void PrintfFormatter::format(BasicCStringRef format_str) if (arg.type <= Arg::LAST_NUMERIC_TYPE) spec.align_ = ALIGN_NUMERIC; else - spec.fill_ = ' '; // Ignore '0' flag for non-numeric types. + spec.fill_ = ' '; // Ignore '0' flag for non-numeric types. } // Parse length and convert the argument to the required type. @@ -703,10 +693,10 @@ inline int fprintf(std::ostream &os, CStringRef format_str, ArgList args) return static_cast(w.size()); } FMT_VARIADIC(int, fprintf, std::ostream &, CStringRef) -} // namespace fmt +} // namespace fmt #ifdef FMT_HEADER_ONLY -# include "printf.cc" +#include "printf.cc" #endif -#endif // FMT_PRINTF_H_ +#endif // FMT_PRINTF_H_ diff --git a/include/spdlog/fmt/bundled/time.h b/include/spdlog/fmt/bundled/time.h index 206d0920..e06fa5b4 100644 --- a/include/spdlog/fmt/bundled/time.h +++ b/include/spdlog/fmt/bundled/time.h @@ -14,16 +14,13 @@ #include #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable: 4702) // unreachable code -# pragma warning(disable: 4996) // "deprecated" functions +#pragma warning(push) +#pragma warning(disable : 4702) // unreachable code +#pragma warning(disable : 4996) // "deprecated" functions #endif -namespace fmt -{ -template -void format_arg(BasicFormatter &f, - const char *&format_str, const std::tm &tm) +namespace fmt { +template void format_arg(BasicFormatter &f, const char *&format_str, const std::tm &tm) { if (*format_str == ':') ++format_str; @@ -60,8 +57,7 @@ void format_arg(BasicFormatter &f, format_str = end + 1; } -namespace internal -{ +namespace internal { inline Null<> localtime_r(...) { return Null<>(); @@ -78,7 +74,7 @@ inline Null<> gmtime_s(...) { return Null<>(); } -} +} // namespace internal // Thread-safe replacement for std::localtime inline std::tm localtime(std::time_t time) @@ -88,7 +84,10 @@ inline std::tm localtime(std::time_t time) std::time_t time_; std::tm tm_; - LocalTime(std::time_t t): time_(t) {} + LocalTime(std::time_t t) + : time_(t) + { + } bool run() { @@ -116,7 +115,8 @@ inline std::tm localtime(std::time_t time) { using namespace fmt::internal; std::tm *tm = std::localtime(&time_); - if (tm) tm_ = *tm; + if (tm) + tm_ = *tm; return tm != FMT_NULL; } }; @@ -136,7 +136,10 @@ inline std::tm gmtime(std::time_t time) std::time_t time_; std::tm tm_; - GMTime(std::time_t t): time_(t) {} + GMTime(std::time_t t) + : time_(t) + { + } bool run() { @@ -163,7 +166,8 @@ inline std::tm gmtime(std::time_t time) bool fallback(internal::Null<>) { std::tm *tm = std::gmtime(&time_); - if (tm != FMT_NULL) tm_ = *tm; + if (tm != FMT_NULL) + tm_ = *tm; return tm != FMT_NULL; } }; @@ -174,10 +178,10 @@ inline std::tm gmtime(std::time_t time) FMT_THROW(fmt::FormatError("time_t value out of range")); return std::tm(); } -} //namespace fmt +} // namespace fmt #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif -#endif // FMT_TIME_H_ +#endif // FMT_TIME_H_ diff --git a/include/spdlog/fmt/fmt.h b/include/spdlog/fmt/fmt.h index 92ca4e50..e2e04854 100644 --- a/include/spdlog/fmt/fmt.h +++ b/include/spdlog/fmt/fmt.h @@ -23,7 +23,7 @@ #include "bundled/printf.h" #endif -#else //external fmtlib +#else // external fmtlib #include #if defined(SPDLOG_FMT_PRINTF) @@ -31,4 +31,3 @@ #endif #endif - diff --git a/include/spdlog/fmt/ostr.h b/include/spdlog/fmt/ostr.h index 5cdd5cd0..cf4c32c5 100644 --- a/include/spdlog/fmt/ostr.h +++ b/include/spdlog/fmt/ostr.h @@ -8,10 +8,8 @@ // include external or bundled copy of fmtlib's ostream support // #if !defined(SPDLOG_FMT_EXTERNAL) -#include "fmt.h" #include "bundled/ostream.h" +#include "fmt.h" #else #include #endif - - diff --git a/include/spdlog/formatter.h b/include/spdlog/formatter.h index 203dc31a..55388ec5 100644 --- a/include/spdlog/formatter.h +++ b/include/spdlog/formatter.h @@ -7,14 +7,12 @@ #include "details/log_msg.h" -#include -#include #include +#include +#include -namespace spdlog -{ -namespace details -{ +namespace spdlog { +namespace details { class flag_formatter; } @@ -22,26 +20,27 @@ class formatter { public: virtual ~formatter() = default; - virtual void format(details::log_msg& msg) = 0; + virtual void format(details::log_msg &msg) = 0; }; class pattern_formatter SPDLOG_FINAL : public formatter { public: - explicit pattern_formatter(const std::string& pattern, pattern_time_type pattern_time = pattern_time_type::local, std::string eol = spdlog::details::os::default_eol); - pattern_formatter(const pattern_formatter&) = delete; - pattern_formatter& operator=(const pattern_formatter&) = delete; - void format(details::log_msg& msg) override; + explicit pattern_formatter(const std::string &pattern, pattern_time_type pattern_time = pattern_time_type::local, + std::string eol = spdlog::details::os::default_eol); + pattern_formatter(const pattern_formatter &) = delete; + pattern_formatter &operator=(const pattern_formatter &) = delete; + void format(details::log_msg &msg) override; private: const std::string _eol; const std::string _pattern; const pattern_time_type _pattern_time; std::vector> _formatters; - std::tm get_time(details::log_msg& msg); + std::tm get_time(details::log_msg &msg); void handle_flag(char flag); - void compile_pattern(const std::string& pattern); + void compile_pattern(const std::string &pattern); }; -} +} // namespace spdlog #include "details/pattern_formatter_impl.h" diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 5502d273..4f3bfa56 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -12,63 +12,61 @@ // 2. Format the message using the formatter function // 3. Pass the formatted message to its sinks to performa the actual logging -#include "sinks/base_sink.h" #include "common.h" +#include "sinks/base_sink.h" -#include #include #include +#include -namespace spdlog -{ +namespace spdlog { class logger { public: - logger(const std::string& name, sink_ptr single_sink); - logger(const std::string& name, sinks_init_list sinks); + logger(const std::string &name, sink_ptr single_sink); + logger(const std::string &name, sinks_init_list sinks); - template - logger(std::string name, const It& begin, const It& end); + template logger(std::string name, const It &begin, const It &end); virtual ~logger(); - logger(const logger&) = delete; - logger& operator=(const logger&) = delete; + logger(const logger &) = delete; + logger &operator=(const logger &) = delete; - template void log(level::level_enum lvl, const char* fmt, const Args&... args); - template void log(level::level_enum lvl, const char* msg); - template void trace(const char* fmt, const Arg1&, const Args&... args); - template void debug(const char* fmt, const Arg1&, const Args&... args); - template void info(const char* fmt, const Arg1&, const Args&... args); - template void warn(const char* fmt, const Arg1&, const Args&... args); - template void error(const char* fmt, const Arg1&, const Args&... args); - template void critical(const char* fmt, const Arg1&, const Args&... args); + template void log(level::level_enum lvl, const char *fmt, const Args &... args); + template void log(level::level_enum lvl, const char *msg); + template void trace(const char *fmt, const Arg1 &, const Args &... args); + template void debug(const char *fmt, const Arg1 &, const Args &... args); + template void info(const char *fmt, const Arg1 &, const Args &... args); + template void warn(const char *fmt, const Arg1 &, const Args &... args); + template void error(const char *fmt, const Arg1 &, const Args &... args); + template void critical(const char *fmt, const Arg1 &, const Args &... args); #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT - template void log(level::level_enum lvl, const wchar_t* msg); - template void log(level::level_enum lvl, const wchar_t* fmt, const Args&... args); - template void trace(const wchar_t* fmt, const Args&... args); - template void debug(const wchar_t* fmt, const Args&... args); - template void info(const wchar_t* fmt, const Args&... args); - template void warn(const wchar_t* fmt, const Args&... args); - template void error(const wchar_t* fmt, const Args&... args); - template void critical(const wchar_t* fmt, const Args&... args); + template void log(level::level_enum lvl, const wchar_t *msg); + template void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); + template void trace(const wchar_t *fmt, const Args &... args); + template void debug(const wchar_t *fmt, const Args &... args); + template void info(const wchar_t *fmt, const Args &... args); + template void warn(const wchar_t *fmt, const Args &... args); + template void error(const wchar_t *fmt, const Args &... args); + template void critical(const wchar_t *fmt, const Args &... args); #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT - template void log(level::level_enum lvl, const T&); - template void trace(const T& msg); - template void debug(const T& msg); - template void info(const T& msg); - template void warn(const T& msg); - template void error(const T& msg); - template void critical(const T& msg); + template void log(level::level_enum lvl, const T &); + template void trace(const T &msg); + template void debug(const T &msg); + template void info(const T &msg); + template void warn(const T &msg); + template void error(const T &msg); + template void critical(const T &msg); bool should_log(level::level_enum msg_level) const; void set_level(level::level_enum log_level); level::level_enum level() const; - const std::string& name() const; - void set_pattern(const std::string& pattern, pattern_time_type pattern_time = pattern_time_type::local); + const std::string &name() const; + void set_pattern(const std::string &pattern, pattern_time_type pattern_time = pattern_time_type::local); void set_formatter(formatter_ptr msg_formatter); // automatically call flush() if message level >= log_level @@ -76,25 +74,25 @@ public: virtual void flush(); - const std::vector& sinks() const; + const std::vector &sinks() const; // error handler virtual void set_error_handler(log_err_handler err_handler); virtual log_err_handler error_handler(); protected: - virtual void _sink_it(details::log_msg& msg); - virtual void _set_pattern(const std::string& pattern, pattern_time_type pattern_time); + virtual void _sink_it(details::log_msg &msg); + virtual void _set_pattern(const std::string &pattern, pattern_time_type pattern_time); virtual void _set_formatter(formatter_ptr msg_formatter); // default error handler: print the error to stderr with the max rate of 1 message/minute virtual void _default_err_handler(const std::string &msg); // return true if the given message level should trigger a flush - bool _should_flush_on(const details::log_msg& msg); + bool _should_flush_on(const details::log_msg &msg); // increment the message count (only if defined(SPDLOG_ENABLE_MESSAGE_COUNTER)) - void _incr_msg_counter(details::log_msg& msg); + void _incr_msg_counter(details::log_msg &msg); const std::string _name; std::vector _sinks; @@ -105,6 +103,6 @@ protected: std::atomic _last_err_time; std::atomic _msg_counter; }; -} +} // namespace spdlog #include "details/logger_impl.h" diff --git a/include/spdlog/sinks/android_sink.h b/include/spdlog/sinks/android_sink.h index e3766755..1284441e 100644 --- a/include/spdlog/sinks/android_sink.h +++ b/include/spdlog/sinks/android_sink.h @@ -7,34 +7,35 @@ #if defined(__ANDROID__) -#include "sink.h" #include "../details/os.h" +#include "sink.h" +#include +#include #include #include -#include #include -#include #if !defined(SPDLOG_ANDROID_RETRIES) #define SPDLOG_ANDROID_RETRIES 2 #endif -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /* -* Android sink (logging using __android_log_write) -* __android_log_write is thread-safe. No lock is needed. -*/ + * Android sink (logging using __android_log_write) + * __android_log_write is thread-safe. No lock is needed. + */ class android_sink : public sink { public: - explicit android_sink(const std::string& tag = "spdlog", bool use_raw_msg = false): _tag(tag), _use_raw_msg(use_raw_msg) {} + explicit android_sink(const std::string &tag = "spdlog", bool use_raw_msg = false) + : _tag(tag) + , _use_raw_msg(use_raw_msg) + { + } - void log(const details::log_msg& msg) override + void log(const details::log_msg &msg) override { const android_LogPriority priority = convert_to_android(msg.level); const char *msg_output = (_use_raw_msg ? msg.raw.c_str() : msg.formatted.c_str()); @@ -42,7 +43,7 @@ public: // See system/core/liblog/logger_write.c for explanation of return value int ret = __android_log_write(priority, _tag.c_str(), msg_output); int retry_count = 0; - while ((ret == -11/*EAGAIN*/) && (retry_count < SPDLOG_ANDROID_RETRIES)) + while ((ret == -11 /*EAGAIN*/) && (retry_count < SPDLOG_ANDROID_RETRIES)) { details::os::sleep_for_millis(5); ret = __android_log_write(priority, _tag.c_str(), msg_output); @@ -55,14 +56,12 @@ public: } } - void flush() override - { - } + void flush() override {} private: static android_LogPriority convert_to_android(spdlog::level::level_enum level) { - switch(level) + switch (level) { case spdlog::level::trace: return ANDROID_LOG_VERBOSE; @@ -85,7 +84,6 @@ private: bool _use_raw_msg; }; -} -} +}} // namespace spdlog::sinks #endif diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index 4bd884cc..7cb2b3e7 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -5,28 +5,25 @@ #pragma once -#include "base_sink.h" #include "../common.h" #include "../details/os.h" +#include "base_sink.h" #include #include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /** * This sink prefixes the output with an ANSI escape sequence color code depending on the severity * of the message. * If no color terminal detected, omit the escape codes. */ -template -class ansicolor_sink : public base_sink +template class ansicolor_sink : public base_sink { public: - explicit ansicolor_sink(FILE* file) : target_file_(file) + explicit ansicolor_sink(FILE *file) + : target_file_(file) { should_do_colors_ = details::os::in_terminal(file) && details::os::is_color_terminal(); colors_[level::trace] = cyan; @@ -43,7 +40,7 @@ public: _flush(); } - void set_color(level::level_enum color_level, const std::string& color) + void set_color(level::level_enum color_level, const std::string &color) { std::lock_guard lock(base_sink::_mutex); colors_[color_level] = color; @@ -80,13 +77,13 @@ public: const std::string on_white = "\033[47m"; protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { // Wrap the originally formatted message in color codes. // If color is not supported in the terminal, log as is instead. if (should_do_colors_) { - const std::string& prefix = colors_[msg.level]; + const std::string &prefix = colors_[msg.level]; fwrite(prefix.data(), sizeof(char), prefix.size(), target_file_); fwrite(msg.formatted.data(), sizeof(char), msg.formatted.size(), target_file_); fwrite(reset.data(), sizeof(char), reset.size(), target_file_); @@ -104,34 +101,33 @@ protected: fflush(target_file_); } - FILE* target_file_; + FILE *target_file_; bool should_do_colors_; std::unordered_map colors_; }; - -template -class ansicolor_stdout_sink: public ansicolor_sink +template class ansicolor_stdout_sink : public ansicolor_sink { public: - ansicolor_stdout_sink(): ansicolor_sink(stdout) - {} + ansicolor_stdout_sink() + : ansicolor_sink(stdout) + { + } }; using ansicolor_stdout_sink_mt = ansicolor_stdout_sink; using ansicolor_stdout_sink_st = ansicolor_stdout_sink; -template -class ansicolor_stderr_sink: public ansicolor_sink +template class ansicolor_stderr_sink : public ansicolor_sink { public: - ansicolor_stderr_sink(): ansicolor_sink(stderr) - {} + ansicolor_stderr_sink() + : ansicolor_sink(stderr) + { + } }; using ansicolor_stderr_sink_mt = ansicolor_stderr_sink; using ansicolor_stderr_sink_st = ansicolor_stderr_sink; -} // namespace sinks -} // namespace spdlog - +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/base_sink.h b/include/spdlog/sinks/base_sink.h index 1d975892..bf67a59c 100644 --- a/include/spdlog/sinks/base_sink.h +++ b/include/spdlog/sinks/base_sink.h @@ -10,27 +10,23 @@ // all locking is taken care of here so no locking needed by the implementers.. // -#include "sink.h" -#include "../formatter.h" #include "../common.h" #include "../details/log_msg.h" +#include "../formatter.h" +#include "sink.h" #include -namespace spdlog -{ -namespace sinks -{ -template -class base_sink : public sink +namespace spdlog { namespace sinks { +template class base_sink : public sink { public: base_sink() = default; - base_sink(const base_sink&) = delete; - base_sink& operator=(const base_sink&) = delete; + base_sink(const base_sink &) = delete; + base_sink &operator=(const base_sink &) = delete; - void log(const details::log_msg& msg) SPDLOG_FINAL override + void log(const details::log_msg &msg) SPDLOG_FINAL override { std::lock_guard lock(_mutex); _sink_it(msg); @@ -43,9 +39,8 @@ public: } protected: - virtual void _sink_it(const details::log_msg& msg) = 0; + virtual void _sink_it(const details::log_msg &msg) = 0; virtual void _flush() = 0; Mutex _mutex; }; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/dist_sink.h b/include/spdlog/sinks/dist_sink.h index 39f162c5..b204790b 100644 --- a/include/spdlog/sinks/dist_sink.h +++ b/include/spdlog/sinks/dist_sink.h @@ -11,32 +11,31 @@ #include "sink.h" #include -#include #include +#include #include // Distribution sink (mux). Stores a vector of sinks which get called when log is called -namespace spdlog -{ -namespace sinks -{ -template -class dist_sink : public base_sink +namespace spdlog { namespace sinks { +template class dist_sink : public base_sink { public: - explicit dist_sink() :_sinks() {} - dist_sink(const dist_sink&) = delete; - dist_sink& operator=(const dist_sink&) = delete; + explicit dist_sink() + : _sinks() + { + } + dist_sink(const dist_sink &) = delete; + dist_sink &operator=(const dist_sink &) = delete; protected: std::vector> _sinks; - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { for (auto &sink : _sinks) { - if( sink->should_log( msg.level)) + if (sink->should_log(msg.level)) { sink->log(msg); } @@ -66,5 +65,4 @@ public: using dist_sink_mt = dist_sink; using dist_sink_st = dist_sink; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/file_sinks.h b/include/spdlog/sinks/file_sinks.h index 39f7b7bb..48322e83 100644 --- a/include/spdlog/sinks/file_sinks.h +++ b/include/spdlog/sinks/file_sinks.h @@ -5,31 +5,28 @@ #pragma once -#include "base_sink.h" -#include "../details/null_mutex.h" #include "../details/file_helper.h" +#include "../details/null_mutex.h" #include "../fmt/fmt.h" +#include "base_sink.h" #include +#include #include #include #include #include #include -#include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /* * Trivial file sink with single file as target */ -template -class simple_file_sink SPDLOG_FINAL : public base_sink +template class simple_file_sink SPDLOG_FINAL : public base_sink { public: - explicit simple_file_sink(const filename_t &filename, bool truncate = false):_force_flush(false) + explicit simple_file_sink(const filename_t &filename, bool truncate = false) + : _force_flush(false) { _file_helper.open(filename, truncate); } @@ -40,10 +37,10 @@ public: } protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { _file_helper.write(msg); - if(_force_flush) + if (_force_flush) _file_helper.flush(); } @@ -63,23 +60,21 @@ using simple_file_sink_st = simple_file_sink; /* * Rotating file sink based on size */ -template -class rotating_file_sink SPDLOG_FINAL : public base_sink +template class rotating_file_sink SPDLOG_FINAL : public base_sink { public: - rotating_file_sink(filename_t base_filename, - std::size_t max_size, std::size_t max_files) : - _base_filename(std::move(base_filename)), - _max_size(max_size), - _max_files(max_files) + rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files) + : _base_filename(std::move(base_filename)) + , _max_size(max_size) + , _max_files(max_files) { _file_helper.open(calc_filename(_base_filename, 0)); - _current_size = _file_helper.size(); //expensive. called only once + _current_size = _file_helper.size(); // expensive. called only once } // calc filename according to index and file extension if exists. // e.g. calc_filename("logs/mylog.txt, 3) => "logs/mylog.3.txt". - static filename_t calc_filename(const filename_t& filename, std::size_t index) + static filename_t calc_filename(const filename_t &filename, std::size_t index) { typename std::conditional::value, fmt::MemoryWriter, fmt::WMemoryWriter>::type w; if (index != 0u) @@ -96,7 +91,7 @@ public: } protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { _current_size += msg.formatted.size(); if (_current_size > _max_size) @@ -158,13 +153,14 @@ using rotating_file_sink_st = rotating_file_sink; struct default_daily_file_name_calculator { // Create filename for the form filename.YYYY-MM-DD_hh-mm.ext - static filename_t calc_filename(const filename_t& filename) + static filename_t calc_filename(const filename_t &filename) { std::tm tm = spdlog::details::os::localtime(); filename_t basename, ext; std::tie(basename, ext) = details::file_helper::split_by_extenstion(filename); std::conditional::value, fmt::MemoryWriter, fmt::WMemoryWriter>::type w; - w.write(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}-{:02d}{}"), basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, ext); + w.write(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}-{:02d}{}"), basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, ext); return w.str(); } }; @@ -175,7 +171,7 @@ struct default_daily_file_name_calculator struct dateonly_daily_file_name_calculator { // Create filename for the form basename.YYYY-MM-DD - static filename_t calc_filename(const filename_t& filename) + static filename_t calc_filename(const filename_t &filename) { std::tm tm = spdlog::details::os::localtime(); filename_t basename, ext; @@ -189,18 +185,14 @@ struct dateonly_daily_file_name_calculator /* * Rotating file sink based on date. rotates at midnight */ -template -class daily_file_sink SPDLOG_FINAL :public base_sink < Mutex > +template class daily_file_sink SPDLOG_FINAL : public base_sink { public: - //create daily file sink which rotates on given time - daily_file_sink( - filename_t base_filename, - int rotation_hour, - int rotation_minute) : - _base_filename(std::move(base_filename)), - _rotation_h(rotation_hour), - _rotation_m(rotation_minute) + // create daily file sink which rotates on given time + daily_file_sink(filename_t base_filename, int rotation_hour, int rotation_minute) + : _base_filename(std::move(base_filename)) + , _rotation_h(rotation_hour) + , _rotation_m(rotation_minute) { if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59) throw spdlog_ex("daily_file_sink: Invalid rotation time in ctor"); @@ -208,9 +200,8 @@ public: _file_helper.open(FileNameCalc::calc_filename(_base_filename)); } - protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { if (std::chrono::system_clock::now() >= _rotation_tp) { @@ -239,7 +230,7 @@ private: { return rotation_time; } - return{ rotation_time + std::chrono::hours(24) }; + return {rotation_time + std::chrono::hours(24)}; } filename_t _base_filename; @@ -252,5 +243,4 @@ private: using daily_file_sink_mt = daily_file_sink; using daily_file_sink_st = daily_file_sink; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/msvc_sink.h b/include/spdlog/sinks/msvc_sink.h index d230613e..e58d49ce 100644 --- a/include/spdlog/sinks/msvc_sink.h +++ b/include/spdlog/sinks/msvc_sink.h @@ -7,43 +7,35 @@ #if defined(_WIN32) -#include "base_sink.h" #include "../details/null_mutex.h" +#include "base_sink.h" #include #include #include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /* -* MSVC sink (logging using OutputDebugStringA) -*/ -template -class msvc_sink : public base_sink + * MSVC sink (logging using OutputDebugStringA) + */ +template class msvc_sink : public base_sink { public: - explicit msvc_sink() - { - } + explicit msvc_sink() {} protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { OutputDebugStringA(msg.formatted.c_str()); } - void _flush() override - {} + void _flush() override {} }; using msvc_sink_mt = msvc_sink; using msvc_sink_st = msvc_sink; -} -} +}} // namespace spdlog::sinks #endif diff --git a/include/spdlog/sinks/null_sink.h b/include/spdlog/sinks/null_sink.h index 9a4fd08d..d8eab97c 100644 --- a/include/spdlog/sinks/null_sink.h +++ b/include/spdlog/sinks/null_sink.h @@ -5,31 +5,22 @@ #pragma once -#include "base_sink.h" #include "../details/null_mutex.h" +#include "base_sink.h" #include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { -template -class null_sink : public base_sink +template class null_sink : public base_sink { protected: - void _sink_it(const details::log_msg&) override - {} - - void _flush() override - {} + void _sink_it(const details::log_msg &) override {} + void _flush() override {} }; using null_sink_mt = null_sink; using null_sink_st = null_sink; -} -} - +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/ostream_sink.h b/include/spdlog/sinks/ostream_sink.h index 9648cc05..bb79de76 100644 --- a/include/spdlog/sinks/ostream_sink.h +++ b/include/spdlog/sinks/ostream_sink.h @@ -8,23 +8,23 @@ #include "../details/null_mutex.h" #include "base_sink.h" -#include #include +#include -namespace spdlog -{ -namespace sinks -{ -template -class ostream_sink : public base_sink +namespace spdlog { namespace sinks { +template class ostream_sink : public base_sink { public: - explicit ostream_sink(std::ostream& os, bool force_flush=false) :_ostream(os), _force_flush(force_flush) {} - ostream_sink(const ostream_sink&) = delete; - ostream_sink& operator=(const ostream_sink&) = delete; + explicit ostream_sink(std::ostream &os, bool force_flush = false) + : _ostream(os) + , _force_flush(force_flush) + { + } + ostream_sink(const ostream_sink &) = delete; + ostream_sink &operator=(const ostream_sink &) = delete; protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { _ostream.write(msg.formatted.data(), msg.formatted.size()); if (_force_flush) @@ -36,12 +36,11 @@ protected: _ostream.flush(); } - std::ostream& _ostream; + std::ostream &_ostream; bool _force_flush; }; using ostream_sink_mt = ostream_sink; using ostream_sink_st = ostream_sink; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/sink.h b/include/spdlog/sinks/sink.h index ff7a144e..f3c146d9 100644 --- a/include/spdlog/sinks/sink.h +++ b/include/spdlog/sinks/sink.h @@ -7,16 +7,13 @@ #include "../details/log_msg.h" -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { class sink { public: virtual ~sink() = default; - virtual void log(const details::log_msg& msg) = 0; + virtual void log(const details::log_msg &msg) = 0; virtual void flush() = 0; bool should_log(level::level_enum msg_level) const; @@ -24,7 +21,7 @@ public: level::level_enum level() const; private: - level_t _level{ level::trace }; + level_t _level{level::trace}; }; inline bool sink::should_log(level::level_enum msg_level) const @@ -42,5 +39,4 @@ inline level::level_enum sink::level() const return static_cast(_level.load(std::memory_order_relaxed)); } -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/stdout_sinks.h b/include/spdlog/sinks/stdout_sinks.h index 0567a05d..4494323b 100644 --- a/include/spdlog/sinks/stdout_sinks.h +++ b/include/spdlog/sinks/stdout_sinks.h @@ -12,13 +12,9 @@ #include #include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { -template -class stdout_sink SPDLOG_FINAL : public base_sink +template class stdout_sink SPDLOG_FINAL : public base_sink { using MyType = stdout_sink; @@ -32,7 +28,7 @@ public: } protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { fwrite(msg.formatted.data(), sizeof(char), msg.formatted.size(), stdout); _flush(); @@ -47,8 +43,7 @@ protected: using stdout_sink_mt = stdout_sink; using stdout_sink_st = stdout_sink; -template -class stderr_sink SPDLOG_FINAL : public base_sink +template class stderr_sink SPDLOG_FINAL : public base_sink { using MyType = stderr_sink; @@ -62,7 +57,7 @@ public: } protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { fwrite(msg.formatted.data(), sizeof(char), msg.formatted.size(), stderr); _flush(); @@ -77,5 +72,4 @@ protected: using stderr_sink_mt = stderr_sink; using stderr_sink_st = stderr_sink; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/syslog_sink.h b/include/spdlog/sinks/syslog_sink.h index d1ffc5c8..e4472f2f 100644 --- a/include/spdlog/sinks/syslog_sink.h +++ b/include/spdlog/sinks/syslog_sink.h @@ -9,18 +9,14 @@ #ifdef SPDLOG_ENABLE_SYSLOG -#include "sink.h" #include "../details/log_msg.h" +#include "sink.h" #include #include #include - -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /** * Sink that write to syslog using the `syscall()` library call. * @@ -30,8 +26,8 @@ class syslog_sink : public sink { public: // - syslog_sink(const std::string& ident = "", int syslog_option=0, int syslog_facility=LOG_USER): - _ident(ident) + syslog_sink(const std::string &ident = "", int syslog_option = 0, int syslog_facility = LOG_USER) + : _ident(ident) { _priorities[static_cast(level::trace)] = LOG_DEBUG; _priorities[static_cast(level::debug)] = LOG_DEBUG; @@ -41,8 +37,8 @@ public: _priorities[static_cast(level::critical)] = LOG_CRIT; _priorities[static_cast(level::off)] = LOG_INFO; - //set ident to be program name if empty - ::openlog(_ident.empty()? nullptr:_ident.c_str(), syslog_option, syslog_facility); + // set ident to be program name if empty + ::openlog(_ident.empty() ? nullptr : _ident.c_str(), syslog_option, syslog_facility); } ~syslog_sink() override @@ -50,22 +46,19 @@ public: ::closelog(); } - syslog_sink(const syslog_sink&) = delete; - syslog_sink& operator=(const syslog_sink&) = delete; + syslog_sink(const syslog_sink &) = delete; + syslog_sink &operator=(const syslog_sink &) = delete; void log(const details::log_msg &msg) override { ::syslog(syslog_prio_from_level(msg), "%s", msg.raw.str().c_str()); } - void flush() override - { - } - + void flush() override {} private: std::array _priorities; - //must store the ident because the man says openlog might use the pointer as is and not a string copy + // must store the ident because the man says openlog might use the pointer as is and not a string copy const std::string _ident; // @@ -76,7 +69,6 @@ private: return _priorities[static_cast(msg.level)]; } }; -} -} +}} // namespace spdlog::sinks #endif diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index 3b4495b0..77ae59e1 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -5,24 +5,20 @@ #pragma once -#include "base_sink.h" -#include "../details/null_mutex.h" #include "../common.h" +#include "../details/null_mutex.h" +#include "base_sink.h" #include #include #include #include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /* * Windows color console sink. Uses WriteConsoleA to write to the console with colors */ -template -class wincolor_sink : public base_sink +template class wincolor_sink : public base_sink { public: const WORD BOLD = FOREGROUND_INTENSITY; @@ -31,13 +27,14 @@ public: const WORD WHITE = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; const WORD YELLOW = FOREGROUND_RED | FOREGROUND_GREEN; - wincolor_sink(HANDLE std_handle): out_handle_(std_handle) + wincolor_sink(HANDLE std_handle) + : out_handle_(std_handle) { colors_[level::trace] = CYAN; colors_[level::debug] = CYAN; colors_[level::info] = WHITE | BOLD; colors_[level::warn] = YELLOW | BOLD; - colors_[level::err] = RED | BOLD; // red bold + colors_[level::err] = RED | BOLD; // red bold colors_[level::critical] = BACKGROUND_RED | WHITE | BOLD; // white bold on red background colors_[level::off] = 0; } @@ -47,8 +44,8 @@ public: this->flush(); } - wincolor_sink(const wincolor_sink& other) = delete; - wincolor_sink& operator=(const wincolor_sink& other) = delete; + wincolor_sink(const wincolor_sink &other) = delete; + wincolor_sink &operator=(const wincolor_sink &other) = delete; // change the color for the given level void set_color(level::level_enum level, WORD color) @@ -58,12 +55,12 @@ public: } protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { auto color = colors_[msg.level]; auto orig_attribs = set_console_attribs(color); WriteConsoleA(out_handle_, msg.formatted.data(), static_cast(msg.formatted.size()), nullptr, nullptr); - SetConsoleTextAttribute(out_handle_, orig_attribs); //reset to orig colors + SetConsoleTextAttribute(out_handle_, orig_attribs); // reset to orig colors } void _flush() override @@ -85,19 +82,20 @@ private: back_color &= static_cast(~(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)); // keep the background color unchanged SetConsoleTextAttribute(out_handle_, attribs | back_color); - return orig_buffer_info.wAttributes; //return orig attribs + return orig_buffer_info.wAttributes; // return orig attribs } }; // // windows color console to stdout // -template -class wincolor_stdout_sink : public wincolor_sink +template class wincolor_stdout_sink : public wincolor_sink { public: - wincolor_stdout_sink() : wincolor_sink(GetStdHandle(STD_OUTPUT_HANDLE)) - {} + wincolor_stdout_sink() + : wincolor_sink(GetStdHandle(STD_OUTPUT_HANDLE)) + { + } }; using wincolor_stdout_sink_mt = wincolor_stdout_sink; @@ -106,16 +104,16 @@ using wincolor_stdout_sink_st = wincolor_stdout_sink; // // windows color console to stderr // -template -class wincolor_stderr_sink : public wincolor_sink +template class wincolor_stderr_sink : public wincolor_sink { public: - wincolor_stderr_sink() : wincolor_sink(GetStdHandle(STD_ERROR_HANDLE)) - {} + wincolor_stderr_sink() + : wincolor_sink(GetStdHandle(STD_ERROR_HANDLE)) + { + } }; using wincolor_stderr_sink_mt = wincolor_stderr_sink; using wincolor_stderr_sink_st = wincolor_stderr_sink; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/windebug_sink.h b/include/spdlog/sinks/windebug_sink.h index 37d67245..5bd58042 100644 --- a/include/spdlog/sinks/windebug_sink.h +++ b/include/spdlog/sinks/windebug_sink.h @@ -9,21 +9,16 @@ #include "msvc_sink.h" -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /* -* Windows debug sink (logging using OutputDebugStringA, synonym for msvc_sink) -*/ -template -using windebug_sink = msvc_sink; + * Windows debug sink (logging using OutputDebugStringA, synonym for msvc_sink) + */ +template using windebug_sink = msvc_sink; using windebug_sink_mt = msvc_sink_mt; using windebug_sink_st = msvc_sink_st; -} -} +}} // namespace spdlog::sinks #endif diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 8965e59f..34706a38 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -7,30 +7,27 @@ #pragma once - #include "common.h" #include "logger.h" -#include -#include #include +#include +#include #include -namespace spdlog -{ +namespace spdlog { // // Return an existing logger or nullptr if a logger with such name doesn't exist. // example: spdlog::get("my_logger")->info("hello {}", "world"); // -std::shared_ptr get(const std::string& name); - +std::shared_ptr get(const std::string &name); // // Set global formatting // example: spdlog::set_pattern("%Y-%m-%d %H:%M:%S.%e %l : %v"); // -void set_pattern(const std::string& format_string); +void set_pattern(const std::string &format_string); void set_formatter(formatter_ptr f); // @@ -64,80 +61,93 @@ void set_error_handler(log_err_handler handler); // worker_teardown_cb (optional): // callback function that will be called in worker thread upon exit // -void set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, const std::function& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function& worker_teardown_cb = nullptr); +void set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); // Turn off async mode void set_sync_mode(); - // // Create and register multi/single threaded basic file logger. // Basic logger simply writes to given file without any limitations or rotations. // -std::shared_ptr basic_logger_mt(const std::string& logger_name, const filename_t& filename, bool truncate = false); -std::shared_ptr basic_logger_st(const std::string& logger_name, const filename_t& filename, bool truncate = false); +std::shared_ptr basic_logger_mt(const std::string &logger_name, const filename_t &filename, bool truncate = false); +std::shared_ptr basic_logger_st(const std::string &logger_name, const filename_t &filename, bool truncate = false); // // Create and register multi/single threaded rotating file logger // -std::shared_ptr rotating_logger_mt(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files); -std::shared_ptr rotating_logger_st(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files); +std::shared_ptr rotating_logger_mt( + const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files); +std::shared_ptr rotating_logger_st( + const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files); // // Create file logger which creates new file on the given time (default in midnight): // -std::shared_ptr daily_logger_mt(const std::string& logger_name, const filename_t& filename, int hour=0, int minute=0); -std::shared_ptr daily_logger_st(const std::string& logger_name, const filename_t& filename, int hour=0, int minute=0); +std::shared_ptr daily_logger_mt(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0); +std::shared_ptr daily_logger_st(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0); // // Create and register stdout/stderr loggers // -std::shared_ptr stdout_logger_mt(const std::string& logger_name); -std::shared_ptr stdout_logger_st(const std::string& logger_name); -std::shared_ptr stderr_logger_mt(const std::string& logger_name); -std::shared_ptr stderr_logger_st(const std::string& logger_name); +std::shared_ptr stdout_logger_mt(const std::string &logger_name); +std::shared_ptr stdout_logger_st(const std::string &logger_name); +std::shared_ptr stderr_logger_mt(const std::string &logger_name); +std::shared_ptr stderr_logger_st(const std::string &logger_name); // // Create and register colored stdout/stderr loggers // -std::shared_ptr stdout_color_mt(const std::string& logger_name); -std::shared_ptr stdout_color_st(const std::string& logger_name); -std::shared_ptr stderr_color_mt(const std::string& logger_name); -std::shared_ptr stderr_color_st(const std::string& logger_name); - +std::shared_ptr stdout_color_mt(const std::string &logger_name); +std::shared_ptr stdout_color_st(const std::string &logger_name); +std::shared_ptr stderr_color_mt(const std::string &logger_name); +std::shared_ptr stderr_color_st(const std::string &logger_name); // // Create and register a syslog logger // #ifdef SPDLOG_ENABLE_SYSLOG -std::shared_ptr syslog_logger(const std::string& logger_name, const std::string& ident = "", int syslog_option = 0, int syslog_facilty = (1<<3)); +std::shared_ptr syslog_logger( + const std::string &logger_name, const std::string &ident = "", int syslog_option = 0, int syslog_facilty = (1 << 3)); #endif #if defined(__ANDROID__) -std::shared_ptr android_logger(const std::string& logger_name, const std::string& tag = "spdlog"); +std::shared_ptr android_logger(const std::string &logger_name, const std::string &tag = "spdlog"); #endif // Create and register a logger with a single sink -std::shared_ptr create(const std::string& logger_name, const sink_ptr& sink); +std::shared_ptr create(const std::string &logger_name, const sink_ptr &sink); // Create and register a logger with multiple sinks -std::shared_ptr create(const std::string& logger_name, sinks_init_list sinks); -template -std::shared_ptr create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end); - +std::shared_ptr create(const std::string &logger_name, sinks_init_list sinks); +template std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end); // Create and register a logger with templated sink type // Example: // spdlog::create("mylog", "dailylog_filename"); -template -std::shared_ptr create(const std::string& logger_name, Args... args); +template std::shared_ptr create(const std::string &logger_name, Args... args); // Create and register an async logger with a single sink -std::shared_ptr create_async(const std::string& logger_name, const sink_ptr& sink, size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, const std::function& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function& worker_teardown_cb = nullptr); +std::shared_ptr create_async(const std::string &logger_name, const sink_ptr &sink, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); // Create and register an async logger with multiple sinks -std::shared_ptr create_async(const std::string& logger_name, sinks_init_list sinks, size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, const std::function& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function& worker_teardown_cb = nullptr); -template -std::shared_ptr create_async(const std::string& logger_name, const It& sinks_begin, const It& sinks_end, size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, const std::function& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function& worker_teardown_cb = nullptr); +std::shared_ptr create_async(const std::string &logger_name, sinks_init_list sinks, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); +template +std::shared_ptr create_async(const std::string &logger_name, const It &sinks_begin, const It &sinks_end, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); // Register the given logger with the given name void register_logger(std::shared_ptr logger); @@ -153,7 +163,6 @@ void drop(const std::string &name); // Drop all references from the registry void drop_all(); - /////////////////////////////////////////////////////////////////////////////// // // Trace & Debug can be switched on/off at compile time for zero cost debug statements. @@ -168,23 +177,23 @@ void drop_all(); /////////////////////////////////////////////////////////////////////////////// #ifdef SPDLOG_TRACE_ON -# define SPDLOG_STR_H(x) #x -# define SPDLOG_STR_HELPER(x) SPDLOG_STR_H(x) -# ifdef _MSC_VER -# define SPDLOG_TRACE(logger, ...) logger->trace("[ " __FILE__ "(" SPDLOG_STR_HELPER(__LINE__) ") ] " __VA_ARGS__) -# else -# define SPDLOG_TRACE(logger, ...) logger->trace("[ " __FILE__ ":" SPDLOG_STR_HELPER(__LINE__) " ] " __VA_ARGS__) -# endif +#define SPDLOG_STR_H(x) #x +#define SPDLOG_STR_HELPER(x) SPDLOG_STR_H(x) +#ifdef _MSC_VER +#define SPDLOG_TRACE(logger, ...) logger->trace("[ " __FILE__ "(" SPDLOG_STR_HELPER(__LINE__) ") ] " __VA_ARGS__) +#else +#define SPDLOG_TRACE(logger, ...) logger->trace("[ " __FILE__ ":" SPDLOG_STR_HELPER(__LINE__) " ] " __VA_ARGS__) +#endif #else -# define SPDLOG_TRACE(logger, ...) (void)0 +#define SPDLOG_TRACE(logger, ...) (void)0 #endif #ifdef SPDLOG_DEBUG_ON -# define SPDLOG_DEBUG(logger, ...) logger->debug(__VA_ARGS__) +#define SPDLOG_DEBUG(logger, ...) logger->debug(__VA_ARGS__) #else -# define SPDLOG_DEBUG(logger, ...) (void)0 +#define SPDLOG_DEBUG(logger, ...) (void)0 #endif -} +} // namespace spdlog #include "details/spdlog_impl.h" diff --git a/include/spdlog/tweakme.h b/include/spdlog/tweakme.h index c5509622..50ad3fb4 100644 --- a/include/spdlog/tweakme.h +++ b/include/spdlog/tweakme.h @@ -11,7 +11,6 @@ // /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Under Linux, the much faster CLOCK_REALTIME_COARSE clock can be used. // This clock is less accurate - can be off by dozens of millis - depending on the kernel HZ. @@ -20,7 +19,6 @@ // #define SPDLOG_CLOCK_COARSE /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment if date/time logging is not needed and never appear in the log pattern. // This will prevent spdlog from querying the clock on each log call. @@ -31,7 +29,6 @@ // #define SPDLOG_NO_DATETIME /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment if thread id logging is not needed (i.e. no %t in the log pattern). // This will prevent spdlog from querying the thread id on each log call. @@ -41,7 +38,6 @@ // #define SPDLOG_NO_THREAD_ID /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to prevent spdlog from caching thread ids in thread local storage. // By default spdlog saves thread ids in tls to gain a few micros for each call. @@ -51,7 +47,6 @@ // #define SPDLOG_DISABLE_TID_CACHING /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment if logger name logging is not needed. // This will prevent spdlog from copying the logger name on each log call. @@ -66,7 +61,6 @@ // #define SPDLOG_TRACE_ON /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to avoid locking in the registry operations (spdlog::get(), spdlog::drop() spdlog::register()). // Use only if your code never modifies concurrently the registry. @@ -75,7 +69,6 @@ // #define SPDLOG_NO_REGISTRY_MUTEX /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to avoid spdlog's usage of atomic log levels // Use only if your code never modifies a logger's log levels concurrently by different threads. @@ -83,21 +76,18 @@ // #define SPDLOG_NO_ATOMIC_LEVELS /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to enable usage of wchar_t for file names on Windows. // // #define SPDLOG_WCHAR_FILENAMES /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to override default eol ("\n" or "\r\n" under Linux/Windows) // // #define SPDLOG_EOL ";-)\n" /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to use your own copy of the fmt library instead of spdlog's copy. // In this case spdlog will try to include so set your -I flag accordingly. @@ -105,7 +95,6 @@ // #define SPDLOG_FMT_EXTERNAL /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to use printf-style messages in your logs instead of the usual // format-style used by default. @@ -113,28 +102,24 @@ // #define SPDLOG_FMT_PRINTF /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to enable syslog (disabled by default) // // #define SPDLOG_ENABLE_SYSLOG /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to enable wchar_t support (convert to utf8) // // #define SPDLOG_WCHAR_TO_UTF8_SUPPORT /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to prevent child processes from inheriting log file descriptors // // #define SPDLOG_PREVENT_CHILD_FD /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment if your compiler doesn't support the "final" keyword. // The final keyword allows more optimizations in release @@ -144,7 +129,6 @@ // #define SPDLOG_NO_FINAL /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to enable message counting feature. // Use the %i in the logger pattern to display log message sequence id. @@ -152,7 +136,6 @@ // #define SPDLOG_ENABLE_MESSAGE_COUNTER /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to customize level names (e.g. "MT TRACE") // diff --git a/tests/errors.cpp b/tests/errors.cpp index c8281d63..1e1826fb 100644 --- a/tests/errors.cpp +++ b/tests/errors.cpp @@ -1,22 +1,18 @@ /* -* 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 +#include - - - -class failing_sink: public spdlog::sinks::sink +class failing_sink : public spdlog::sinks::sink { - void log(const spdlog::details::log_msg& msg) override + void log(const spdlog::details::log_msg &msg) override { throw std::runtime_error("some error happened during log"); } - void flush() override - {} + void flush() override {} }; TEST_CASE("default_error_handler", "[errors]]") @@ -39,21 +35,16 @@ TEST_CASE("default_error_handler", "[errors]]") REQUIRE(count_lines(filename) == 1); } - - - struct custom_ex -{}; +{ +}; TEST_CASE("custom_error_handler", "[errors]]") { prepare_logdir(); std::string filename = "logs/simple_log.txt"; auto logger = spdlog::create("logger", filename, true); logger->flush_on(spdlog::level::info); - logger->set_error_handler([=](const std::string& msg) - { - throw custom_ex(); - }); + logger->set_error_handler([=](const std::string &msg) { throw custom_ex(); }); logger->info("Good message #1"); #if !defined(SPDLOG_FMT_PRINTF) REQUIRE_THROWS_AS(logger->info("Bad format msg {} {}", "xxx"), custom_ex); @@ -68,10 +59,7 @@ TEST_CASE("default_error_handler2", "[errors]]") { auto logger = spdlog::create("failed_logger"); - logger->set_error_handler([=](const std::string& msg) - { - throw custom_ex(); - }); + logger->set_error_handler([=](const std::string &msg) { throw custom_ex(); }); REQUIRE_THROWS_AS(logger->info("Some message"), custom_ex); } @@ -83,10 +71,10 @@ TEST_CASE("async_error_handler", "[errors]]") std::string filename = "logs/simple_async_log.txt"; { auto logger = spdlog::create("logger", filename, true); - logger->set_error_handler([=](const std::string& msg) - { + logger->set_error_handler([=](const std::string &msg) { std::ofstream ofs("logs/custom_err.txt"); - if (!ofs) throw std::runtime_error("Failed open logs/custom_err.txt"); + if (!ofs) + throw std::runtime_error("Failed open logs/custom_err.txt"); ofs << err_msg; }); logger->info("Good message #1"); @@ -96,7 +84,7 @@ TEST_CASE("async_error_handler", "[errors]]") logger->info("Bad format msg %s %s", "xxx"); #endif logger->info("Good message #2"); - spdlog::drop("logger"); //force logger to drain the queue and shutdown + spdlog::drop("logger"); // force logger to drain the queue and shutdown spdlog::set_sync_mode(); } REQUIRE(count_lines(filename) == 2); @@ -111,14 +99,14 @@ TEST_CASE("async_error_handler2", "[errors]]") spdlog::set_async_mode(128); { auto logger = spdlog::create("failed_logger"); - logger->set_error_handler([=](const std::string& msg) - { + logger->set_error_handler([=](const std::string &msg) { std::ofstream ofs("logs/custom_err2.txt"); - if (!ofs) throw std::runtime_error("Failed open logs/custom_err2.txt"); + if (!ofs) + throw std::runtime_error("Failed open logs/custom_err2.txt"); ofs << err_msg; }); logger->info("Hello failure"); - spdlog::drop("failed_logger"); //force logger to drain the queue and shutdown + spdlog::drop("failed_logger"); // force logger to drain the queue and shutdown spdlog::set_sync_mode(); } diff --git a/tests/file_helper.cpp b/tests/file_helper.cpp index f57397eb..931c3f3e 100644 --- a/tests/file_helper.cpp +++ b/tests/file_helper.cpp @@ -1,10 +1,10 @@ /* -* 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::log_msg; using spdlog::details::file_helper; +using spdlog::details::log_msg; static const std::string target_filename = "logs/file_helper_test.txt"; @@ -70,7 +70,7 @@ TEST_CASE("file_helper_reopen2", "[file_helper::reopen(false)]]") REQUIRE(helper.size() == expected_size); } -static void test_split_ext(const char* fname, const char* expect_base, const char* expect_ext) +static void test_split_ext(const char *fname, const char *expect_base, const char *expect_ext) { spdlog::filename_t filename(fname); spdlog::filename_t expected_base(expect_base); diff --git a/tests/file_log.cpp b/tests/file_log.cpp index 086bd5ed..e20071a3 100644 --- a/tests/file_log.cpp +++ b/tests/file_log.cpp @@ -3,7 +3,6 @@ */ #include "includes.h" - TEST_CASE("simple_file_logger", "[simple_logger]]") { prepare_logdir(); @@ -24,7 +23,6 @@ TEST_CASE("simple_file_logger", "[simple_logger]]") REQUIRE(count_lines(filename) == 2); } - TEST_CASE("flush_on", "[flush_on]]") { prepare_logdir(); @@ -69,7 +67,6 @@ TEST_CASE("rotating_file_logger1", "[rotating_logger]]") REQUIRE(count_lines(filename) == 10); } - TEST_CASE("rotating_file_logger2", "[rotating_logger]]") { prepare_logdir(); @@ -96,11 +93,10 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]]") REQUIRE(get_filesize(filename1) <= 1024); } - TEST_CASE("daily_logger", "[daily_logger]]") { prepare_logdir(); - //calculate filename (time based) + // calculate filename (time based) std::string basename = "logs/daily_log"; std::tm tm = spdlog::details::os::localtime(); fmt::MemoryWriter w; @@ -121,15 +117,12 @@ TEST_CASE("daily_logger", "[daily_logger]]") REQUIRE(count_lines(filename) == 10); } - TEST_CASE("daily_logger with dateonly calculator", "[daily_logger_dateonly]]") { - using sink_type = spdlog::sinks::daily_file_sink< - std::mutex, - spdlog::sinks::dateonly_daily_file_name_calculator>; + using sink_type = spdlog::sinks::daily_file_sink; prepare_logdir(); - //calculate filename (time based) + // calculate filename (time based) std::string basename = "logs/daily_dateonly"; std::tm tm = spdlog::details::os::localtime(); fmt::MemoryWriter w; @@ -151,7 +144,7 @@ TEST_CASE("daily_logger with dateonly calculator", "[daily_logger_dateonly]]") struct custom_daily_file_name_calculator { - static spdlog::filename_t calc_filename(const spdlog::filename_t& basename) + static spdlog::filename_t calc_filename(const spdlog::filename_t &basename) { std::tm tm = spdlog::details::os::localtime(); fmt::MemoryWriter w; @@ -162,12 +155,10 @@ struct custom_daily_file_name_calculator TEST_CASE("daily_logger with custom calculator", "[daily_logger_custom]]") { - using sink_type = spdlog::sinks::daily_file_sink< - std::mutex, - custom_daily_file_name_calculator>; + using sink_type = spdlog::sinks::daily_file_sink; prepare_logdir(); - //calculate filename (time based) + // calculate filename (time based) std::string basename = "logs/daily_dateonly"; std::tm tm = spdlog::details::os::localtime(); fmt::MemoryWriter w; @@ -188,7 +179,6 @@ TEST_CASE("daily_logger with custom calculator", "[daily_logger_custom]]") REQUIRE(count_lines(filename) == 10); } - /* * File name calculations */ @@ -211,12 +201,8 @@ TEST_CASE("rotating_file_sink::calc_filename3", "[rotating_file_sink]]") REQUIRE(filename == "rotated.txt"); } - - - - // regex supported only from gcc 4.9 and above -#if defined (_MSC_VER) || !(__GNUC__ <= 4 && __GNUC_MINOR__ < 9) +#if defined(_MSC_VER) || !(__GNUC__ <= 4 && __GNUC_MINOR__ < 9) #include TEST_CASE("daily_file_sink::default_daily_file_name_calculator1", "[daily_file_sink]]") { diff --git a/tests/includes.h b/tests/includes.h index 8e70efad..ccc62d16 100644 --- a/tests/includes.h +++ b/tests/includes.h @@ -1,18 +1,17 @@ #pragma once +#include "catch.hpp" +#include "utils.h" +#include #include +#include #include -#include #include -#include -#include -#include "catch.hpp" -#include "utils.h" +#include #define SPDLOG_TRACE_ON #define SPDLOG_DEBUG_ON -#include "../include/spdlog/spdlog.h" #include "../include/spdlog/sinks/null_sink.h" #include "../include/spdlog/sinks/ostream_sink.h" - +#include "../include/spdlog/spdlog.h" diff --git a/tests/registry.cpp b/tests/registry.cpp index 1936932a..ff84cacf 100644 --- a/tests/registry.cpp +++ b/tests/registry.cpp @@ -7,23 +7,24 @@ TEST_CASE("register_drop", "[registry]") { spdlog::drop_all(); spdlog::create(tested_logger_name); - REQUIRE(spdlog::get(tested_logger_name)!=nullptr); - //Throw if registring existing name + REQUIRE(spdlog::get(tested_logger_name) != nullptr); + // Throw if registring existing name 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()); spdlog::register_logger(logger); REQUIRE(spdlog::get(tested_logger_name) != nullptr); - //Throw if registring existing name + // Throw if registring existing name REQUIRE_THROWS_AS(spdlog::create(tested_logger_name), spdlog::spdlog_ex); } -TEST_CASE("apply_all" "[registry]") +TEST_CASE("apply_all" + "[registry]") { spdlog::drop_all(); auto logger = std::make_shared(tested_logger_name, std::make_shared()); @@ -32,26 +33,20 @@ TEST_CASE("apply_all" "[registry]") spdlog::register_logger(logger2); int counter = 0; - spdlog::apply_all([&counter](std::shared_ptr l) - { - counter++; - }); + spdlog::apply_all([&counter](std::shared_ptr l) { counter++; }); REQUIRE(counter == 2); counter = 0; spdlog::drop(tested_logger_name2); - spdlog::apply_all([&counter](std::shared_ptr l) - { + spdlog::apply_all([&counter](std::shared_ptr l) { REQUIRE(l->name() == tested_logger_name); counter++; - } - ); + }); REQUIRE(counter == 1); } - - -TEST_CASE("drop" "[registry]") +TEST_CASE("drop" + "[registry]") { spdlog::drop_all(); spdlog::create(tested_logger_name); @@ -59,7 +54,8 @@ TEST_CASE("drop" "[registry]") 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); @@ -69,8 +65,8 @@ TEST_CASE("drop_all" "[registry]") REQUIRE_FALSE(spdlog::get(tested_logger_name)); } - -TEST_CASE("drop non existing" "[registry]") +TEST_CASE("drop non existing" + "[registry]") { spdlog::drop_all(); spdlog::create(tested_logger_name); @@ -79,6 +75,3 @@ TEST_CASE("drop non existing" "[registry]") REQUIRE(spdlog::get(tested_logger_name)); spdlog::drop_all(); } - - - diff --git a/tests/test_macros.cpp b/tests/test_macros.cpp index 8ad7bd41..e3e66c4a 100644 --- a/tests/test_macros.cpp +++ b/tests/test_macros.cpp @@ -1,6 +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" @@ -14,7 +14,7 @@ TEST_CASE("debug and trace w/o format string", "[macros]]") logger->set_level(spdlog::level::trace); SPDLOG_TRACE(logger, "Test message 1"); - //SPDLOG_DEBUG(logger, "Test message 2"); + // SPDLOG_DEBUG(logger, "Test message 2"); SPDLOG_DEBUG(logger, "Test message 2"); logger->flush(); @@ -22,7 +22,6 @@ TEST_CASE("debug and trace w/o format string", "[macros]]") REQUIRE(count_lines(filename) == 2); } - TEST_CASE("debug and trace with format strings", "[macros]]") { prepare_logdir(); @@ -34,11 +33,11 @@ TEST_CASE("debug and trace with format strings", "[macros]]") #if !defined(SPDLOG_FMT_PRINTF) SPDLOG_TRACE(logger, "Test message {}", 1); - //SPDLOG_DEBUG(logger, "Test message 2"); + // SPDLOG_DEBUG(logger, "Test message 2"); SPDLOG_DEBUG(logger, "Test message {}", 222); #else SPDLOG_TRACE(logger, "Test message %d", 1); - //SPDLOG_DEBUG(logger, "Test message 2"); + // SPDLOG_DEBUG(logger, "Test message 2"); SPDLOG_DEBUG(logger, "Test message %d", 222); #endif @@ -47,4 +46,3 @@ TEST_CASE("debug and trace with format strings", "[macros]]") REQUIRE(ends_with(file_contents(filename), "Test message 222\n")); REQUIRE(count_lines(filename) == 2); } - diff --git a/tests/test_pattern_formatter.cpp b/tests/test_pattern_formatter.cpp index 51b0f35d..5c2be1f2 100644 --- a/tests/test_pattern_formatter.cpp +++ b/tests/test_pattern_formatter.cpp @@ -1,13 +1,14 @@ #include "includes.h" // log to str and return it -static std::string log_to_str(const std::string& msg, const std::shared_ptr& formatter = nullptr) +static std::string log_to_str(const std::string &msg, const std::shared_ptr &formatter = nullptr) { 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); - if (formatter) oss_logger.set_formatter(formatter); + if (formatter) + oss_logger.set_formatter(formatter); oss_logger.info(msg); return oss.str(); } @@ -56,6 +57,7 @@ TEST_CASE("date MM/DD/YY ", "[pattern_formatter]") auto formatter = std::make_shared("%D %v", spdlog::pattern_time_type::local, "\n"); 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"; + 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", formatter) == oss.str()); } diff --git a/tests/utils.cpp b/tests/utils.cpp index e179147b..2c50ce36 100644 --- a/tests/utils.cpp +++ b/tests/utils.cpp @@ -1,6 +1,5 @@ #include "includes.h" - void prepare_logdir() { spdlog::drop_all(); @@ -14,18 +13,15 @@ void prepare_logdir() #endif } - -std::string file_contents(const std::string& filename) +std::string file_contents(const std::string &filename) { std::ifstream ifs(filename); if (!ifs) throw std::runtime_error("Failed open file "); - return std::string((std::istreambuf_iterator(ifs)), - (std::istreambuf_iterator())); - + 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) @@ -33,12 +29,12 @@ std::size_t count_lines(const std::string& filename) std::string line; size_t counter = 0; - while(std::getline(ifs, line)) + while (std::getline(ifs, line)) counter++; return counter; } -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) @@ -47,10 +43,10 @@ std::size_t get_filesize(const std::string& filename) return static_cast(ifs.tellg()); } - // source: https://stackoverflow.com/a/2072890/192001 -bool ends_with(std::string const & value, std::string const & ending) +bool ends_with(std::string const &value, std::string const &ending) { - if (ending.size() > value.size()) return false; + if (ending.size() > value.size()) + return false; return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } diff --git a/tests/utils.h b/tests/utils.h index 819bcee6..e788b507 100644 --- a/tests/utils.h +++ b/tests/utils.h @@ -1,16 +1,16 @@ #pragma once +#include #include -#include -std::size_t count_lines(const std::string& filename); +std::size_t count_lines(const std::string &filename); void prepare_logdir(); -std::string file_contents(const std::string& filename); +std::string file_contents(const std::string &filename); -std::size_t count_lines(const std::string& filename); +std::size_t count_lines(const std::string &filename); -std::size_t get_filesize(const std::string& filename); +std::size_t get_filesize(const std::string &filename); -bool ends_with(std::string const & value, std::string const & ending); \ No newline at end of file +bool ends_with(std::string const &value, std::string const &ending); \ No newline at end of file From ad221b0990893b951d3eb27732fc93ffbd153416 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 9 Mar 2018 15:27:53 +0200 Subject: [PATCH 12/62] Changed function name to level::from_str --- include/spdlog/common.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index b4e10170..4ab5e792 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -103,7 +103,7 @@ inline const char *to_short_str(spdlog::level::level_enum l) { return short_level_names[l]; } -inline spdlog::level::level_enum to_level_enum(const std::string &name) +inline spdlog::level::level_enum from_str(const std::string &name) { static std::unordered_map name_to_level = // map string->level {{level_names[0], level::trace}, // trace From cbe98c0fd236078eedc51f72d93a6fee4d2e2148 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 9 Mar 2018 15:30:48 +0200 Subject: [PATCH 13/62] clang format --- include/spdlog/fmt/bundled/format.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/include/spdlog/fmt/bundled/format.h b/include/spdlog/fmt/bundled/format.h index bc84c7b5..1396d6b3 100644 --- a/include/spdlog/fmt/bundled/format.h +++ b/include/spdlog/fmt/bundled/format.h @@ -2898,8 +2898,9 @@ inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) FMT_WRAP1(func, arg_type, 1) \ FMT_WRAP1(func, arg_type, 2) \ FMT_WRAP1(func, arg_type, 3) \ - FMT_WRAP1(func, arg_type, 4) FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) FMT_WRAP1(func, arg_type, 7) \ - FMT_WRAP1(func, arg_type, 8) FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) + FMT_WRAP1(func, arg_type, 4) \ + FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \ + FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) #define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ template ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ From 1946818292285923002b8aa07e33ed3d39de668a Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Fri, 9 Mar 2018 23:11:48 +0200 Subject: [PATCH 14/62] Update .clang-format --- .clang-format | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.clang-format b/.clang-format index ba46f843..d6154a92 100644 --- a/.clang-format +++ b/.clang-format @@ -17,7 +17,7 @@ AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: false +AlwaysBreakTemplateDeclarations: true BinPackArguments: true BinPackParameters: true BraceWrapping: From 650daf75428c72b08f6039f8ecf942e8490c5fbf Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Fri, 9 Mar 2018 23:26:28 +0200 Subject: [PATCH 15/62] Update common.h Updated spdlog version macro to 0.16.4-rc --- include/spdlog/common.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 4ab5e792..dc5f3795 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -5,7 +5,7 @@ #pragma once -#define SPDLOG_VERSION "0.16.3" +#define SPDLOG_VERSION "0.16.4-rc" #include "tweakme.h" From 8ee7b772a9b33d87be3f6b09faa91ffa85e5cc03 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Mar 2018 14:15:35 +0200 Subject: [PATCH 16/62] Added -O3 flag to CMakeLists.txt --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b4fe429d..873979dc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,7 +16,7 @@ set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") - set(CMAKE_CXX_FLAGS "-Wall ${CMAKE_CXX_FLAGS}") + set(CMAKE_CXX_FLAGS "-Wall -O3 ${CMAKE_CXX_FLAGS}") endif() #--------------------------------------------------------------------------------------- From 1108515738aa28ca619a32e0fc17f44dc011cbb9 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Mar 2018 17:04:35 +0200 Subject: [PATCH 17/62] format.sh small fix --- format.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/format.sh b/format.sh index e23097b9..6c61c628 100755 --- a/format.sh +++ b/format.sh @@ -1,5 +1,5 @@ #!/bin/bash find . -name "*\.h" -o -name "*\.cpp"|xargs dos2unix -find . -name "*\.h" -o -name "*\.cpp"|xargs clang-format-5.0 -i +find . -name "*\.h" -o -name "*\.cpp"|xargs clang-format -i From f4ce52d206ff94b8e6336e5b86b33b0902d44309 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Mar 2018 17:13:22 +0200 Subject: [PATCH 18/62] Changed clang formatting for templates --- .clang-format | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.clang-format b/.clang-format index d6154a92..24e999da 100644 --- a/.clang-format +++ b/.clang-format @@ -17,7 +17,7 @@ AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: true +AlwaysBreakTemplateDeclarations: false BinPackArguments: true BinPackParameters: true BraceWrapping: @@ -91,7 +91,7 @@ ReflowComments: true SortIncludes: true SortUsingDeclarations: true SpaceAfterCStyleCast: false -SpaceAfterTemplateKeyword: true +SpaceAfterTemplateKeyword: false SpaceBeforeAssignmentOperators: true SpaceBeforeParens: ControlStatements SpaceInEmptyParentheses: false From 5afb5dc782dfa115811533e69faa8202f8b68c46 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Mar 2018 17:13:50 +0200 Subject: [PATCH 19/62] Changed clang formatting for templates --- bench/g2log-async.cpp | 2 +- bench/latency/utils.h | 4 +- bench/utils.h | 4 +- example/example.cpp | 8 +- example/jni/example.cpp | 2 +- example/utils.h | 4 +- include/spdlog/async_logger.h | 2 +- include/spdlog/details/async_logger_impl.h | 2 +- include/spdlog/details/logger_impl.h | 48 +-- include/spdlog/details/mpmc_bounded_q.h | 2 +- include/spdlog/details/registry.h | 6 +- include/spdlog/details/spdlog_impl.h | 6 +- include/spdlog/fmt/bundled/format.h | 347 ++++++++++----------- include/spdlog/fmt/bundled/ostream.h | 8 +- include/spdlog/fmt/bundled/printf.h | 42 +-- include/spdlog/fmt/bundled/time.h | 2 +- include/spdlog/logger.h | 48 +-- include/spdlog/sinks/ansicolor_sink.h | 6 +- include/spdlog/sinks/base_sink.h | 2 +- include/spdlog/sinks/dist_sink.h | 2 +- include/spdlog/sinks/file_sinks.h | 6 +- include/spdlog/sinks/msvc_sink.h | 2 +- include/spdlog/sinks/null_sink.h | 2 +- include/spdlog/sinks/ostream_sink.h | 2 +- include/spdlog/sinks/stdout_sinks.h | 4 +- include/spdlog/sinks/wincolor_sink.h | 6 +- include/spdlog/sinks/windebug_sink.h | 2 +- include/spdlog/spdlog.h | 6 +- tests/test_misc.cpp | 2 +- 29 files changed, 291 insertions(+), 288 deletions(-) diff --git a/bench/g2log-async.cpp b/bench/g2log-async.cpp index 97cac5dc..1a2f2c76 100644 --- a/bench/g2log-async.cpp +++ b/bench/g2log-async.cpp @@ -13,7 +13,7 @@ #include "g2logworker.h" using namespace std; -template std::string format(const T &value); +template std::string format(const T &value); int main(int argc, char *argv[]) { diff --git a/bench/latency/utils.h b/bench/latency/utils.h index 6d6ee85d..079c5cb8 100644 --- a/bench/latency/utils.h +++ b/bench/latency/utils.h @@ -11,7 +11,7 @@ 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; @@ -20,7 +20,7 @@ template 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; diff --git a/bench/utils.h b/bench/utils.h index 6d6ee85d..079c5cb8 100644 --- a/bench/utils.h +++ b/bench/utils.h @@ -11,7 +11,7 @@ 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; @@ -20,7 +20,7 @@ template 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; diff --git a/example/example.cpp b/example/example.cpp index 937c69f9..f61ea732 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -24,6 +24,12 @@ void err_handler_example(); namespace spd = spdlog; int main(int, char *[]) { + fmt::MemoryWriter w; + w.write("HELLO", 10); + std::string s(w.data(), w.size()); + std::cout << s << std::endl; + return 0; + try { // Console logger with color @@ -133,7 +139,7 @@ void android_example() struct my_type { int i; - template friend OStream &operator<<(OStream &os, const my_type &c) + template friend OStream &operator<<(OStream &os, const my_type &c) { return os << "[my_type i=" << c.i << "]"; } diff --git a/example/jni/example.cpp b/example/jni/example.cpp index 937c69f9..385ed53f 100644 --- a/example/jni/example.cpp +++ b/example/jni/example.cpp @@ -133,7 +133,7 @@ void android_example() struct my_type { int i; - template friend OStream &operator<<(OStream &os, const my_type &c) + template friend OStream &operator<<(OStream &os, const my_type &c) { return os << "[my_type i=" << c.i << "]"; } diff --git a/example/utils.h b/example/utils.h index 6d6ee85d..079c5cb8 100644 --- a/example/utils.h +++ b/example/utils.h @@ -11,7 +11,7 @@ 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; @@ -20,7 +20,7 @@ template 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; diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index 78765972..75641d26 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -32,7 +32,7 @@ class async_log_helper; class async_logger SPDLOG_FINAL : public logger { public: - template + template async_logger(const std::string &logger_name, const It &begin, const It &end, size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, const std::function &worker_warmup_cb = nullptr, diff --git a/include/spdlog/details/async_logger_impl.h b/include/spdlog/details/async_logger_impl.h index ca458740..36e2ec68 100644 --- a/include/spdlog/details/async_logger_impl.h +++ b/include/spdlog/details/async_logger_impl.h @@ -16,7 +16,7 @@ #include #include -template +template inline spdlog::async_logger::async_logger(const std::string &logger_name, const It &begin, const It &end, size_t queue_size, const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) diff --git a/include/spdlog/details/logger_impl.h b/include/spdlog/details/logger_impl.h index 3b64543d..70eec0e1 100644 --- a/include/spdlog/details/logger_impl.h +++ b/include/spdlog/details/logger_impl.h @@ -13,7 +13,7 @@ // create logger with given name, sinks and the default pattern formatter // all other ctors will call this one -template +template inline spdlog::logger::logger(std::string logger_name, const It &begin, const It &end) : _name(std::move(logger_name)) , _sinks(begin, end) @@ -50,7 +50,7 @@ inline void spdlog::logger::set_pattern(const std::string &pattern, pattern_time _set_pattern(pattern, pattern_time); } -template inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) +template inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) { if (!should_log(lvl)) return; @@ -77,7 +77,7 @@ template inline void spdlog::logger::log(level::level_enum lv } } -template inline void spdlog::logger::log(level::level_enum lvl, const char *msg) +template inline void spdlog::logger::log(level::level_enum lvl, const char *msg) { if (!should_log(lvl)) return; @@ -98,7 +98,7 @@ template inline void spdlog::logger::log(level::level_enum lv } } -template inline void spdlog::logger::log(level::level_enum lvl, const T &msg) +template inline void spdlog::logger::log(level::level_enum lvl, const T &msg) { if (!should_log(lvl)) return; @@ -119,62 +119,62 @@ template inline void spdlog::logger::log(level::level_enum lvl, con } } -template inline void spdlog::logger::trace(const char *fmt, const Arg1 &arg1, const Args &... args) +template inline void spdlog::logger::trace(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::trace, fmt, arg1, args...); } -template inline void spdlog::logger::debug(const char *fmt, const Arg1 &arg1, const Args &... args) +template inline void spdlog::logger::debug(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::debug, fmt, arg1, args...); } -template inline void spdlog::logger::info(const char *fmt, const Arg1 &arg1, const Args &... args) +template inline void spdlog::logger::info(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::info, fmt, arg1, args...); } -template inline void spdlog::logger::warn(const char *fmt, const Arg1 &arg1, const Args &... args) +template inline void spdlog::logger::warn(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::warn, fmt, arg1, args...); } -template inline void spdlog::logger::error(const char *fmt, const Arg1 &arg1, const Args &... args) +template inline void spdlog::logger::error(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::err, fmt, arg1, args...); } -template inline void spdlog::logger::critical(const char *fmt, const Arg1 &arg1, const Args &... args) +template inline void spdlog::logger::critical(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::critical, fmt, arg1, args...); } -template inline void spdlog::logger::trace(const T &msg) +template inline void spdlog::logger::trace(const T &msg) { log(level::trace, msg); } -template inline void spdlog::logger::debug(const T &msg) +template inline void spdlog::logger::debug(const T &msg) { log(level::debug, msg); } -template inline void spdlog::logger::info(const T &msg) +template inline void spdlog::logger::info(const T &msg) { log(level::info, msg); } -template inline void spdlog::logger::warn(const T &msg) +template inline void spdlog::logger::warn(const T &msg) { log(level::warn, msg); } -template inline void spdlog::logger::error(const T &msg) +template inline void spdlog::logger::error(const T &msg) { log(level::err, msg); } -template inline void spdlog::logger::critical(const T &msg) +template inline void spdlog::logger::critical(const T &msg) { log(level::critical, msg); } @@ -183,14 +183,14 @@ template inline void spdlog::logger::critical(const T &msg) #include #include -template inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *msg) +template inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *msg) { std::wstring_convert> conv; log(lvl, conv.to_bytes(msg)); } -template inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) +template inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) { fmt::WMemoryWriter wWriter; @@ -198,32 +198,32 @@ template inline void spdlog::logger::log(level::level_enum lv log(lvl, wWriter.c_str()); } -template inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args) +template inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args) { log(level::trace, fmt, args...); } -template inline void spdlog::logger::debug(const wchar_t *fmt, const Args &... args) +template inline void spdlog::logger::debug(const wchar_t *fmt, const Args &... args) { log(level::debug, fmt, args...); } -template inline void spdlog::logger::info(const wchar_t *fmt, const Args &... args) +template inline void spdlog::logger::info(const wchar_t *fmt, const Args &... args) { log(level::info, fmt, args...); } -template inline void spdlog::logger::warn(const wchar_t *fmt, const Args &... args) +template inline void spdlog::logger::warn(const wchar_t *fmt, const Args &... args) { log(level::warn, fmt, args...); } -template inline void spdlog::logger::error(const wchar_t *fmt, const Args &... args) +template inline void spdlog::logger::error(const wchar_t *fmt, const Args &... args) { log(level::err, fmt, args...); } -template inline void spdlog::logger::critical(const wchar_t *fmt, const Args &... args) +template inline void spdlog::logger::critical(const wchar_t *fmt, const Args &... args) { log(level::critical, fmt, args...); } diff --git a/include/spdlog/details/mpmc_bounded_q.h b/include/spdlog/details/mpmc_bounded_q.h index 567f292f..427af65c 100644 --- a/include/spdlog/details/mpmc_bounded_q.h +++ b/include/spdlog/details/mpmc_bounded_q.h @@ -50,7 +50,7 @@ Distributed under the MIT License (http://opensource.org/licenses/MIT) namespace spdlog { namespace details { -template class mpmc_bounded_queue +template class mpmc_bounded_queue { public: using item_type = T; diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 300e4fd7..3f500c1e 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -23,7 +23,7 @@ #include namespace spdlog { namespace details { -template class registry_t +template class registry_t { public: registry_t(const registry_t &) = delete; @@ -44,7 +44,7 @@ public: return found == _loggers.end() ? nullptr : found->second; } - template std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end) + template std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end) { std::lock_guard lock(_mutex); throw_if_exists(logger_name); @@ -69,7 +69,7 @@ public: return new_logger; } - template + template std::shared_ptr create_async(const std::string &logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb, const It &sinks_begin, diff --git a/include/spdlog/details/spdlog_impl.h b/include/spdlog/details/spdlog_impl.h index 114498b1..4c363834 100644 --- a/include/spdlog/details/spdlog_impl.h +++ b/include/spdlog/details/spdlog_impl.h @@ -190,14 +190,14 @@ inline std::shared_ptr spdlog::create(const std::string &logger_ return details::registry::instance().create(logger_name, sinks); } -template +template inline std::shared_ptr spdlog::create(const std::string &logger_name, Args... args) { sink_ptr sink = std::make_shared(args...); return details::registry::instance().create(logger_name, {sink}); } -template +template inline std::shared_ptr spdlog::create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end) { return details::registry::instance().create(logger_name, sinks_begin, sinks_end); @@ -221,7 +221,7 @@ inline std::shared_ptr spdlog::create_async(const std::string &l logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks); } -template +template inline std::shared_ptr spdlog::create_async(const std::string &logger_name, const It &sinks_begin, const It &sinks_end, size_t queue_size, const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) diff --git a/include/spdlog/fmt/bundled/format.h b/include/spdlog/fmt/bundled/format.h index 1396d6b3..529ffb36 100644 --- a/include/spdlog/fmt/bundled/format.h +++ b/include/spdlog/fmt/bundled/format.h @@ -345,8 +345,7 @@ typedef __int64 intmax_t; #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(_MANAGED) #include // _BitScanReverse, _BitScanReverse64 -namespace fmt { -namespace internal { +namespace fmt { namespace internal { // avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning #ifndef __clang__ #pragma intrinsic(_BitScanReverse) @@ -392,8 +391,7 @@ inline uint32_t clzll(uint64_t x) return 63 - r; } #define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) -} -} // namespace fmt +}} // namespace fmt::internal #endif namespace fmt { namespace internal { @@ -436,7 +434,7 @@ inline DummyInt _isnan(...) // A helper function to suppress bogus "conditional expression is constant" // warnings. -template inline T const_check(T value) +template inline T const_check(T value) { return value; } @@ -447,11 +445,11 @@ namespace std { // is used to resolve ambiguity between isinf and std::isinf in glibc: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891 // and the same for isnan and signbit. -template <> class numeric_limits : public std::numeric_limits +template<> class numeric_limits : public std::numeric_limits { public: // Portable version of isinf. - template static bool isinfinity(T x) + template static bool isinfinity(T x) { using namespace fmt::internal; // The resolution "priority" is: @@ -464,7 +462,7 @@ public: } // Portable version of isnan. - template static bool isnotanumber(T x) + template static bool isnotanumber(T x) { using namespace fmt::internal; if (const_check(sizeof(isnan(x)) == sizeof(bool) || sizeof(isnan(x)) == sizeof(int))) @@ -505,18 +503,18 @@ FMT_GCC_EXTENSION typedef unsigned long long ULongLong; using std::move; #endif -template class BasicWriter; +template class BasicWriter; typedef BasicWriter Writer; typedef BasicWriter WWriter; -template class ArgFormatter; +template class ArgFormatter; struct FormatSpec; -template class BasicPrintfArgFormatter; +template class BasicPrintfArgFormatter; -template > class BasicFormatter; +template> class BasicFormatter; /** \rst @@ -543,7 +541,7 @@ template format(std::string("{}"), 42); \endrst */ -template class BasicStringRef +template class BasicStringRef { private: const Char *data_; @@ -574,7 +572,7 @@ public: Constructs a string reference from a ``std::basic_string`` object. \endrst */ - template + template BasicStringRef(const std::basic_string, Allocator> &s) : data_(s.c_str()) , size_(s.size()) @@ -690,7 +688,7 @@ typedef BasicStringRef WStringRef; format(std::string("{}"), 42); \endrst */ -template class BasicCStringRef +template class BasicCStringRef { private: const Char *data_; @@ -707,7 +705,7 @@ public: Constructs a string reference from a ``std::basic_string`` object. \endrst */ - template + template BasicCStringRef(const std::basic_string, Allocator> &s) : data_(s.c_str()) { @@ -741,13 +739,13 @@ public: namespace internal { // MakeUnsigned::Type gives an unsigned type corresponding to integer type T. -template struct MakeUnsigned +template struct MakeUnsigned { typedef T Type; }; #define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \ - template <> struct MakeUnsigned \ + template<> struct MakeUnsigned \ { \ typedef U Type; \ } @@ -760,7 +758,7 @@ FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long); FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong); // Casts nonnegative integer to unsigned. -template inline typename MakeUnsigned::Type to_unsigned(Int value) +template inline typename MakeUnsigned::Type to_unsigned(Int value) { FMT_ASSERT(value >= 0, "negative value"); return static_cast::Type>(value); @@ -775,12 +773,12 @@ enum #if FMT_SECURE_SCL // Use checked iterator to avoid warnings on MSVC. -template inline stdext::checked_array_iterator make_ptr(T *ptr, std::size_t size) +template inline stdext::checked_array_iterator make_ptr(T *ptr, std::size_t size) { return stdext::checked_array_iterator(ptr, size); } #else -template inline T *make_ptr(T *ptr, std::size_t) +template inline T *make_ptr(T *ptr, std::size_t) { return ptr; } @@ -792,7 +790,7 @@ template inline T *make_ptr(T *ptr, std::size_t) A buffer supporting a subset of ``std::vector``'s operations. \endrst */ -template class Buffer +template class Buffer { private: FMT_DISALLOW_COPY_AND_ASSIGN(Buffer); @@ -866,7 +864,7 @@ public: } /** Appends data to the end of the buffer. */ - template void append(const U *begin, const U *end); + template void append(const U *begin, const U *end); T &operator[](std::size_t index) { @@ -878,7 +876,7 @@ public: } }; -template template void Buffer::append(const U *begin, const U *end) +template template void Buffer::append(const U *begin, const U *end) { FMT_ASSERT(end >= begin, "negative value"); std::size_t new_size = size_ + static_cast(end - begin); @@ -892,7 +890,7 @@ namespace internal { // A memory buffer for trivially copyable/constructible types with the first // SIZE elements stored in the object itself. -template > class MemoryBuffer : private Allocator, public Buffer +template> class MemoryBuffer : private Allocator, public Buffer { private: T data_[SIZE]; @@ -963,7 +961,7 @@ public: } }; -template void MemoryBuffer::grow(std::size_t size) +template void MemoryBuffer::grow(std::size_t size) { std::size_t new_capacity = this->capacity_ + this->capacity_ / 2; if (size > new_capacity) @@ -987,7 +985,7 @@ template void MemoryBuffer class FixedBuffer : public fmt::Buffer +template class FixedBuffer : public fmt::Buffer { public: FixedBuffer(Char *array, std::size_t size) @@ -999,7 +997,7 @@ protected: FMT_API void grow(std::size_t size) FMT_OVERRIDE; }; -template class BasicCharTraits +template class BasicCharTraits { public: #if FMT_SECURE_SCL @@ -1013,9 +1011,9 @@ public: } }; -template class CharTraits; +template class CharTraits; -template <> class CharTraits : public BasicCharTraits +template<> class CharTraits : public BasicCharTraits { private: // Conversion from wchar_t to char is not allowed. @@ -1028,7 +1026,7 @@ public: } // Formats a floating-point number. - template + template FMT_API static int format_float(char *buffer, std::size_t size, const char *format, unsigned width, int precision, T value); }; @@ -1039,7 +1037,7 @@ extern template int CharTraits::format_float( char *buffer, std::size_t size, const char *format, unsigned width, int precision, long double value); #endif -template <> class CharTraits : public BasicCharTraits +template<> class CharTraits : public BasicCharTraits { public: static wchar_t convert(char value) @@ -1051,7 +1049,7 @@ public: return value; } - template + template FMT_API static int format_float(wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, T value); }; @@ -1063,17 +1061,17 @@ extern template int CharTraits::format_float( #endif // Checks if a number is negative - used to avoid warnings. -template struct SignChecker +template struct SignChecker { - template static bool is_negative(T value) + template static bool is_negative(T value) { return value < 0; } }; -template <> struct SignChecker +template<> struct SignChecker { - template static bool is_negative(T) + template static bool is_negative(T) { return false; } @@ -1081,23 +1079,23 @@ template <> struct SignChecker // Returns true if value is negative, false otherwise. // Same as (value < 0) but doesn't produce warnings if T is an unsigned type. -template inline bool is_negative(T value) +template inline bool is_negative(T value) { return SignChecker::is_signed>::is_negative(value); } // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise. -template struct TypeSelector +template struct TypeSelector { typedef uint32_t Type; }; -template <> struct TypeSelector +template<> struct TypeSelector { typedef uint64_t Type; }; -template struct IntTraits +template struct IntTraits { // Smallest of uint32_t and uint64_t that is large enough to represent // all values of T. @@ -1108,7 +1106,7 @@ FMT_API FMT_NORETURN void report_unknown_type(char code, const char *type); // Static data is placed in this class template to allow header-only // configuration. -template struct FMT_API BasicData +template struct FMT_API BasicData { static const uint32_t POWERS_OF_10_32[]; static const uint64_t POWERS_OF_10_64[]; @@ -1167,7 +1165,7 @@ inline unsigned count_digits(uint32_t n) // A functor that doesn't add a thousands separator. struct NoThousandsSep { - template void operator()(Char *) {} + template void operator()(Char *) {} }; // A functor that adds a thousands separator. @@ -1186,7 +1184,7 @@ public: { } - template void operator()(Char *&buffer) + template void operator()(Char *&buffer) { if (++digit_index_ % 3 != 0) return; @@ -1198,7 +1196,7 @@ public: // Formats a decimal unsigned integer value writing into buffer. // thousands_sep is a functor that is called after writing each char to // add a thousands separator if necessary. -template +template inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, ThousandsSep thousands_sep) { buffer += num_digits; @@ -1225,7 +1223,7 @@ inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, Thousa *--buffer = Data::DIGITS[index]; } -template inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) +template inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) { format_decimal(buffer, value, num_digits, NoThousandsSep()); return; @@ -1306,7 +1304,7 @@ FMT_API void format_windows_error(fmt::Writer &out, int error_code, fmt::StringR // A formatting argument value. struct Value { - template struct StringValue + template struct StringValue { const Char *value; std::size_t size; @@ -1367,22 +1365,22 @@ struct Arg : Value Type type; }; -template struct NamedArg; -template struct NamedArgWithType; +template struct NamedArg; +template struct NamedArgWithType; -template struct Null +template struct Null { }; // A helper class template to enable or disable overloads taking wide // characters and strings in MakeValue. -template struct WCharHelper +template struct WCharHelper { typedef Null Supported; typedef T Unsupported; }; -template struct WCharHelper +template struct WCharHelper { typedef T Supported; typedef Null Unsupported; @@ -1391,13 +1389,13 @@ template struct WCharHelper typedef char Yes[1]; typedef char No[2]; -template T &get(); +template T &get(); // These are non-members to workaround an overload resolution bug in bcc32. Yes &convert(fmt::ULongLong); No &convert(...); -template struct ConvertToIntImpl +template struct ConvertToIntImpl { enum { @@ -1405,7 +1403,7 @@ template struct ConvertToIntImpl }; }; -template struct ConvertToIntImpl2 +template struct ConvertToIntImpl2 { enum { @@ -1413,7 +1411,7 @@ template struct ConvertToIntImpl2 }; }; -template struct ConvertToIntImpl2 +template struct ConvertToIntImpl2 { enum { @@ -1422,7 +1420,7 @@ template struct ConvertToIntImpl2 }; }; -template struct ConvertToInt +template struct ConvertToInt { enum { @@ -1435,7 +1433,7 @@ template struct ConvertToInt }; #define FMT_DISABLE_CONVERSION_TO_INT(Type) \ - template <> struct ConvertToInt \ + template<> struct ConvertToInt \ { \ enum \ { \ @@ -1448,27 +1446,27 @@ FMT_DISABLE_CONVERSION_TO_INT(float); FMT_DISABLE_CONVERSION_TO_INT(double); FMT_DISABLE_CONVERSION_TO_INT(long double); -template struct EnableIf +template struct EnableIf { }; -template struct EnableIf +template struct EnableIf { typedef T type; }; -template struct Conditional +template struct Conditional { typedef T type; }; -template struct Conditional +template struct Conditional { typedef F type; }; // For bcc32 which doesn't understand ! in template arguments. -template struct Not +template struct Not { enum { @@ -1476,7 +1474,7 @@ template struct Not }; }; -template <> struct Not +template<> struct Not { enum { @@ -1484,7 +1482,7 @@ template <> struct Not }; }; -template struct FalseType +template struct FalseType { enum { @@ -1492,7 +1490,7 @@ template struct FalseType }; }; -template struct LConvCheck +template struct LConvCheck { LConvCheck(int) {} }; @@ -1500,7 +1498,7 @@ template struct LConvCheck // Returns the thousands separator for the current locale. // We check if ``lconv`` contains ``thousands_sep`` because on Android // ``lconv`` is stubbed as an empty struct. -template inline StringRef thousands_sep(LConv *lc, LConvCheck = 0) +template inline StringRef thousands_sep(LConv *lc, LConvCheck = 0) { return lc->thousands_sep; } @@ -1529,7 +1527,7 @@ inline fmt::StringRef thousands_sep(...) #define FMT_STATIC_ASSERT(cond, message) typedef int FMT_CONCAT_(Assert, __LINE__)[(cond) ? 1 : -1] FMT_UNUSED #endif -template void format_arg(Formatter &, ...) +template void format_arg(Formatter &, ...) { FMT_STATIC_ASSERT(FalseType::value, "Cannot format argument. To enable the use of ostream " "operator<< include fmt/ostream.h. Otherwise provide " @@ -1537,7 +1535,7 @@ template void format_arg(Formatter &, ...) } // Makes an Arg object from any type. -template class MakeValue : public Arg +template class MakeValue : public Arg { public: typedef typename Formatter::Char Char; @@ -1548,8 +1546,8 @@ private: // "void *" or "const void *". In particular, this forbids formatting // of "[const] volatile char *" which is printed as bool by iostreams. // Do not implement! - template MakeValue(const T *value); - template MakeValue(T *value); + template MakeValue(const T *value); + template MakeValue(T *value); // The following methods are private to disallow formatting of wide // characters and strings into narrow strings as in @@ -1579,7 +1577,7 @@ private: } // Formats an argument of a custom type, such as a user-defined class. - template static void format_custom_arg(void *formatter, const void *arg, void *format_str_ptr) + template static void format_custom_arg(void *formatter, const void *arg, void *format_str_ptr) { format_arg(*static_cast(formatter), *static_cast(format_str_ptr), *static_cast(arg)); } @@ -1641,13 +1639,12 @@ public: FMT_MAKE_VALUE(char, int_value, CHAR) #if __cplusplus >= 201103L - template ::value && ConvertToInt::value>::type> MakeValue(T value) + template::value && ConvertToInt::value>::type> MakeValue(T value) { int_value = value; } - template ::value && ConvertToInt::value>::type> - static uint64_t type(T) + template::value && ConvertToInt::value>::type> static uint64_t type(T) { return Arg::INT; } @@ -1708,39 +1705,39 @@ public: FMT_MAKE_VALUE(void *, pointer, POINTER) FMT_MAKE_VALUE(const void *, pointer, POINTER) - template MakeValue(const T &value, typename EnableIf::value>::value, int>::type = 0) + template MakeValue(const T &value, typename EnableIf::value>::value, int>::type = 0) { custom.value = &value; custom.format = &format_custom_arg; } - template static typename EnableIf::value>::value, uint64_t>::type type(const T &) + template static typename EnableIf::value>::value, uint64_t>::type type(const T &) { return Arg::CUSTOM; } // Additional template param `Char_` is needed here because make_type always // uses char. - template MakeValue(const NamedArg &value) + template MakeValue(const NamedArg &value) { pointer = &value; } - template MakeValue(const NamedArgWithType &value) + template MakeValue(const NamedArgWithType &value) { pointer = &value; } - template static uint64_t type(const NamedArg &) + template static uint64_t type(const NamedArg &) { return Arg::NAMED_ARG; } - template static uint64_t type(const NamedArgWithType &) + template static uint64_t type(const NamedArgWithType &) { return Arg::NAMED_ARG; } }; -template class MakeArg : public Arg +template class MakeArg : public Arg { public: MakeArg() @@ -1748,7 +1745,7 @@ public: type = Arg::NONE; } - template + template MakeArg(const T &value) : Arg(MakeValue(value)) { @@ -1756,11 +1753,11 @@ public: } }; -template struct NamedArg : Arg +template struct NamedArg : Arg { BasicStringRef name; - template + template NamedArg(BasicStringRef argname, const T &value) : Arg(MakeArg>(value)) , name(argname) @@ -1768,7 +1765,7 @@ template struct NamedArg : Arg } }; -template struct NamedArgWithType : NamedArg +template struct NamedArgWithType : NamedArg { NamedArgWithType(BasicStringRef argname, const T &value) : NamedArg(argname, value) @@ -1790,7 +1787,7 @@ protected: FMT_API ~RuntimeError() FMT_DTOR_NOEXCEPT FMT_OVERRIDE; }; -template class ArgMap; +template class ArgMap; } // namespace internal /** An argument list. */ @@ -1816,7 +1813,7 @@ private: return type(types_, index); } - template friend class internal::ArgMap; + template friend class internal::ArgMap; public: // Maximum number of arguments with packed types. @@ -1910,7 +1907,7 @@ public: }; \endrst */ -template class ArgVisitor +template class ArgVisitor { private: typedef internal::Arg Arg; @@ -1961,7 +1958,7 @@ public: } /** Visits an argument of any integral type. **/ - template Result visit_any_int(T) + template Result visit_any_int(T) { return FMT_DISPATCH(visit_unhandled_arg()); } @@ -1979,7 +1976,7 @@ public: } /** Visits a ``double`` or ``long double`` argument. **/ - template Result visit_any_double(T) + template Result visit_any_double(T) { return FMT_DISPATCH(visit_unhandled_arg()); } @@ -2086,7 +2083,7 @@ struct EmptySpec }; // A type specifier. -template struct TypeSpec : EmptySpec +template struct TypeSpec : EmptySpec { Alignment align() const { @@ -2165,7 +2162,7 @@ struct AlignSpec : WidthSpec }; // An alignment and type specifier. -template struct AlignTypeSpec : AlignSpec +template struct AlignTypeSpec : AlignSpec { AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) @@ -2220,7 +2217,7 @@ struct FormatSpec : AlignSpec }; // An integer format specifier. -template , typename Char = char> class IntFormatSpec : public SpecT +template, typename Char = char> class IntFormatSpec : public SpecT { private: T value_; @@ -2239,13 +2236,13 @@ public: }; // A string format specifier. -template class StrFormatSpec : public AlignSpec +template class StrFormatSpec : public AlignSpec { private: const Char *str_; public: - template + template StrFormatSpec(const Char *str, unsigned width, FillChar fill) : AlignSpec(width, fill) , str_(str) @@ -2295,7 +2292,7 @@ IntFormatSpec> hexu(int value); \endrst */ -template IntFormatSpec, Char> pad(int value, unsigned width, Char fill = ' '); +template IntFormatSpec, Char> pad(int value, unsigned width, Char fill = ' '); #define FMT_DEFINE_INT_FORMATTERS(TYPE) \ inline IntFormatSpec> bin(TYPE value) \ @@ -2318,7 +2315,7 @@ template IntFormatSpec>(value, TypeSpec<'X'>()); \ } \ \ - template \ + template \ inline IntFormatSpec> pad(IntFormatSpec> f, unsigned width) \ { \ return IntFormatSpec>(f.value(), AlignTypeSpec(width, ' ')); \ @@ -2328,7 +2325,7 @@ template IntFormatSpec \ + template \ inline IntFormatSpec, Char> pad( \ IntFormatSpec, Char> f, unsigned width, Char fill) \ { \ @@ -2340,7 +2337,7 @@ template IntFormatSpec>(value, AlignTypeSpec<0>(width, ' ')); \ } \ \ - template inline IntFormatSpec, Char> pad(TYPE value, unsigned width, Char fill) \ + template inline IntFormatSpec, Char> pad(TYPE value, unsigned width, Char fill) \ { \ return IntFormatSpec, Char>(value, AlignTypeSpec<0>(width, fill)); \ } @@ -2364,7 +2361,7 @@ FMT_DEFINE_INT_FORMATTERS(ULongLong) \endrst */ -template inline StrFormatSpec pad(const Char *str, unsigned width, Char fill = ' ') +template inline StrFormatSpec pad(const Char *str, unsigned width, Char fill = ' ') { return StrFormatSpec(str, width, fill); } @@ -2376,7 +2373,7 @@ inline StrFormatSpec pad(const wchar_t *str, unsigned width, char fill namespace internal { -template class ArgMap +template class ArgMap { private: typedef std::vector, internal::Arg>> MapType; @@ -2399,7 +2396,7 @@ public: } }; -template void ArgMap::init(const ArgList &args) +template void ArgMap::init(const ArgList &args) { if (!map_.empty()) return; @@ -2452,7 +2449,7 @@ template void ArgMap::init(const ArgList &args) } } -template class ArgFormatterBase : public ArgVisitor +template class ArgFormatterBase : public ArgVisitor { private: BasicWriter &writer_; @@ -2502,12 +2499,12 @@ public: { } - template void visit_any_int(T value) + template void visit_any_int(T value) { writer_.write_int(value, spec_); } - template void visit_any_double(T value) + template void visit_any_double(T value) { writer_.write_double(value, spec_); } @@ -2636,7 +2633,7 @@ protected: return true; } - template void write(BasicWriter &w, const Char *start, const Char *end) + template void write(BasicWriter &w, const Char *start, const Char *end) { if (start != end) w << BasicStringRef(start, internal::to_unsigned(end - start)); @@ -2661,7 +2658,7 @@ protected: will be called. \endrst */ -template +template class BasicArgFormatter : public internal::ArgFormatterBase { private: @@ -2692,7 +2689,7 @@ public: }; /** The default argument formatter. */ -template class ArgFormatter : public BasicArgFormatter, Char, FormatSpec> +template class ArgFormatter : public BasicArgFormatter, Char, FormatSpec> { public: /** Constructs an argument formatter object. */ @@ -2703,7 +2700,7 @@ public: }; /** This template formats data and writes the output to a writer. */ -template class BasicFormatter : private internal::FormatterBase +template class BasicFormatter : private internal::FormatterBase { public: /** The character type for the output. */ @@ -2779,19 +2776,19 @@ inline uint64_t make_type() return 0; } -template inline uint64_t make_type(const T &arg) +template inline uint64_t make_type(const T &arg) { return MakeValue>::type(arg); } -template struct ArgArray; +template struct ArgArray; -template struct ArgArray +template struct ArgArray { // '+' is used to silence GCC -Wduplicated-branches warning. typedef Value Type[N > 0 ? N : +1]; - template static Value make(const T &value) + template static Value make(const T &value) { #ifdef __clang__ Value result = MakeValue(value); @@ -2805,18 +2802,18 @@ template struct ArgArray } }; -template struct ArgArray +template struct ArgArray { typedef Arg Type[N + 1]; // +1 for the list end Arg::NONE - template static Arg make(const T &value) + template static Arg make(const T &value) { return MakeArg(value); } }; #if FMT_USE_VARIADIC_TEMPLATES -template inline uint64_t make_type(const Arg &first, const Args &... tail) +template inline uint64_t make_type(const Arg &first, const Args &... tail) { return make_type(first) | (make_type(tail...) << 4); } @@ -2832,7 +2829,7 @@ struct ArgType { } - template + template ArgType(const T &arg) : type(make_type(arg)) { @@ -2859,7 +2856,7 @@ inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) #if FMT_USE_VARIADIC_TEMPLATES // Defines a variadic function returning void. #define FMT_VARIADIC_VOID(func, arg_type) \ - template void func(arg_type arg0, const Args &... args) \ + template void func(arg_type arg0, const Args &... args) \ { \ typedef fmt::internal::ArgArray ArgArray; \ typename ArgArray::Type array{ArgArray::template make>(args)...}; \ @@ -2868,7 +2865,7 @@ inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) // Defines a variadic constructor. #define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ - template ctor(arg0_type arg0, arg1_type arg1, const Args &... args) \ + template ctor(arg0_type arg0, arg1_type arg1, const Args &... args) \ { \ typedef fmt::internal::ArgArray ArgArray; \ typename ArgArray::Type array{ArgArray::template make>(args)...}; \ @@ -2883,7 +2880,7 @@ inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) // Defines a wrapper for a function taking one argument of type arg_type // and n additional arguments of arbitrary types. #define FMT_WRAP1(func, arg_type, n) \ - template inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ + template inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ { \ const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ func(arg1, fmt::ArgList(fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ @@ -2899,11 +2896,12 @@ inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) FMT_WRAP1(func, arg_type, 2) \ FMT_WRAP1(func, arg_type, 3) \ FMT_WRAP1(func, arg_type, 4) \ - FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \ - FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) + FMT_WRAP1(func, arg_type, 5) \ + FMT_WRAP1(func, arg_type, 6) \ + FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) #define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ - template ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ + template ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ { \ const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ @@ -3022,7 +3020,7 @@ FMT_API void format_system_error(fmt::Writer &out, int error_code, fmt::StringRe \endrst */ -template class BasicWriter +template class BasicWriter { private: // Output buffer. @@ -3059,7 +3057,7 @@ private: } // Writes an unsigned decimal integer. - template Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) + template Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) { unsigned num_digits = internal::count_digits(value); Char *ptr = get(grow_buffer(prefix_size + num_digits)); @@ -3068,7 +3066,7 @@ private: } // Writes a decimal integer. - template void write_decimal(Int value) + template void write_decimal(Int value) { typedef typename internal::IntTraits::MainType MainType; MainType abs_value = static_cast(value); @@ -3092,18 +3090,18 @@ private: return p + size - 1; } - template CharPtr prepare_int_buffer(unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size); + template CharPtr prepare_int_buffer(unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size); // Formats an integer. - template void write_int(T value, Spec spec); + template void write_int(T value, Spec spec); // Formats a floating-point number (double or long double). - template void write_double(T value, const Spec &spec); + template void write_double(T value, const Spec &spec); // Writes a formatted string. - template CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); + template CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); - template void write_str(const internal::Arg::StringValue &str, const Spec &spec); + template void write_str(const internal::Arg::StringValue &str, const Spec &spec); // This following methods are private to disallow writing wide characters // and strings to a char stream. If you want to print a wide string as a @@ -3119,11 +3117,11 @@ private: *format_ptr++ = 'L'; } - template void append_float_length(Char *&, T) {} + template void append_float_length(Char *&, T) {} - template friend class internal::ArgFormatterBase; + template friend class internal::ArgFormatterBase; - template friend class BasicPrintfArgFormatter; + template friend class BasicPrintfArgFormatter; protected: /** @@ -3298,14 +3296,14 @@ public: return *this; } - template BasicWriter &operator<<(IntFormatSpec spec) + template BasicWriter &operator<<(IntFormatSpec spec) { internal::CharTraits::convert(FillChar()); write_int(spec.value(), spec); return *this; } - template BasicWriter &operator<<(const StrFormatSpec &spec) + template BasicWriter &operator<<(const StrFormatSpec &spec) { const StrChar *s = spec.str(); write_str(s, std::char_traits::length(s), spec); @@ -3323,8 +3321,8 @@ public: } }; -template -template +template +template typename BasicWriter::CharPtr BasicWriter::write_str(const StrChar *s, std::size_t size, const AlignSpec &spec) { CharPtr out = CharPtr(); @@ -3354,8 +3352,8 @@ typename BasicWriter::CharPtr BasicWriter::write_str(const StrChar * return out; } -template -template +template +template void BasicWriter::write_str(const internal::Arg::StringValue &s, const Spec &spec) { // Check if StrChar is convertible to Char. @@ -3377,7 +3375,7 @@ void BasicWriter::write_str(const internal::Arg::StringValue &s, write_str(str_value, str_size, spec); } -template +template typename BasicWriter::CharPtr BasicWriter::fill_padding( CharPtr buffer, unsigned total_size, std::size_t content_size, wchar_t fill) { @@ -3391,8 +3389,8 @@ typename BasicWriter::CharPtr BasicWriter::fill_padding( return content; } -template -template +template +template typename BasicWriter::CharPtr BasicWriter::prepare_int_buffer( unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size) { @@ -3465,7 +3463,7 @@ typename BasicWriter::CharPtr BasicWriter::prepare_int_buffer( return p - 1; } -template template void BasicWriter::write_int(T value, Spec spec) +template template void BasicWriter::write_int(T value, Spec spec) { unsigned prefix_size = 0; typedef typename internal::IntTraits::MainType UnsignedType; @@ -3573,7 +3571,7 @@ template template void BasicWriter template void BasicWriter::write_double(T value, const Spec &spec) +template template void BasicWriter::write_double(T value, const Spec &spec) { // Check type. char type = spec.type(); @@ -3791,7 +3789,7 @@ template template void BasicWriter> class BasicMemoryWriter : public BasicWriter +template> class BasicMemoryWriter : public BasicWriter { private: internal::MemoryBuffer buffer_; @@ -3852,7 +3850,7 @@ typedef BasicMemoryWriter WMemoryWriter; +--------------+---------------------------+ \endrst */ -template class BasicArrayWriter : public BasicWriter +template class BasicArrayWriter : public BasicWriter { private: internal::FixedBuffer buffer_; @@ -3876,7 +3874,7 @@ public: size known at compile time. \endrst */ - template + template explicit BasicArrayWriter(Char (&array)[SIZE]) : BasicWriter(buffer_) , buffer_(array, SIZE) @@ -4122,7 +4120,7 @@ public: // Formats a decimal integer value writing into buffer and returns // a pointer to the end of the formatted string. This function doesn't // write a terminating null character. -template inline void format_decimal(char *&buffer, T value) +template inline void format_decimal(char *&buffer, T value) { typedef typename internal::IntTraits::MainType MainType; MainType abs_value = static_cast(value); @@ -4158,20 +4156,20 @@ template inline void format_decimal(char *&buffer, T value) \endrst */ -template inline internal::NamedArgWithType arg(StringRef name, const T &arg) +template inline internal::NamedArgWithType arg(StringRef name, const T &arg) { return internal::NamedArgWithType(name, arg); } -template inline internal::NamedArgWithType arg(WStringRef name, const T &arg) +template inline internal::NamedArgWithType arg(WStringRef name, const T &arg) { return internal::NamedArgWithType(name, arg); } // The following two functions are deleted intentionally to disable // nested named arguments as in ``format("{}", arg("a", arg("b", 42)))``. -template void arg(StringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; -template void arg(WStringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; +template void arg(StringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; +template void arg(WStringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; } // namespace fmt #if FMT_GCC_VERSION @@ -4200,7 +4198,7 @@ template void arg(WStringRef, const internal::NamedArg &) #if FMT_USE_VARIADIC_TEMPLATES #define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ - template ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), const Args &... args) Const \ + template ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), const Args &... args) Const \ { \ typedef fmt::internal::ArgArray ArgArray; \ typename ArgArray::Type array{ArgArray::template make>(args)...}; \ @@ -4210,7 +4208,7 @@ template void arg(WStringRef, const internal::NamedArg &) // Defines a wrapper for a function taking __VA_ARGS__ arguments // and n additional arguments of arbitrary types. #define FMT_WRAP(Const, Char, ReturnType, func, call, n, ...) \ - template \ + template \ inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), FMT_GEN(n, FMT_MAKE_ARG)) Const \ { \ fmt::internal::ArgArray::Type arr; \ @@ -4305,14 +4303,14 @@ FMT_VARIADIC(void, print, std::FILE *, CStringRef) FMT_VARIADIC(void, print_colored, Color, CStringRef) namespace internal { -template inline bool is_name_start(Char c) +template inline bool is_name_start(Char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; } // Parses an unsigned integer advancing s to the end of the parsed input. // This function assumes that the first character of s is a digit. -template unsigned parse_nonnegative_int(const Char *&s) +template unsigned parse_nonnegative_int(const Char *&s) { assert('0' <= *s && *s <= '9'); unsigned value = 0; @@ -4345,7 +4343,7 @@ inline void require_numeric_argument(const Arg &arg, char spec) } } -template void check_sign(const Char *&s, const Arg &arg) +template void check_sign(const Char *&s, const Arg &arg) { char sign = static_cast(*s); require_numeric_argument(arg, sign); @@ -4357,7 +4355,7 @@ template void check_sign(const Char *&s, const Arg &arg) } } // namespace internal -template +template inline internal::Arg BasicFormatter::get_arg(BasicStringRef arg_name, const char *&error) { if (check_no_auto_index(error)) @@ -4371,7 +4369,7 @@ inline internal::Arg BasicFormatter::get_arg(BasicStringRef arg_ return internal::Arg(); } -template inline internal::Arg BasicFormatter::parse_arg_index(const Char *&s) +template inline internal::Arg BasicFormatter::parse_arg_index(const Char *&s) { const char *error = FMT_NULL; internal::Arg arg = *s < '0' || *s > '9' ? next_arg(error) : get_arg(internal::parse_nonnegative_int(s), error); @@ -4382,7 +4380,7 @@ template inline internal::Arg BasicFormatter inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) +template inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) { assert(internal::is_name_start(*s)); const Char *start = s; @@ -4398,7 +4396,7 @@ template inline internal::Arg BasicFormatter +template const Char *BasicFormatter::format(const Char *&format_str, const internal::Arg &arg) { using internal::Arg; @@ -4592,7 +4590,7 @@ const Char *BasicFormatter::format(const Char *&format_str, return s; } -template void BasicFormatter::format(BasicCStringRef format_str) +template void BasicFormatter::format(BasicCStringRef format_str) { const Char *s = format_str.c_str(); const Char *start = s; @@ -4616,7 +4614,7 @@ template void BasicFormatter::format(Basi write(writer_, start, s); } -template struct ArgJoin +template struct ArgJoin { It first; It last; @@ -4630,30 +4628,29 @@ template struct ArgJoin } }; -template ArgJoin join(It first, It last, const BasicCStringRef &sep) +template ArgJoin join(It first, It last, const BasicCStringRef &sep) { return ArgJoin(first, last, sep); } -template ArgJoin join(It first, It last, const BasicCStringRef &sep) +template ArgJoin join(It first, It last, const BasicCStringRef &sep) { return ArgJoin(first, last, sep); } #if FMT_HAS_GXX_CXX11 -template auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin +template auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin { return join(std::begin(range), std::end(range), sep); } -template -auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin +template auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin { return join(std::begin(range), std::end(range), sep); } #endif -template +template void format_arg(fmt::BasicFormatter &f, const Char *&format_str, const ArgJoin &e) { const Char *end = format_str; @@ -4684,21 +4681,21 @@ void format_arg(fmt::BasicFormatter &f, const Char *&format_ namespace fmt { namespace internal { -template struct UdlFormat +template struct UdlFormat { const Char *str; - template auto operator()(Args &&... args) const -> decltype(format(str, std::forward(args)...)) + template auto operator()(Args &&... args) const -> decltype(format(str, std::forward(args)...)) { return format(str, std::forward(args)...); } }; -template struct UdlArg +template struct UdlArg { const Char *str; - template NamedArgWithType operator=(T &&value) const + template NamedArgWithType operator=(T &&value) const { return {str, std::forward(value)}; } diff --git a/include/spdlog/fmt/bundled/ostream.h b/include/spdlog/fmt/bundled/ostream.h index 1a21f984..98f9f22a 100644 --- a/include/spdlog/fmt/bundled/ostream.h +++ b/include/spdlog/fmt/bundled/ostream.h @@ -17,7 +17,7 @@ namespace fmt { namespace internal { -template class FormatBuf : public std::basic_streambuf +template class FormatBuf : public std::basic_streambuf { private: typedef typename std::basic_streambuf::int_type int_type; @@ -60,12 +60,12 @@ struct DummyStream : std::ostream DummyStream(); // Suppress a bogus warning in MSVC. // Hide all operator<< overloads from std::ostream. - template typename EnableIf::type operator<<(const T &); + template typename EnableIf::type operator<<(const T &); }; No &operator<<(std::ostream &, int); -template struct ConvertToIntImpl +template struct ConvertToIntImpl { // Convert to int only if T doesn't have an overloaded operator<<. enum @@ -79,7 +79,7 @@ FMT_API void write(std::ostream &os, Writer &w); } // namespace internal // Formats a value. -template +template void format_arg(BasicFormatter &f, const Char *&format_str, const T &value) { internal::MemoryBuffer buffer; diff --git a/include/spdlog/fmt/bundled/printf.h b/include/spdlog/fmt/bundled/printf.h index 4f540048..2102cf24 100644 --- a/include/spdlog/fmt/bundled/printf.h +++ b/include/spdlog/fmt/bundled/printf.h @@ -20,9 +20,9 @@ namespace internal { // Checks if a value fits in int - used to avoid warnings about comparing // signed and unsigned integers. -template struct IntChecker +template struct IntChecker { - template static bool fits_in_int(T value) + template static bool fits_in_int(T value) { unsigned max = std::numeric_limits::max(); return value <= max; @@ -33,9 +33,9 @@ template struct IntChecker } }; -template <> struct IntChecker +template<> struct IntChecker { - template static bool fits_in_int(T value) + template static bool fits_in_int(T value) { return value >= std::numeric_limits::min() && value <= std::numeric_limits::max(); } @@ -53,7 +53,7 @@ public: FMT_THROW(FormatError("precision is not integer")); } - template int visit_any_int(T value) + template int visit_any_int(T value) { if (!IntChecker::is_signed>::fits_in_int(value)) FMT_THROW(FormatError("number is too big")); @@ -65,7 +65,7 @@ public: class IsZeroInt : public ArgVisitor { public: - template bool visit_any_int(T value) + template bool visit_any_int(T value) { return value == 0; } @@ -90,12 +90,12 @@ public: return 'p'; } - template char visit_any_int(T) + template char visit_any_int(T) { return 'd'; } - template char visit_any_double(T) + template char visit_any_double(T) { return 'g'; } @@ -106,7 +106,7 @@ public: } }; -template struct is_same +template struct is_same { enum { @@ -114,7 +114,7 @@ template struct is_same }; }; -template struct is_same +template struct is_same { enum { @@ -126,7 +126,7 @@ template struct is_same // if T is an integral type. If T is void, the argument is converted to // corresponding signed or unsigned type depending on the type specifier: // 'd' and 'i' - signed, other - unsigned) -template class ArgConverter : public ArgVisitor, void> +template class ArgConverter : public ArgVisitor, void> { private: internal::Arg &arg_; @@ -153,7 +153,7 @@ public: visit_any_int(value); } - template void visit_any_int(U value) + template void visit_any_int(U value) { bool is_signed = type_ == 'd' || type_ == 'i'; if (type_ == 's') @@ -211,7 +211,7 @@ public: { } - template void visit_any_int(T value) + template void visit_any_int(T value) { arg_.type = internal::Arg::CHAR; arg_.int_value = static_cast(value); @@ -238,7 +238,7 @@ public: FMT_THROW(FormatError("width is not integer")); } - template unsigned visit_any_int(T value) + template unsigned visit_any_int(T value) { typedef typename internal::IntTraits::MainType UnsignedType; UnsignedType width = static_cast(value); @@ -272,7 +272,7 @@ public: superclass will be called. \endrst */ -template class BasicPrintfArgFormatter : public internal::ArgFormatterBase +template class BasicPrintfArgFormatter : public internal::ArgFormatterBase { private: void write_null_pointer() @@ -367,7 +367,7 @@ public: }; /** The default printf argument formatter. */ -template class PrintfArgFormatter : public BasicPrintfArgFormatter, Char, FormatSpec> +template class PrintfArgFormatter : public BasicPrintfArgFormatter, Char, FormatSpec> { public: /** Constructs an argument formatter object. */ @@ -378,7 +378,7 @@ public: }; /** This template formats data and writes the output to a writer. */ -template > class PrintfFormatter : private internal::FormatterBase +template> class PrintfFormatter : private internal::FormatterBase { private: BasicWriter &writer_; @@ -410,7 +410,7 @@ public: void format(BasicCStringRef format_str); }; -template void PrintfFormatter::parse_flags(FormatSpec &spec, const Char *&s) +template void PrintfFormatter::parse_flags(FormatSpec &spec, const Char *&s) { for (;;) { @@ -438,7 +438,7 @@ template void PrintfFormatter::parse_flag } } -template internal::Arg PrintfFormatter::get_arg(const Char *s, unsigned arg_index) +template internal::Arg PrintfFormatter::get_arg(const Char *s, unsigned arg_index) { (void)s; const char *error = FMT_NULL; @@ -448,7 +448,7 @@ template internal::Arg PrintfFormatter::g return arg; } -template unsigned PrintfFormatter::parse_header(const Char *&s, FormatSpec &spec) +template unsigned PrintfFormatter::parse_header(const Char *&s, FormatSpec &spec) { unsigned arg_index = std::numeric_limits::max(); Char c = *s; @@ -489,7 +489,7 @@ template unsigned PrintfFormatter::parse_ return arg_index; } -template void PrintfFormatter::format(BasicCStringRef format_str) +template void PrintfFormatter::format(BasicCStringRef format_str) { const Char *start = format_str.c_str(); const Char *s = start; diff --git a/include/spdlog/fmt/bundled/time.h b/include/spdlog/fmt/bundled/time.h index e06fa5b4..e5f0d772 100644 --- a/include/spdlog/fmt/bundled/time.h +++ b/include/spdlog/fmt/bundled/time.h @@ -20,7 +20,7 @@ #endif namespace fmt { -template void format_arg(BasicFormatter &f, const char *&format_str, const std::tm &tm) +template void format_arg(BasicFormatter &f, const char *&format_str, const std::tm &tm) { if (*format_str == ':') ++format_str; diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 4f3bfa56..8358cee2 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -27,40 +27,40 @@ public: logger(const std::string &name, sink_ptr single_sink); logger(const std::string &name, sinks_init_list sinks); - template logger(std::string name, const It &begin, const It &end); + template logger(std::string name, const It &begin, const It &end); virtual ~logger(); logger(const logger &) = delete; logger &operator=(const logger &) = delete; - template void log(level::level_enum lvl, const char *fmt, const Args &... args); - template void log(level::level_enum lvl, const char *msg); - template void trace(const char *fmt, const Arg1 &, const Args &... args); - template void debug(const char *fmt, const Arg1 &, const Args &... args); - template void info(const char *fmt, const Arg1 &, const Args &... args); - template void warn(const char *fmt, const Arg1 &, const Args &... args); - template void error(const char *fmt, const Arg1 &, const Args &... args); - template void critical(const char *fmt, const Arg1 &, const Args &... args); + template void log(level::level_enum lvl, const char *fmt, const Args &... args); + template void log(level::level_enum lvl, const char *msg); + template void trace(const char *fmt, const Arg1 &, const Args &... args); + template void debug(const char *fmt, const Arg1 &, const Args &... args); + template void info(const char *fmt, const Arg1 &, const Args &... args); + template void warn(const char *fmt, const Arg1 &, const Args &... args); + template void error(const char *fmt, const Arg1 &, const Args &... args); + template void critical(const char *fmt, const Arg1 &, const Args &... args); #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT - template void log(level::level_enum lvl, const wchar_t *msg); - template void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); - template void trace(const wchar_t *fmt, const Args &... args); - template void debug(const wchar_t *fmt, const Args &... args); - template void info(const wchar_t *fmt, const Args &... args); - template void warn(const wchar_t *fmt, const Args &... args); - template void error(const wchar_t *fmt, const Args &... args); - template void critical(const wchar_t *fmt, const Args &... args); + template void log(level::level_enum lvl, const wchar_t *msg); + template void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); + template void trace(const wchar_t *fmt, const Args &... args); + template void debug(const wchar_t *fmt, const Args &... args); + template void info(const wchar_t *fmt, const Args &... args); + template void warn(const wchar_t *fmt, const Args &... args); + template void error(const wchar_t *fmt, const Args &... args); + template void critical(const wchar_t *fmt, const Args &... args); #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT - template void log(level::level_enum lvl, const T &); - template void trace(const T &msg); - template void debug(const T &msg); - template void info(const T &msg); - template void warn(const T &msg); - template void error(const T &msg); - template void critical(const T &msg); + template void log(level::level_enum lvl, const T &); + template void trace(const T &msg); + template void debug(const T &msg); + template void info(const T &msg); + template void warn(const T &msg); + template void error(const T &msg); + template void critical(const T &msg); bool should_log(level::level_enum msg_level) const; void set_level(level::level_enum log_level); diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index 7cb2b3e7..d08eac47 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -19,7 +19,7 @@ namespace spdlog { namespace sinks { * of the message. * If no color terminal detected, omit the escape codes. */ -template class ansicolor_sink : public base_sink +template class ansicolor_sink : public base_sink { public: explicit ansicolor_sink(FILE *file) @@ -106,7 +106,7 @@ protected: std::unordered_map colors_; }; -template class ansicolor_stdout_sink : public ansicolor_sink +template class ansicolor_stdout_sink : public ansicolor_sink { public: ansicolor_stdout_sink() @@ -118,7 +118,7 @@ public: using ansicolor_stdout_sink_mt = ansicolor_stdout_sink; using ansicolor_stdout_sink_st = ansicolor_stdout_sink; -template class ansicolor_stderr_sink : public ansicolor_sink +template class ansicolor_stderr_sink : public ansicolor_sink { public: ansicolor_stderr_sink() diff --git a/include/spdlog/sinks/base_sink.h b/include/spdlog/sinks/base_sink.h index bf67a59c..7c628c18 100644 --- a/include/spdlog/sinks/base_sink.h +++ b/include/spdlog/sinks/base_sink.h @@ -18,7 +18,7 @@ #include namespace spdlog { namespace sinks { -template class base_sink : public sink +template class base_sink : public sink { public: base_sink() = default; diff --git a/include/spdlog/sinks/dist_sink.h b/include/spdlog/sinks/dist_sink.h index b204790b..c2c91412 100644 --- a/include/spdlog/sinks/dist_sink.h +++ b/include/spdlog/sinks/dist_sink.h @@ -18,7 +18,7 @@ // Distribution sink (mux). Stores a vector of sinks which get called when log is called namespace spdlog { namespace sinks { -template class dist_sink : public base_sink +template class dist_sink : public base_sink { public: explicit dist_sink() diff --git a/include/spdlog/sinks/file_sinks.h b/include/spdlog/sinks/file_sinks.h index 48322e83..9b3cc9f5 100644 --- a/include/spdlog/sinks/file_sinks.h +++ b/include/spdlog/sinks/file_sinks.h @@ -22,7 +22,7 @@ namespace spdlog { namespace sinks { /* * Trivial file sink with single file as target */ -template class simple_file_sink SPDLOG_FINAL : public base_sink +template class simple_file_sink SPDLOG_FINAL : public base_sink { public: explicit simple_file_sink(const filename_t &filename, bool truncate = false) @@ -60,7 +60,7 @@ using simple_file_sink_st = simple_file_sink; /* * Rotating file sink based on size */ -template class rotating_file_sink SPDLOG_FINAL : public base_sink +template class rotating_file_sink SPDLOG_FINAL : public base_sink { public: rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files) @@ -185,7 +185,7 @@ struct dateonly_daily_file_name_calculator /* * Rotating file sink based on date. rotates at midnight */ -template class daily_file_sink SPDLOG_FINAL : public base_sink +template class daily_file_sink SPDLOG_FINAL : public base_sink { public: // create daily file sink which rotates on given time diff --git a/include/spdlog/sinks/msvc_sink.h b/include/spdlog/sinks/msvc_sink.h index e58d49ce..a618886b 100644 --- a/include/spdlog/sinks/msvc_sink.h +++ b/include/spdlog/sinks/msvc_sink.h @@ -19,7 +19,7 @@ namespace spdlog { namespace sinks { /* * MSVC sink (logging using OutputDebugStringA) */ -template class msvc_sink : public base_sink +template class msvc_sink : public base_sink { public: explicit msvc_sink() {} diff --git a/include/spdlog/sinks/null_sink.h b/include/spdlog/sinks/null_sink.h index d8eab97c..46e90775 100644 --- a/include/spdlog/sinks/null_sink.h +++ b/include/spdlog/sinks/null_sink.h @@ -12,7 +12,7 @@ namespace spdlog { namespace sinks { -template class null_sink : public base_sink +template class null_sink : public base_sink { protected: void _sink_it(const details::log_msg &) override {} diff --git a/include/spdlog/sinks/ostream_sink.h b/include/spdlog/sinks/ostream_sink.h index bb79de76..5c4ec810 100644 --- a/include/spdlog/sinks/ostream_sink.h +++ b/include/spdlog/sinks/ostream_sink.h @@ -12,7 +12,7 @@ #include namespace spdlog { namespace sinks { -template class ostream_sink : public base_sink +template class ostream_sink : public base_sink { public: explicit ostream_sink(std::ostream &os, bool force_flush = false) diff --git a/include/spdlog/sinks/stdout_sinks.h b/include/spdlog/sinks/stdout_sinks.h index 4494323b..fb3e1bc0 100644 --- a/include/spdlog/sinks/stdout_sinks.h +++ b/include/spdlog/sinks/stdout_sinks.h @@ -14,7 +14,7 @@ namespace spdlog { namespace sinks { -template class stdout_sink SPDLOG_FINAL : public base_sink +template class stdout_sink SPDLOG_FINAL : public base_sink { using MyType = stdout_sink; @@ -43,7 +43,7 @@ protected: using stdout_sink_mt = stdout_sink; using stdout_sink_st = stdout_sink; -template class stderr_sink SPDLOG_FINAL : public base_sink +template class stderr_sink SPDLOG_FINAL : public base_sink { using MyType = stderr_sink; diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index 77ae59e1..3f5fdfe6 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -18,7 +18,7 @@ namespace spdlog { namespace sinks { /* * Windows color console sink. Uses WriteConsoleA to write to the console with colors */ -template class wincolor_sink : public base_sink +template class wincolor_sink : public base_sink { public: const WORD BOLD = FOREGROUND_INTENSITY; @@ -89,7 +89,7 @@ private: // // windows color console to stdout // -template class wincolor_stdout_sink : public wincolor_sink +template class wincolor_stdout_sink : public wincolor_sink { public: wincolor_stdout_sink() @@ -104,7 +104,7 @@ using wincolor_stdout_sink_st = wincolor_stdout_sink; // // windows color console to stderr // -template class wincolor_stderr_sink : public wincolor_sink +template class wincolor_stderr_sink : public wincolor_sink { public: wincolor_stderr_sink() diff --git a/include/spdlog/sinks/windebug_sink.h b/include/spdlog/sinks/windebug_sink.h index 5bd58042..0ada9b94 100644 --- a/include/spdlog/sinks/windebug_sink.h +++ b/include/spdlog/sinks/windebug_sink.h @@ -14,7 +14,7 @@ namespace spdlog { namespace sinks { /* * Windows debug sink (logging using OutputDebugStringA, synonym for msvc_sink) */ -template using windebug_sink = msvc_sink; +template using windebug_sink = msvc_sink; using windebug_sink_mt = msvc_sink_mt; using windebug_sink_st = msvc_sink_st; diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 34706a38..977cc508 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -122,12 +122,12 @@ std::shared_ptr create(const std::string &logger_name, const sink_ptr &s // Create and register a logger with multiple sinks std::shared_ptr create(const std::string &logger_name, sinks_init_list sinks); -template std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end); +template std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end); // Create and register a logger with templated sink type // Example: // spdlog::create("mylog", "dailylog_filename"); -template std::shared_ptr create(const std::string &logger_name, Args... args); +template std::shared_ptr create(const std::string &logger_name, Args... args); // Create and register an async logger with a single sink std::shared_ptr create_async(const std::string &logger_name, const sink_ptr &sink, size_t queue_size, @@ -142,7 +142,7 @@ std::shared_ptr create_async(const std::string &logger_name, sinks_init_ const std::function &worker_warmup_cb = nullptr, const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), const std::function &worker_teardown_cb = nullptr); -template +template std::shared_ptr create_async(const std::string &logger_name, const It &sinks_begin, const It &sinks_end, size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, const std::function &worker_warmup_cb = nullptr, diff --git a/tests/test_misc.cpp b/tests/test_misc.cpp index 772e928d..fa605e3d 100644 --- a/tests/test_misc.cpp +++ b/tests/test_misc.cpp @@ -1,6 +1,6 @@ #include "includes.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; From fe5aaf4932403f3e18cc480d4ae1651369bf4471 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Mar 2018 17:17:33 +0200 Subject: [PATCH 20/62] Fixed example --- example/example.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index f61ea732..385ed53f 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -24,12 +24,6 @@ void err_handler_example(); namespace spd = spdlog; int main(int, char *[]) { - fmt::MemoryWriter w; - w.write("HELLO", 10); - std::string s(w.data(), w.size()); - std::cout << s << std::endl; - return 0; - try { // Console logger with color From ea95ea8295ecfe43011ff1997cfd6024996c5418 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Mar 2018 17:20:56 +0200 Subject: [PATCH 21/62] Fix potential issue #660 --- include/spdlog/fmt/ostr.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/include/spdlog/fmt/ostr.h b/include/spdlog/fmt/ostr.h index cf4c32c5..9902898f 100644 --- a/include/spdlog/fmt/ostr.h +++ b/include/spdlog/fmt/ostr.h @@ -4,10 +4,13 @@ // #pragma once - -// include external or bundled copy of fmtlib's ostream support +// +// include bundled or external copy of fmtlib's ostream support // #if !defined(SPDLOG_FMT_EXTERNAL) +#ifndef FMT_HEADER_ONLY +#define FMT_HEADER_ONLY +#endif #include "bundled/ostream.h" #include "fmt.h" #else From 4ee89877d5e0041771002f7eb408f970531bfe47 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Mar 2018 17:35:50 +0200 Subject: [PATCH 22/62] Changed clang formatting for templates --- .clang-format | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.clang-format b/.clang-format index 24e999da..26dde7e4 100644 --- a/.clang-format +++ b/.clang-format @@ -17,7 +17,7 @@ AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: false +AlwaysBreakTemplateDeclarations: true BinPackArguments: true BinPackParameters: true BraceWrapping: From 4445f6f86900e9ede7f8f111ee3687a693168450 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Mar 2018 17:35:56 +0200 Subject: [PATCH 23/62] formatting --- bench/g2log-async.cpp | 3 +- bench/latency/utils.h | 6 +- bench/utils.h | 6 +- example/example.cpp | 3 +- example/jni/example.cpp | 3 +- example/utils.h | 6 +- include/spdlog/details/logger_impl.h | 69 ++-- include/spdlog/details/mpmc_bounded_q.h | 3 +- include/spdlog/details/registry.h | 6 +- include/spdlog/fmt/bundled/format.h | 436 ++++++++++++++++-------- include/spdlog/fmt/bundled/ostream.h | 9 +- include/spdlog/fmt/bundled/printf.h | 63 ++-- include/spdlog/fmt/bundled/time.h | 3 +- include/spdlog/logger.h | 92 +++-- include/spdlog/sinks/ansicolor_sink.h | 9 +- include/spdlog/sinks/base_sink.h | 3 +- include/spdlog/sinks/dist_sink.h | 3 +- include/spdlog/sinks/file_sinks.h | 9 +- include/spdlog/sinks/msvc_sink.h | 3 +- include/spdlog/sinks/null_sink.h | 3 +- include/spdlog/sinks/ostream_sink.h | 3 +- include/spdlog/sinks/stdout_sinks.h | 6 +- include/spdlog/sinks/wincolor_sink.h | 9 +- include/spdlog/sinks/windebug_sink.h | 3 +- include/spdlog/spdlog.h | 9 +- tests/test_misc.cpp | 3 +- 26 files changed, 524 insertions(+), 247 deletions(-) diff --git a/bench/g2log-async.cpp b/bench/g2log-async.cpp index 1a2f2c76..10b4a8c2 100644 --- a/bench/g2log-async.cpp +++ b/bench/g2log-async.cpp @@ -13,7 +13,8 @@ #include "g2logworker.h" using namespace std; -template std::string format(const T &value); +template +std::string format(const T &value); int main(int argc, char *argv[]) { diff --git a/bench/latency/utils.h b/bench/latency/utils.h index 079c5cb8..91610128 100644 --- a/bench/latency/utils.h +++ b/bench/latency/utils.h @@ -11,7 +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; @@ -20,7 +21,8 @@ template 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; diff --git a/bench/utils.h b/bench/utils.h index 079c5cb8..91610128 100644 --- a/bench/utils.h +++ b/bench/utils.h @@ -11,7 +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; @@ -20,7 +21,8 @@ template 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; diff --git a/example/example.cpp b/example/example.cpp index 385ed53f..48c4b19e 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -133,7 +133,8 @@ void android_example() struct my_type { int i; - template friend OStream &operator<<(OStream &os, const my_type &c) + template + friend OStream &operator<<(OStream &os, const my_type &c) { return os << "[my_type i=" << c.i << "]"; } diff --git a/example/jni/example.cpp b/example/jni/example.cpp index 385ed53f..48c4b19e 100644 --- a/example/jni/example.cpp +++ b/example/jni/example.cpp @@ -133,7 +133,8 @@ void android_example() struct my_type { int i; - template friend OStream &operator<<(OStream &os, const my_type &c) + template + friend OStream &operator<<(OStream &os, const my_type &c) { return os << "[my_type i=" << c.i << "]"; } diff --git a/example/utils.h b/example/utils.h index 079c5cb8..91610128 100644 --- a/example/utils.h +++ b/example/utils.h @@ -11,7 +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; @@ -20,7 +21,8 @@ template 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; diff --git a/include/spdlog/details/logger_impl.h b/include/spdlog/details/logger_impl.h index 70eec0e1..38ff0b8f 100644 --- a/include/spdlog/details/logger_impl.h +++ b/include/spdlog/details/logger_impl.h @@ -50,7 +50,8 @@ inline void spdlog::logger::set_pattern(const std::string &pattern, pattern_time _set_pattern(pattern, pattern_time); } -template inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) +template +inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) { if (!should_log(lvl)) return; @@ -77,7 +78,8 @@ template inline void spdlog::logger::log(level::level_enum lvl } } -template inline void spdlog::logger::log(level::level_enum lvl, const char *msg) +template +inline void spdlog::logger::log(level::level_enum lvl, const char *msg) { if (!should_log(lvl)) return; @@ -98,7 +100,8 @@ template inline void spdlog::logger::log(level::level_enum lvl } } -template inline void spdlog::logger::log(level::level_enum lvl, const T &msg) +template +inline void spdlog::logger::log(level::level_enum lvl, const T &msg) { if (!should_log(lvl)) return; @@ -119,62 +122,74 @@ template inline void spdlog::logger::log(level::level_enum lvl, cons } } -template inline void spdlog::logger::trace(const char *fmt, const Arg1 &arg1, const Args &... args) +template +inline void spdlog::logger::trace(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::trace, fmt, arg1, args...); } -template inline void spdlog::logger::debug(const char *fmt, const Arg1 &arg1, const Args &... args) +template +inline void spdlog::logger::debug(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::debug, fmt, arg1, args...); } -template inline void spdlog::logger::info(const char *fmt, const Arg1 &arg1, const Args &... args) +template +inline void spdlog::logger::info(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::info, fmt, arg1, args...); } -template inline void spdlog::logger::warn(const char *fmt, const Arg1 &arg1, const Args &... args) +template +inline void spdlog::logger::warn(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::warn, fmt, arg1, args...); } -template inline void spdlog::logger::error(const char *fmt, const Arg1 &arg1, const Args &... args) +template +inline void spdlog::logger::error(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::err, fmt, arg1, args...); } -template inline void spdlog::logger::critical(const char *fmt, const Arg1 &arg1, const Args &... args) +template +inline void spdlog::logger::critical(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::critical, fmt, arg1, args...); } -template inline void spdlog::logger::trace(const T &msg) +template +inline void spdlog::logger::trace(const T &msg) { log(level::trace, msg); } -template inline void spdlog::logger::debug(const T &msg) +template +inline void spdlog::logger::debug(const T &msg) { log(level::debug, msg); } -template inline void spdlog::logger::info(const T &msg) +template +inline void spdlog::logger::info(const T &msg) { log(level::info, msg); } -template inline void spdlog::logger::warn(const T &msg) +template +inline void spdlog::logger::warn(const T &msg) { log(level::warn, msg); } -template inline void spdlog::logger::error(const T &msg) +template +inline void spdlog::logger::error(const T &msg) { log(level::err, msg); } -template inline void spdlog::logger::critical(const T &msg) +template +inline void spdlog::logger::critical(const T &msg) { log(level::critical, msg); } @@ -183,14 +198,16 @@ template inline void spdlog::logger::critical(const T &msg) #include #include -template inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *msg) +template +inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *msg) { std::wstring_convert> conv; log(lvl, conv.to_bytes(msg)); } -template inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) +template +inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) { fmt::WMemoryWriter wWriter; @@ -198,32 +215,38 @@ template inline void spdlog::logger::log(level::level_enum lvl log(lvl, wWriter.c_str()); } -template inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args) +template +inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args) { log(level::trace, fmt, args...); } -template inline void spdlog::logger::debug(const wchar_t *fmt, const Args &... args) +template +inline void spdlog::logger::debug(const wchar_t *fmt, const Args &... args) { log(level::debug, fmt, args...); } -template inline void spdlog::logger::info(const wchar_t *fmt, const Args &... args) +template +inline void spdlog::logger::info(const wchar_t *fmt, const Args &... args) { log(level::info, fmt, args...); } -template inline void spdlog::logger::warn(const wchar_t *fmt, const Args &... args) +template +inline void spdlog::logger::warn(const wchar_t *fmt, const Args &... args) { log(level::warn, fmt, args...); } -template inline void spdlog::logger::error(const wchar_t *fmt, const Args &... args) +template +inline void spdlog::logger::error(const wchar_t *fmt, const Args &... args) { log(level::err, fmt, args...); } -template inline void spdlog::logger::critical(const wchar_t *fmt, const Args &... args) +template +inline void spdlog::logger::critical(const wchar_t *fmt, const Args &... args) { log(level::critical, fmt, args...); } diff --git a/include/spdlog/details/mpmc_bounded_q.h b/include/spdlog/details/mpmc_bounded_q.h index 427af65c..29ec316b 100644 --- a/include/spdlog/details/mpmc_bounded_q.h +++ b/include/spdlog/details/mpmc_bounded_q.h @@ -50,7 +50,8 @@ Distributed under the MIT License (http://opensource.org/licenses/MIT) namespace spdlog { namespace details { -template class mpmc_bounded_queue +template +class mpmc_bounded_queue { public: using item_type = T; diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 3f500c1e..ac0a58a5 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -23,7 +23,8 @@ #include namespace spdlog { namespace details { -template class registry_t +template +class registry_t { public: registry_t(const registry_t &) = delete; @@ -44,7 +45,8 @@ public: return found == _loggers.end() ? nullptr : found->second; } - template std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end) + template + std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end) { std::lock_guard lock(_mutex); throw_if_exists(logger_name); diff --git a/include/spdlog/fmt/bundled/format.h b/include/spdlog/fmt/bundled/format.h index 529ffb36..9b2fe3b4 100644 --- a/include/spdlog/fmt/bundled/format.h +++ b/include/spdlog/fmt/bundled/format.h @@ -434,7 +434,8 @@ inline DummyInt _isnan(...) // A helper function to suppress bogus "conditional expression is constant" // warnings. -template inline T const_check(T value) +template +inline T const_check(T value) { return value; } @@ -445,11 +446,13 @@ namespace std { // is used to resolve ambiguity between isinf and std::isinf in glibc: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891 // and the same for isnan and signbit. -template<> class numeric_limits : public std::numeric_limits +template<> +class numeric_limits : public std::numeric_limits { public: // Portable version of isinf. - template static bool isinfinity(T x) + template + static bool isinfinity(T x) { using namespace fmt::internal; // The resolution "priority" is: @@ -462,7 +465,8 @@ public: } // Portable version of isnan. - template static bool isnotanumber(T x) + template + static bool isnotanumber(T x) { using namespace fmt::internal; if (const_check(sizeof(isnan(x)) == sizeof(bool) || sizeof(isnan(x)) == sizeof(int))) @@ -503,18 +507,22 @@ FMT_GCC_EXTENSION typedef unsigned long long ULongLong; using std::move; #endif -template class BasicWriter; +template +class BasicWriter; typedef BasicWriter Writer; typedef BasicWriter WWriter; -template class ArgFormatter; +template +class ArgFormatter; struct FormatSpec; -template class BasicPrintfArgFormatter; +template +class BasicPrintfArgFormatter; -template> class BasicFormatter; +template> +class BasicFormatter; /** \rst @@ -541,7 +549,8 @@ template> format(std::string("{}"), 42); \endrst */ -template class BasicStringRef +template +class BasicStringRef { private: const Char *data_; @@ -688,7 +697,8 @@ typedef BasicStringRef WStringRef; format(std::string("{}"), 42); \endrst */ -template class BasicCStringRef +template +class BasicCStringRef { private: const Char *data_; @@ -739,13 +749,15 @@ public: namespace internal { // MakeUnsigned::Type gives an unsigned type corresponding to integer type T. -template struct MakeUnsigned +template +struct MakeUnsigned { typedef T Type; }; #define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \ - template<> struct MakeUnsigned \ + template<> \ + struct MakeUnsigned \ { \ typedef U Type; \ } @@ -758,7 +770,8 @@ FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long); FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong); // Casts nonnegative integer to unsigned. -template inline typename MakeUnsigned::Type to_unsigned(Int value) +template +inline typename MakeUnsigned::Type to_unsigned(Int value) { FMT_ASSERT(value >= 0, "negative value"); return static_cast::Type>(value); @@ -773,12 +786,14 @@ enum #if FMT_SECURE_SCL // Use checked iterator to avoid warnings on MSVC. -template inline stdext::checked_array_iterator make_ptr(T *ptr, std::size_t size) +template +inline stdext::checked_array_iterator make_ptr(T *ptr, std::size_t size) { return stdext::checked_array_iterator(ptr, size); } #else -template inline T *make_ptr(T *ptr, std::size_t) +template +inline T *make_ptr(T *ptr, std::size_t) { return ptr; } @@ -790,7 +805,8 @@ template inline T *make_ptr(T *ptr, std::size_t) A buffer supporting a subset of ``std::vector``'s operations. \endrst */ -template class Buffer +template +class Buffer { private: FMT_DISALLOW_COPY_AND_ASSIGN(Buffer); @@ -864,7 +880,8 @@ public: } /** Appends data to the end of the buffer. */ - template void append(const U *begin, const U *end); + template + void append(const U *begin, const U *end); T &operator[](std::size_t index) { @@ -876,7 +893,9 @@ public: } }; -template template void Buffer::append(const U *begin, const U *end) +template +template +void Buffer::append(const U *begin, const U *end) { FMT_ASSERT(end >= begin, "negative value"); std::size_t new_size = size_ + static_cast(end - begin); @@ -890,7 +909,8 @@ namespace internal { // A memory buffer for trivially copyable/constructible types with the first // SIZE elements stored in the object itself. -template> class MemoryBuffer : private Allocator, public Buffer +template> +class MemoryBuffer : private Allocator, public Buffer { private: T data_[SIZE]; @@ -961,7 +981,8 @@ public: } }; -template void MemoryBuffer::grow(std::size_t size) +template +void MemoryBuffer::grow(std::size_t size) { std::size_t new_capacity = this->capacity_ + this->capacity_ / 2; if (size > new_capacity) @@ -985,7 +1006,8 @@ template void MemoryBuffer class FixedBuffer : public fmt::Buffer +template +class FixedBuffer : public fmt::Buffer { public: FixedBuffer(Char *array, std::size_t size) @@ -997,7 +1019,8 @@ protected: FMT_API void grow(std::size_t size) FMT_OVERRIDE; }; -template class BasicCharTraits +template +class BasicCharTraits { public: #if FMT_SECURE_SCL @@ -1011,9 +1034,11 @@ public: } }; -template class CharTraits; +template +class CharTraits; -template<> class CharTraits : public BasicCharTraits +template<> +class CharTraits : public BasicCharTraits { private: // Conversion from wchar_t to char is not allowed. @@ -1037,7 +1062,8 @@ extern template int CharTraits::format_float( char *buffer, std::size_t size, const char *format, unsigned width, int precision, long double value); #endif -template<> class CharTraits : public BasicCharTraits +template<> +class CharTraits : public BasicCharTraits { public: static wchar_t convert(char value) @@ -1061,17 +1087,21 @@ extern template int CharTraits::format_float( #endif // Checks if a number is negative - used to avoid warnings. -template struct SignChecker +template +struct SignChecker { - template static bool is_negative(T value) + template + static bool is_negative(T value) { return value < 0; } }; -template<> struct SignChecker +template<> +struct SignChecker { - template static bool is_negative(T) + template + static bool is_negative(T) { return false; } @@ -1079,23 +1109,27 @@ template<> struct SignChecker // Returns true if value is negative, false otherwise. // Same as (value < 0) but doesn't produce warnings if T is an unsigned type. -template inline bool is_negative(T value) +template +inline bool is_negative(T value) { return SignChecker::is_signed>::is_negative(value); } // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise. -template struct TypeSelector +template +struct TypeSelector { typedef uint32_t Type; }; -template<> struct TypeSelector +template<> +struct TypeSelector { typedef uint64_t Type; }; -template struct IntTraits +template +struct IntTraits { // Smallest of uint32_t and uint64_t that is large enough to represent // all values of T. @@ -1106,7 +1140,8 @@ FMT_API FMT_NORETURN void report_unknown_type(char code, const char *type); // Static data is placed in this class template to allow header-only // configuration. -template struct FMT_API BasicData +template +struct FMT_API BasicData { static const uint32_t POWERS_OF_10_32[]; static const uint64_t POWERS_OF_10_64[]; @@ -1165,7 +1200,10 @@ inline unsigned count_digits(uint32_t n) // A functor that doesn't add a thousands separator. struct NoThousandsSep { - template void operator()(Char *) {} + template + void operator()(Char *) + { + } }; // A functor that adds a thousands separator. @@ -1184,7 +1222,8 @@ public: { } - template void operator()(Char *&buffer) + template + void operator()(Char *&buffer) { if (++digit_index_ % 3 != 0) return; @@ -1223,7 +1262,8 @@ inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, Thousa *--buffer = Data::DIGITS[index]; } -template inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) +template +inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) { format_decimal(buffer, value, num_digits, NoThousandsSep()); return; @@ -1304,7 +1344,8 @@ FMT_API void format_windows_error(fmt::Writer &out, int error_code, fmt::StringR // A formatting argument value. struct Value { - template struct StringValue + template + struct StringValue { const Char *value; std::size_t size; @@ -1365,22 +1406,27 @@ struct Arg : Value Type type; }; -template struct NamedArg; -template struct NamedArgWithType; +template +struct NamedArg; +template +struct NamedArgWithType; -template struct Null +template +struct Null { }; // A helper class template to enable or disable overloads taking wide // characters and strings in MakeValue. -template struct WCharHelper +template +struct WCharHelper { typedef Null Supported; typedef T Unsupported; }; -template struct WCharHelper +template +struct WCharHelper { typedef T Supported; typedef Null Unsupported; @@ -1389,13 +1435,15 @@ template struct WCharHelper typedef char Yes[1]; typedef char No[2]; -template T &get(); +template +T &get(); // These are non-members to workaround an overload resolution bug in bcc32. Yes &convert(fmt::ULongLong); No &convert(...); -template struct ConvertToIntImpl +template +struct ConvertToIntImpl { enum { @@ -1403,7 +1451,8 @@ template struct ConvertToIntImpl }; }; -template struct ConvertToIntImpl2 +template +struct ConvertToIntImpl2 { enum { @@ -1411,7 +1460,8 @@ template struct ConvertToIntImpl2 }; }; -template struct ConvertToIntImpl2 +template +struct ConvertToIntImpl2 { enum { @@ -1420,7 +1470,8 @@ template struct ConvertToIntImpl2 }; }; -template struct ConvertToInt +template +struct ConvertToInt { enum { @@ -1433,7 +1484,8 @@ template struct ConvertToInt }; #define FMT_DISABLE_CONVERSION_TO_INT(Type) \ - template<> struct ConvertToInt \ + template<> \ + struct ConvertToInt \ { \ enum \ { \ @@ -1446,27 +1498,32 @@ FMT_DISABLE_CONVERSION_TO_INT(float); FMT_DISABLE_CONVERSION_TO_INT(double); FMT_DISABLE_CONVERSION_TO_INT(long double); -template struct EnableIf +template +struct EnableIf { }; -template struct EnableIf +template +struct EnableIf { typedef T type; }; -template struct Conditional +template +struct Conditional { typedef T type; }; -template struct Conditional +template +struct Conditional { typedef F type; }; // For bcc32 which doesn't understand ! in template arguments. -template struct Not +template +struct Not { enum { @@ -1474,7 +1531,8 @@ template struct Not }; }; -template<> struct Not +template<> +struct Not { enum { @@ -1482,7 +1540,8 @@ template<> struct Not }; }; -template struct FalseType +template +struct FalseType { enum { @@ -1490,7 +1549,8 @@ template struct FalseType }; }; -template struct LConvCheck +template +struct LConvCheck { LConvCheck(int) {} }; @@ -1498,7 +1558,8 @@ template struct LConvCheck // Returns the thousands separator for the current locale. // We check if ``lconv`` contains ``thousands_sep`` because on Android // ``lconv`` is stubbed as an empty struct. -template inline StringRef thousands_sep(LConv *lc, LConvCheck = 0) +template +inline StringRef thousands_sep(LConv *lc, LConvCheck = 0) { return lc->thousands_sep; } @@ -1527,7 +1588,8 @@ inline fmt::StringRef thousands_sep(...) #define FMT_STATIC_ASSERT(cond, message) typedef int FMT_CONCAT_(Assert, __LINE__)[(cond) ? 1 : -1] FMT_UNUSED #endif -template void format_arg(Formatter &, ...) +template +void format_arg(Formatter &, ...) { FMT_STATIC_ASSERT(FalseType::value, "Cannot format argument. To enable the use of ostream " "operator<< include fmt/ostream.h. Otherwise provide " @@ -1535,7 +1597,8 @@ template void format_arg(Formatter &, ...) } // Makes an Arg object from any type. -template class MakeValue : public Arg +template +class MakeValue : public Arg { public: typedef typename Formatter::Char Char; @@ -1546,8 +1609,10 @@ private: // "void *" or "const void *". In particular, this forbids formatting // of "[const] volatile char *" which is printed as bool by iostreams. // Do not implement! - template MakeValue(const T *value); - template MakeValue(T *value); + template + MakeValue(const T *value); + template + MakeValue(T *value); // The following methods are private to disallow formatting of wide // characters and strings into narrow strings as in @@ -1577,7 +1642,8 @@ private: } // Formats an argument of a custom type, such as a user-defined class. - template static void format_custom_arg(void *formatter, const void *arg, void *format_str_ptr) + template + static void format_custom_arg(void *formatter, const void *arg, void *format_str_ptr) { format_arg(*static_cast(formatter), *static_cast(format_str_ptr), *static_cast(arg)); } @@ -1639,12 +1705,14 @@ public: FMT_MAKE_VALUE(char, int_value, CHAR) #if __cplusplus >= 201103L - template::value && ConvertToInt::value>::type> MakeValue(T value) + template::value && ConvertToInt::value>::type> + MakeValue(T value) { int_value = value; } - template::value && ConvertToInt::value>::type> static uint64_t type(T) + template::value && ConvertToInt::value>::type> + static uint64_t type(T) { return Arg::INT; } @@ -1705,39 +1773,46 @@ public: FMT_MAKE_VALUE(void *, pointer, POINTER) FMT_MAKE_VALUE(const void *, pointer, POINTER) - template MakeValue(const T &value, typename EnableIf::value>::value, int>::type = 0) + template + MakeValue(const T &value, typename EnableIf::value>::value, int>::type = 0) { custom.value = &value; custom.format = &format_custom_arg; } - template static typename EnableIf::value>::value, uint64_t>::type type(const T &) + template + static typename EnableIf::value>::value, uint64_t>::type type(const T &) { return Arg::CUSTOM; } // Additional template param `Char_` is needed here because make_type always // uses char. - template MakeValue(const NamedArg &value) + template + MakeValue(const NamedArg &value) { pointer = &value; } - template MakeValue(const NamedArgWithType &value) + template + MakeValue(const NamedArgWithType &value) { pointer = &value; } - template static uint64_t type(const NamedArg &) + template + static uint64_t type(const NamedArg &) { return Arg::NAMED_ARG; } - template static uint64_t type(const NamedArgWithType &) + template + static uint64_t type(const NamedArgWithType &) { return Arg::NAMED_ARG; } }; -template class MakeArg : public Arg +template +class MakeArg : public Arg { public: MakeArg() @@ -1753,7 +1828,8 @@ public: } }; -template struct NamedArg : Arg +template +struct NamedArg : Arg { BasicStringRef name; @@ -1765,7 +1841,8 @@ template struct NamedArg : Arg } }; -template struct NamedArgWithType : NamedArg +template +struct NamedArgWithType : NamedArg { NamedArgWithType(BasicStringRef argname, const T &value) : NamedArg(argname, value) @@ -1787,7 +1864,8 @@ protected: FMT_API ~RuntimeError() FMT_DTOR_NOEXCEPT FMT_OVERRIDE; }; -template class ArgMap; +template +class ArgMap; } // namespace internal /** An argument list. */ @@ -1813,7 +1891,8 @@ private: return type(types_, index); } - template friend class internal::ArgMap; + template + friend class internal::ArgMap; public: // Maximum number of arguments with packed types. @@ -1907,7 +1986,8 @@ public: }; \endrst */ -template class ArgVisitor +template +class ArgVisitor { private: typedef internal::Arg Arg; @@ -1958,7 +2038,8 @@ public: } /** Visits an argument of any integral type. **/ - template Result visit_any_int(T) + template + Result visit_any_int(T) { return FMT_DISPATCH(visit_unhandled_arg()); } @@ -1976,7 +2057,8 @@ public: } /** Visits a ``double`` or ``long double`` argument. **/ - template Result visit_any_double(T) + template + Result visit_any_double(T) { return FMT_DISPATCH(visit_unhandled_arg()); } @@ -2083,7 +2165,8 @@ struct EmptySpec }; // A type specifier. -template struct TypeSpec : EmptySpec +template +struct TypeSpec : EmptySpec { Alignment align() const { @@ -2162,7 +2245,8 @@ struct AlignSpec : WidthSpec }; // An alignment and type specifier. -template struct AlignTypeSpec : AlignSpec +template +struct AlignTypeSpec : AlignSpec { AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) @@ -2217,7 +2301,8 @@ struct FormatSpec : AlignSpec }; // An integer format specifier. -template, typename Char = char> class IntFormatSpec : public SpecT +template, typename Char = char> +class IntFormatSpec : public SpecT { private: T value_; @@ -2236,7 +2321,8 @@ public: }; // A string format specifier. -template class StrFormatSpec : public AlignSpec +template +class StrFormatSpec : public AlignSpec { private: const Char *str_; @@ -2292,7 +2378,8 @@ IntFormatSpec> hexu(int value); \endrst */ -template IntFormatSpec, Char> pad(int value, unsigned width, Char fill = ' '); +template +IntFormatSpec, Char> pad(int value, unsigned width, Char fill = ' '); #define FMT_DEFINE_INT_FORMATTERS(TYPE) \ inline IntFormatSpec> bin(TYPE value) \ @@ -2337,7 +2424,8 @@ template IntFormatSpec>(value, AlignTypeSpec<0>(width, ' ')); \ } \ \ - template inline IntFormatSpec, Char> pad(TYPE value, unsigned width, Char fill) \ + template \ + inline IntFormatSpec, Char> pad(TYPE value, unsigned width, Char fill) \ { \ return IntFormatSpec, Char>(value, AlignTypeSpec<0>(width, fill)); \ } @@ -2361,7 +2449,8 @@ FMT_DEFINE_INT_FORMATTERS(ULongLong) \endrst */ -template inline StrFormatSpec pad(const Char *str, unsigned width, Char fill = ' ') +template +inline StrFormatSpec pad(const Char *str, unsigned width, Char fill = ' ') { return StrFormatSpec(str, width, fill); } @@ -2373,7 +2462,8 @@ inline StrFormatSpec pad(const wchar_t *str, unsigned width, char fill namespace internal { -template class ArgMap +template +class ArgMap { private: typedef std::vector, internal::Arg>> MapType; @@ -2396,7 +2486,8 @@ public: } }; -template void ArgMap::init(const ArgList &args) +template +void ArgMap::init(const ArgList &args) { if (!map_.empty()) return; @@ -2449,7 +2540,8 @@ template void ArgMap::init(const ArgList &args) } } -template class ArgFormatterBase : public ArgVisitor +template +class ArgFormatterBase : public ArgVisitor { private: BasicWriter &writer_; @@ -2499,12 +2591,14 @@ public: { } - template void visit_any_int(T value) + template + void visit_any_int(T value) { writer_.write_int(value, spec_); } - template void visit_any_double(T value) + template + void visit_any_double(T value) { writer_.write_double(value, spec_); } @@ -2633,7 +2727,8 @@ protected: return true; } - template void write(BasicWriter &w, const Char *start, const Char *end) + template + void write(BasicWriter &w, const Char *start, const Char *end) { if (start != end) w << BasicStringRef(start, internal::to_unsigned(end - start)); @@ -2689,7 +2784,8 @@ public: }; /** The default argument formatter. */ -template class ArgFormatter : public BasicArgFormatter, Char, FormatSpec> +template +class ArgFormatter : public BasicArgFormatter, Char, FormatSpec> { public: /** Constructs an argument formatter object. */ @@ -2700,7 +2796,8 @@ public: }; /** This template formats data and writes the output to a writer. */ -template class BasicFormatter : private internal::FormatterBase +template +class BasicFormatter : private internal::FormatterBase { public: /** The character type for the output. */ @@ -2776,19 +2873,23 @@ inline uint64_t make_type() return 0; } -template inline uint64_t make_type(const T &arg) +template +inline uint64_t make_type(const T &arg) { return MakeValue>::type(arg); } -template struct ArgArray; +template +struct ArgArray; -template struct ArgArray +template +struct ArgArray { // '+' is used to silence GCC -Wduplicated-branches warning. typedef Value Type[N > 0 ? N : +1]; - template static Value make(const T &value) + template + static Value make(const T &value) { #ifdef __clang__ Value result = MakeValue(value); @@ -2802,18 +2903,21 @@ template struct ArgArray } }; -template struct ArgArray +template +struct ArgArray { typedef Arg Type[N + 1]; // +1 for the list end Arg::NONE - template static Arg make(const T &value) + template + static Arg make(const T &value) { return MakeArg(value); } }; #if FMT_USE_VARIADIC_TEMPLATES -template inline uint64_t make_type(const Arg &first, const Args &... tail) +template +inline uint64_t make_type(const Arg &first, const Args &... tail) { return make_type(first) | (make_type(tail...) << 4); } @@ -2856,7 +2960,8 @@ inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) #if FMT_USE_VARIADIC_TEMPLATES // Defines a variadic function returning void. #define FMT_VARIADIC_VOID(func, arg_type) \ - template void func(arg_type arg0, const Args &... args) \ + template \ + void func(arg_type arg0, const Args &... args) \ { \ typedef fmt::internal::ArgArray ArgArray; \ typename ArgArray::Type array{ArgArray::template make>(args)...}; \ @@ -2865,7 +2970,8 @@ inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) // Defines a variadic constructor. #define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ - template ctor(arg0_type arg0, arg1_type arg1, const Args &... args) \ + template \ + ctor(arg0_type arg0, arg1_type arg1, const Args &... args) \ { \ typedef fmt::internal::ArgArray ArgArray; \ typename ArgArray::Type array{ArgArray::template make>(args)...}; \ @@ -2880,7 +2986,8 @@ inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) // Defines a wrapper for a function taking one argument of type arg_type // and n additional arguments of arbitrary types. #define FMT_WRAP1(func, arg_type, n) \ - template inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ + template \ + inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ { \ const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ func(arg1, fmt::ArgList(fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ @@ -2901,7 +3008,8 @@ inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) #define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ - template ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ + template \ + ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ { \ const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ @@ -3020,7 +3128,8 @@ FMT_API void format_system_error(fmt::Writer &out, int error_code, fmt::StringRe \endrst */ -template class BasicWriter +template +class BasicWriter { private: // Output buffer. @@ -3057,7 +3166,8 @@ private: } // Writes an unsigned decimal integer. - template Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) + template + Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) { unsigned num_digits = internal::count_digits(value); Char *ptr = get(grow_buffer(prefix_size + num_digits)); @@ -3066,7 +3176,8 @@ private: } // Writes a decimal integer. - template void write_decimal(Int value) + template + void write_decimal(Int value) { typedef typename internal::IntTraits::MainType MainType; MainType abs_value = static_cast(value); @@ -3090,18 +3201,23 @@ private: return p + size - 1; } - template CharPtr prepare_int_buffer(unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size); + template + CharPtr prepare_int_buffer(unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size); // Formats an integer. - template void write_int(T value, Spec spec); + template + void write_int(T value, Spec spec); // Formats a floating-point number (double or long double). - template void write_double(T value, const Spec &spec); + template + void write_double(T value, const Spec &spec); // Writes a formatted string. - template CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); + template + CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); - template void write_str(const internal::Arg::StringValue &str, const Spec &spec); + template + void write_str(const internal::Arg::StringValue &str, const Spec &spec); // This following methods are private to disallow writing wide characters // and strings to a char stream. If you want to print a wide string as a @@ -3117,11 +3233,16 @@ private: *format_ptr++ = 'L'; } - template void append_float_length(Char *&, T) {} + template + void append_float_length(Char *&, T) + { + } - template friend class internal::ArgFormatterBase; + template + friend class internal::ArgFormatterBase; - template friend class BasicPrintfArgFormatter; + template + friend class BasicPrintfArgFormatter; protected: /** @@ -3296,14 +3417,16 @@ public: return *this; } - template BasicWriter &operator<<(IntFormatSpec spec) + template + BasicWriter &operator<<(IntFormatSpec spec) { internal::CharTraits::convert(FillChar()); write_int(spec.value(), spec); return *this; } - template BasicWriter &operator<<(const StrFormatSpec &spec) + template + BasicWriter &operator<<(const StrFormatSpec &spec) { const StrChar *s = spec.str(); write_str(s, std::char_traits::length(s), spec); @@ -3463,7 +3586,9 @@ typename BasicWriter::CharPtr BasicWriter::prepare_int_buffer( return p - 1; } -template template void BasicWriter::write_int(T value, Spec spec) +template +template +void BasicWriter::write_int(T value, Spec spec) { unsigned prefix_size = 0; typedef typename internal::IntTraits::MainType UnsignedType; @@ -3571,7 +3696,9 @@ template template void BasicWriter template void BasicWriter::write_double(T value, const Spec &spec) +template +template +void BasicWriter::write_double(T value, const Spec &spec) { // Check type. char type = spec.type(); @@ -3789,7 +3916,8 @@ template template void BasicWriter> class BasicMemoryWriter : public BasicWriter +template> +class BasicMemoryWriter : public BasicWriter { private: internal::MemoryBuffer buffer_; @@ -3850,7 +3978,8 @@ typedef BasicMemoryWriter WMemoryWriter; +--------------+---------------------------+ \endrst */ -template class BasicArrayWriter : public BasicWriter +template +class BasicArrayWriter : public BasicWriter { private: internal::FixedBuffer buffer_; @@ -4120,7 +4249,8 @@ public: // Formats a decimal integer value writing into buffer and returns // a pointer to the end of the formatted string. This function doesn't // write a terminating null character. -template inline void format_decimal(char *&buffer, T value) +template +inline void format_decimal(char *&buffer, T value) { typedef typename internal::IntTraits::MainType MainType; MainType abs_value = static_cast(value); @@ -4156,20 +4286,24 @@ template inline void format_decimal(char *&buffer, T value) \endrst */ -template inline internal::NamedArgWithType arg(StringRef name, const T &arg) +template +inline internal::NamedArgWithType arg(StringRef name, const T &arg) { return internal::NamedArgWithType(name, arg); } -template inline internal::NamedArgWithType arg(WStringRef name, const T &arg) +template +inline internal::NamedArgWithType arg(WStringRef name, const T &arg) { return internal::NamedArgWithType(name, arg); } // The following two functions are deleted intentionally to disable // nested named arguments as in ``format("{}", arg("a", arg("b", 42)))``. -template void arg(StringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; -template void arg(WStringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; +template +void arg(StringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; +template +void arg(WStringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; } // namespace fmt #if FMT_GCC_VERSION @@ -4198,7 +4332,8 @@ template void arg(WStringRef, const internal::NamedArg &) F #if FMT_USE_VARIADIC_TEMPLATES #define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ - template ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), const Args &... args) Const \ + template \ + ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), const Args &... args) Const \ { \ typedef fmt::internal::ArgArray ArgArray; \ typename ArgArray::Type array{ArgArray::template make>(args)...}; \ @@ -4303,14 +4438,16 @@ FMT_VARIADIC(void, print, std::FILE *, CStringRef) FMT_VARIADIC(void, print_colored, Color, CStringRef) namespace internal { -template inline bool is_name_start(Char c) +template +inline bool is_name_start(Char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; } // Parses an unsigned integer advancing s to the end of the parsed input. // This function assumes that the first character of s is a digit. -template unsigned parse_nonnegative_int(const Char *&s) +template +unsigned parse_nonnegative_int(const Char *&s) { assert('0' <= *s && *s <= '9'); unsigned value = 0; @@ -4343,7 +4480,8 @@ inline void require_numeric_argument(const Arg &arg, char spec) } } -template void check_sign(const Char *&s, const Arg &arg) +template +void check_sign(const Char *&s, const Arg &arg) { char sign = static_cast(*s); require_numeric_argument(arg, sign); @@ -4369,7 +4507,8 @@ inline internal::Arg BasicFormatter::get_arg(BasicStringRef arg_ return internal::Arg(); } -template inline internal::Arg BasicFormatter::parse_arg_index(const Char *&s) +template +inline internal::Arg BasicFormatter::parse_arg_index(const Char *&s) { const char *error = FMT_NULL; internal::Arg arg = *s < '0' || *s > '9' ? next_arg(error) : get_arg(internal::parse_nonnegative_int(s), error); @@ -4380,7 +4519,8 @@ template inline internal::Arg BasicFormatter inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) +template +inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) { assert(internal::is_name_start(*s)); const Char *start = s; @@ -4590,7 +4730,8 @@ const Char *BasicFormatter::format(const Char *&format_str, return s; } -template void BasicFormatter::format(BasicCStringRef format_str) +template +void BasicFormatter::format(BasicCStringRef format_str) { const Char *s = format_str.c_str(); const Char *start = s; @@ -4614,7 +4755,8 @@ template void BasicFormatter::format(Basic write(writer_, start, s); } -template struct ArgJoin +template +struct ArgJoin { It first; It last; @@ -4628,23 +4770,27 @@ template struct ArgJoin } }; -template ArgJoin join(It first, It last, const BasicCStringRef &sep) +template +ArgJoin join(It first, It last, const BasicCStringRef &sep) { return ArgJoin(first, last, sep); } -template ArgJoin join(It first, It last, const BasicCStringRef &sep) +template +ArgJoin join(It first, It last, const BasicCStringRef &sep) { return ArgJoin(first, last, sep); } #if FMT_HAS_GXX_CXX11 -template auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin +template +auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin { return join(std::begin(range), std::end(range), sep); } -template auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin +template +auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin { return join(std::begin(range), std::end(range), sep); } @@ -4681,21 +4827,25 @@ void format_arg(fmt::BasicFormatter &f, const Char *&format_ namespace fmt { namespace internal { -template struct UdlFormat +template +struct UdlFormat { const Char *str; - template auto operator()(Args &&... args) const -> decltype(format(str, std::forward(args)...)) + template + auto operator()(Args &&... args) const -> decltype(format(str, std::forward(args)...)) { return format(str, std::forward(args)...); } }; -template struct UdlArg +template +struct UdlArg { const Char *str; - template NamedArgWithType operator=(T &&value) const + template + NamedArgWithType operator=(T &&value) const { return {str, std::forward(value)}; } diff --git a/include/spdlog/fmt/bundled/ostream.h b/include/spdlog/fmt/bundled/ostream.h index 98f9f22a..ffa75ab0 100644 --- a/include/spdlog/fmt/bundled/ostream.h +++ b/include/spdlog/fmt/bundled/ostream.h @@ -17,7 +17,8 @@ namespace fmt { namespace internal { -template class FormatBuf : public std::basic_streambuf +template +class FormatBuf : public std::basic_streambuf { private: typedef typename std::basic_streambuf::int_type int_type; @@ -60,12 +61,14 @@ struct DummyStream : std::ostream DummyStream(); // Suppress a bogus warning in MSVC. // Hide all operator<< overloads from std::ostream. - template typename EnableIf::type operator<<(const T &); + template + typename EnableIf::type operator<<(const T &); }; No &operator<<(std::ostream &, int); -template struct ConvertToIntImpl +template +struct ConvertToIntImpl { // Convert to int only if T doesn't have an overloaded operator<<. enum diff --git a/include/spdlog/fmt/bundled/printf.h b/include/spdlog/fmt/bundled/printf.h index 2102cf24..679e8fc1 100644 --- a/include/spdlog/fmt/bundled/printf.h +++ b/include/spdlog/fmt/bundled/printf.h @@ -20,9 +20,11 @@ namespace internal { // Checks if a value fits in int - used to avoid warnings about comparing // signed and unsigned integers. -template struct IntChecker +template +struct IntChecker { - template static bool fits_in_int(T value) + template + static bool fits_in_int(T value) { unsigned max = std::numeric_limits::max(); return value <= max; @@ -33,9 +35,11 @@ template struct IntChecker } }; -template<> struct IntChecker +template<> +struct IntChecker { - template static bool fits_in_int(T value) + template + static bool fits_in_int(T value) { return value >= std::numeric_limits::min() && value <= std::numeric_limits::max(); } @@ -53,7 +57,8 @@ public: FMT_THROW(FormatError("precision is not integer")); } - template int visit_any_int(T value) + template + int visit_any_int(T value) { if (!IntChecker::is_signed>::fits_in_int(value)) FMT_THROW(FormatError("number is too big")); @@ -65,7 +70,8 @@ public: class IsZeroInt : public ArgVisitor { public: - template bool visit_any_int(T value) + template + bool visit_any_int(T value) { return value == 0; } @@ -90,12 +96,14 @@ public: return 'p'; } - template char visit_any_int(T) + template + char visit_any_int(T) { return 'd'; } - template char visit_any_double(T) + template + char visit_any_double(T) { return 'g'; } @@ -106,7 +114,8 @@ public: } }; -template struct is_same +template +struct is_same { enum { @@ -114,7 +123,8 @@ template struct is_same }; }; -template struct is_same +template +struct is_same { enum { @@ -126,7 +136,8 @@ template struct is_same // if T is an integral type. If T is void, the argument is converted to // corresponding signed or unsigned type depending on the type specifier: // 'd' and 'i' - signed, other - unsigned) -template class ArgConverter : public ArgVisitor, void> +template +class ArgConverter : public ArgVisitor, void> { private: internal::Arg &arg_; @@ -153,7 +164,8 @@ public: visit_any_int(value); } - template void visit_any_int(U value) + template + void visit_any_int(U value) { bool is_signed = type_ == 'd' || type_ == 'i'; if (type_ == 's') @@ -211,7 +223,8 @@ public: { } - template void visit_any_int(T value) + template + void visit_any_int(T value) { arg_.type = internal::Arg::CHAR; arg_.int_value = static_cast(value); @@ -238,7 +251,8 @@ public: FMT_THROW(FormatError("width is not integer")); } - template unsigned visit_any_int(T value) + template + unsigned visit_any_int(T value) { typedef typename internal::IntTraits::MainType UnsignedType; UnsignedType width = static_cast(value); @@ -272,7 +286,8 @@ public: superclass will be called. \endrst */ -template class BasicPrintfArgFormatter : public internal::ArgFormatterBase +template +class BasicPrintfArgFormatter : public internal::ArgFormatterBase { private: void write_null_pointer() @@ -367,7 +382,8 @@ public: }; /** The default printf argument formatter. */ -template class PrintfArgFormatter : public BasicPrintfArgFormatter, Char, FormatSpec> +template +class PrintfArgFormatter : public BasicPrintfArgFormatter, Char, FormatSpec> { public: /** Constructs an argument formatter object. */ @@ -378,7 +394,8 @@ public: }; /** This template formats data and writes the output to a writer. */ -template> class PrintfFormatter : private internal::FormatterBase +template> +class PrintfFormatter : private internal::FormatterBase { private: BasicWriter &writer_; @@ -410,7 +427,8 @@ public: void format(BasicCStringRef format_str); }; -template void PrintfFormatter::parse_flags(FormatSpec &spec, const Char *&s) +template +void PrintfFormatter::parse_flags(FormatSpec &spec, const Char *&s) { for (;;) { @@ -438,7 +456,8 @@ template void PrintfFormatter::parse_flags } } -template internal::Arg PrintfFormatter::get_arg(const Char *s, unsigned arg_index) +template +internal::Arg PrintfFormatter::get_arg(const Char *s, unsigned arg_index) { (void)s; const char *error = FMT_NULL; @@ -448,7 +467,8 @@ template internal::Arg PrintfFormatter::ge return arg; } -template unsigned PrintfFormatter::parse_header(const Char *&s, FormatSpec &spec) +template +unsigned PrintfFormatter::parse_header(const Char *&s, FormatSpec &spec) { unsigned arg_index = std::numeric_limits::max(); Char c = *s; @@ -489,7 +509,8 @@ template unsigned PrintfFormatter::parse_h return arg_index; } -template void PrintfFormatter::format(BasicCStringRef format_str) +template +void PrintfFormatter::format(BasicCStringRef format_str) { const Char *start = format_str.c_str(); const Char *s = start; diff --git a/include/spdlog/fmt/bundled/time.h b/include/spdlog/fmt/bundled/time.h index e5f0d772..1d4210c8 100644 --- a/include/spdlog/fmt/bundled/time.h +++ b/include/spdlog/fmt/bundled/time.h @@ -20,7 +20,8 @@ #endif namespace fmt { -template void format_arg(BasicFormatter &f, const char *&format_str, const std::tm &tm) +template +void format_arg(BasicFormatter &f, const char *&format_str, const std::tm &tm) { if (*format_str == ':') ++format_str; diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 8358cee2..8e52095d 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -27,40 +27,84 @@ public: logger(const std::string &name, sink_ptr single_sink); logger(const std::string &name, sinks_init_list sinks); - template logger(std::string name, const It &begin, const It &end); + template + logger(std::string name, const It &begin, const It &end); virtual ~logger(); logger(const logger &) = delete; logger &operator=(const logger &) = delete; - template void log(level::level_enum lvl, const char *fmt, const Args &... args); - template void log(level::level_enum lvl, const char *msg); - template void trace(const char *fmt, const Arg1 &, const Args &... args); - template void debug(const char *fmt, const Arg1 &, const Args &... args); - template void info(const char *fmt, const Arg1 &, const Args &... args); - template void warn(const char *fmt, const Arg1 &, const Args &... args); - template void error(const char *fmt, const Arg1 &, const Args &... args); - template void critical(const char *fmt, const Arg1 &, const Args &... args); + template + void log(level::level_enum lvl, const char *fmt, const Args &... args); + + template + void log(level::level_enum lvl, const char *msg); + + template + void trace(const char *fmt, const Arg1 &, const Args &... args); + + template + void debug(const char *fmt, const Arg1 &, const Args &... args); + + template + void info(const char *fmt, const Arg1 &, const Args &... args); + + template + void warn(const char *fmt, const Arg1 &, const Args &... args); + + template + void error(const char *fmt, const Arg1 &, const Args &... args); + + template + void critical(const char *fmt, const Arg1 &, const Args &... args); #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT - template void log(level::level_enum lvl, const wchar_t *msg); - template void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); - template void trace(const wchar_t *fmt, const Args &... args); - template void debug(const wchar_t *fmt, const Args &... args); - template void info(const wchar_t *fmt, const Args &... args); - template void warn(const wchar_t *fmt, const Args &... args); - template void error(const wchar_t *fmt, const Args &... args); - template void critical(const wchar_t *fmt, const Args &... args); + template + void log(level::level_enum lvl, const wchar_t *msg); + + template + void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); + + template + void trace(const wchar_t *fmt, const Args &... args); + + template + void debug(const wchar_t *fmt, const Args &... args); + + template + void info(const wchar_t *fmt, const Args &... args); + + template + void warn(const wchar_t *fmt, const Args &... args); + + template + void error(const wchar_t *fmt, const Args &... args); + + template + void critical(const wchar_t *fmt, const Args &... args); + #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT + template + void log(level::level_enum lvl, const T &); + + template + void trace(const T &msg); + + template + void debug(const T &msg); + + template + void info(const T &msg); + + template + void warn(const T &msg); + + template + void error(const T &msg); - template void log(level::level_enum lvl, const T &); - template void trace(const T &msg); - template void debug(const T &msg); - template void info(const T &msg); - template void warn(const T &msg); - template void error(const T &msg); - template void critical(const T &msg); + template + void critical(const T &msg); bool should_log(level::level_enum msg_level) const; void set_level(level::level_enum log_level); diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index d08eac47..2a5203c3 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -19,7 +19,8 @@ namespace spdlog { namespace sinks { * of the message. * If no color terminal detected, omit the escape codes. */ -template class ansicolor_sink : public base_sink +template +class ansicolor_sink : public base_sink { public: explicit ansicolor_sink(FILE *file) @@ -106,7 +107,8 @@ protected: std::unordered_map colors_; }; -template class ansicolor_stdout_sink : public ansicolor_sink +template +class ansicolor_stdout_sink : public ansicolor_sink { public: ansicolor_stdout_sink() @@ -118,7 +120,8 @@ public: using ansicolor_stdout_sink_mt = ansicolor_stdout_sink; using ansicolor_stdout_sink_st = ansicolor_stdout_sink; -template class ansicolor_stderr_sink : public ansicolor_sink +template +class ansicolor_stderr_sink : public ansicolor_sink { public: ansicolor_stderr_sink() diff --git a/include/spdlog/sinks/base_sink.h b/include/spdlog/sinks/base_sink.h index 7c628c18..16035ec9 100644 --- a/include/spdlog/sinks/base_sink.h +++ b/include/spdlog/sinks/base_sink.h @@ -18,7 +18,8 @@ #include namespace spdlog { namespace sinks { -template class base_sink : public sink +template +class base_sink : public sink { public: base_sink() = default; diff --git a/include/spdlog/sinks/dist_sink.h b/include/spdlog/sinks/dist_sink.h index c2c91412..3191783a 100644 --- a/include/spdlog/sinks/dist_sink.h +++ b/include/spdlog/sinks/dist_sink.h @@ -18,7 +18,8 @@ // Distribution sink (mux). Stores a vector of sinks which get called when log is called namespace spdlog { namespace sinks { -template class dist_sink : public base_sink +template +class dist_sink : public base_sink { public: explicit dist_sink() diff --git a/include/spdlog/sinks/file_sinks.h b/include/spdlog/sinks/file_sinks.h index 9b3cc9f5..6f8517e8 100644 --- a/include/spdlog/sinks/file_sinks.h +++ b/include/spdlog/sinks/file_sinks.h @@ -22,7 +22,8 @@ namespace spdlog { namespace sinks { /* * Trivial file sink with single file as target */ -template class simple_file_sink SPDLOG_FINAL : public base_sink +template +class simple_file_sink SPDLOG_FINAL : public base_sink { public: explicit simple_file_sink(const filename_t &filename, bool truncate = false) @@ -60,7 +61,8 @@ using simple_file_sink_st = simple_file_sink; /* * Rotating file sink based on size */ -template class rotating_file_sink SPDLOG_FINAL : public base_sink +template +class rotating_file_sink SPDLOG_FINAL : public base_sink { public: rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files) @@ -185,7 +187,8 @@ struct dateonly_daily_file_name_calculator /* * Rotating file sink based on date. rotates at midnight */ -template class daily_file_sink SPDLOG_FINAL : public base_sink +template +class daily_file_sink SPDLOG_FINAL : public base_sink { public: // create daily file sink which rotates on given time diff --git a/include/spdlog/sinks/msvc_sink.h b/include/spdlog/sinks/msvc_sink.h index a618886b..fa83a18c 100644 --- a/include/spdlog/sinks/msvc_sink.h +++ b/include/spdlog/sinks/msvc_sink.h @@ -19,7 +19,8 @@ namespace spdlog { namespace sinks { /* * MSVC sink (logging using OutputDebugStringA) */ -template class msvc_sink : public base_sink +template +class msvc_sink : public base_sink { public: explicit msvc_sink() {} diff --git a/include/spdlog/sinks/null_sink.h b/include/spdlog/sinks/null_sink.h index 46e90775..c0ae4167 100644 --- a/include/spdlog/sinks/null_sink.h +++ b/include/spdlog/sinks/null_sink.h @@ -12,7 +12,8 @@ namespace spdlog { namespace sinks { -template class null_sink : public base_sink +template +class null_sink : public base_sink { protected: void _sink_it(const details::log_msg &) override {} diff --git a/include/spdlog/sinks/ostream_sink.h b/include/spdlog/sinks/ostream_sink.h index 5c4ec810..7d91a1ee 100644 --- a/include/spdlog/sinks/ostream_sink.h +++ b/include/spdlog/sinks/ostream_sink.h @@ -12,7 +12,8 @@ #include namespace spdlog { namespace sinks { -template class ostream_sink : public base_sink +template +class ostream_sink : public base_sink { public: explicit ostream_sink(std::ostream &os, bool force_flush = false) diff --git a/include/spdlog/sinks/stdout_sinks.h b/include/spdlog/sinks/stdout_sinks.h index fb3e1bc0..35324370 100644 --- a/include/spdlog/sinks/stdout_sinks.h +++ b/include/spdlog/sinks/stdout_sinks.h @@ -14,7 +14,8 @@ namespace spdlog { namespace sinks { -template class stdout_sink SPDLOG_FINAL : public base_sink +template +class stdout_sink SPDLOG_FINAL : public base_sink { using MyType = stdout_sink; @@ -43,7 +44,8 @@ protected: using stdout_sink_mt = stdout_sink; using stdout_sink_st = stdout_sink; -template class stderr_sink SPDLOG_FINAL : public base_sink +template +class stderr_sink SPDLOG_FINAL : public base_sink { using MyType = stderr_sink; diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index 3f5fdfe6..bc036d44 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -18,7 +18,8 @@ namespace spdlog { namespace sinks { /* * Windows color console sink. Uses WriteConsoleA to write to the console with colors */ -template class wincolor_sink : public base_sink +template +class wincolor_sink : public base_sink { public: const WORD BOLD = FOREGROUND_INTENSITY; @@ -89,7 +90,8 @@ private: // // windows color console to stdout // -template class wincolor_stdout_sink : public wincolor_sink +template +class wincolor_stdout_sink : public wincolor_sink { public: wincolor_stdout_sink() @@ -104,7 +106,8 @@ using wincolor_stdout_sink_st = wincolor_stdout_sink; // // windows color console to stderr // -template class wincolor_stderr_sink : public wincolor_sink +template +class wincolor_stderr_sink : public wincolor_sink { public: wincolor_stderr_sink() diff --git a/include/spdlog/sinks/windebug_sink.h b/include/spdlog/sinks/windebug_sink.h index 0ada9b94..353a7bde 100644 --- a/include/spdlog/sinks/windebug_sink.h +++ b/include/spdlog/sinks/windebug_sink.h @@ -14,7 +14,8 @@ namespace spdlog { namespace sinks { /* * Windows debug sink (logging using OutputDebugStringA, synonym for msvc_sink) */ -template using windebug_sink = msvc_sink; +template +using windebug_sink = msvc_sink; using windebug_sink_mt = msvc_sink_mt; using windebug_sink_st = msvc_sink_st; diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 977cc508..21f5951b 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -81,6 +81,7 @@ std::shared_ptr basic_logger_st(const std::string &logger_name, const fi // std::shared_ptr rotating_logger_mt( const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files); + std::shared_ptr rotating_logger_st( const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files); @@ -122,12 +123,15 @@ std::shared_ptr create(const std::string &logger_name, const sink_ptr &s // Create and register a logger with multiple sinks std::shared_ptr create(const std::string &logger_name, sinks_init_list sinks); -template std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end); + +template +std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end); // Create and register a logger with templated sink type // Example: // spdlog::create("mylog", "dailylog_filename"); -template std::shared_ptr create(const std::string &logger_name, Args... args); +template +std::shared_ptr create(const std::string &logger_name, Args... args); // Create and register an async logger with a single sink std::shared_ptr create_async(const std::string &logger_name, const sink_ptr &sink, size_t queue_size, @@ -142,6 +146,7 @@ std::shared_ptr create_async(const std::string &logger_name, sinks_init_ const std::function &worker_warmup_cb = nullptr, const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), const std::function &worker_teardown_cb = nullptr); + template std::shared_ptr create_async(const std::string &logger_name, const It &sinks_begin, const It &sinks_end, size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, diff --git a/tests/test_misc.cpp b/tests/test_misc.cpp index fa605e3d..73ef926b 100644 --- a/tests/test_misc.cpp +++ b/tests/test_misc.cpp @@ -1,6 +1,7 @@ #include "includes.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; From fe8a519434c70c28717b5c951dacc83e1d5ccf84 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Fri, 16 Mar 2018 22:03:54 +0200 Subject: [PATCH 24/62] Update logger.h --- include/spdlog/logger.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 8e52095d..e05867ef 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -83,8 +83,8 @@ public: template void critical(const wchar_t *fmt, const Args &... args); - #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT + template void log(level::level_enum lvl, const T &); From c739e68021b4fdeaf22b3612fc1ed1dfe34021d1 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 17 Mar 2018 12:47:04 +0200 Subject: [PATCH 25/62] clang format namespace fix --- .clang-format | 2 +- format.sh | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.clang-format b/.clang-format index 26dde7e4..89e5b902 100644 --- a/.clang-format +++ b/.clang-format @@ -45,7 +45,7 @@ BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true ColumnLimit: 140 CommentPragmas: '^ IWYU pragma:' -CompactNamespaces: true +CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 diff --git a/format.sh b/format.sh index 6c61c628..51b987e4 100755 --- a/format.sh +++ b/format.sh @@ -1,5 +1,9 @@ #!/bin/bash -find . -name "*\.h" -o -name "*\.cpp"|xargs dos2unix -find . -name "*\.h" -o -name "*\.cpp"|xargs clang-format -i +echo -n "Running dos2unix " +find . -name "*\.h" -o -name "*\.cpp"|xargs -I {} sh -c "dos2unix '{}' 2>/dev/null; echo -n '.'" +echo +echo -n "Running clang-format " +find . -name "*\.h" -o -name "*\.cpp"|xargs -I {} sh -c "clang-format -i {}; echo -n '.'" +echo From 56e4a201ec7a703b22b8ad37852ef093b318d26e Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 17 Mar 2018 12:47:46 +0200 Subject: [PATCH 26/62] formatting --- include/spdlog/common.h | 6 ++++-- include/spdlog/details/async_log_helper.h | 6 ++++-- include/spdlog/details/file_helper.h | 6 ++++-- include/spdlog/details/log_msg.h | 6 ++++-- include/spdlog/details/mpmc_bounded_q.h | 6 ++++-- include/spdlog/details/null_mutex.h | 6 ++++-- include/spdlog/details/os.h | 8 ++++++-- include/spdlog/details/pattern_formatter_impl.h | 6 ++++-- include/spdlog/details/registry.h | 6 ++++-- include/spdlog/fmt/bundled/format.h | 12 ++++++++---- include/spdlog/sinks/android_sink.h | 6 ++++-- include/spdlog/sinks/ansicolor_sink.h | 6 ++++-- include/spdlog/sinks/base_sink.h | 6 ++++-- include/spdlog/sinks/dist_sink.h | 6 ++++-- include/spdlog/sinks/file_sinks.h | 6 ++++-- include/spdlog/sinks/msvc_sink.h | 6 ++++-- include/spdlog/sinks/null_sink.h | 6 ++++-- include/spdlog/sinks/ostream_sink.h | 6 ++++-- include/spdlog/sinks/sink.h | 6 ++++-- include/spdlog/sinks/stdout_sinks.h | 6 ++++-- include/spdlog/sinks/syslog_sink.h | 6 ++++-- include/spdlog/sinks/wincolor_sink.h | 6 ++++-- include/spdlog/sinks/windebug_sink.h | 6 ++++-- 23 files changed, 98 insertions(+), 48 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index dc5f3795..69f2f6ad 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -143,9 +143,11 @@ enum class pattern_time_type // // Log exception // -namespace details { namespace os { +namespace details { +namespace os { std::string errno_str(int err_num); -}} // namespace details::os +} +} // namespace details class spdlog_ex : public std::exception { public: diff --git a/include/spdlog/details/async_log_helper.h b/include/spdlog/details/async_log_helper.h index 78058975..569e8e48 100644 --- a/include/spdlog/details/async_log_helper.h +++ b/include/spdlog/details/async_log_helper.h @@ -28,7 +28,8 @@ #include #include -namespace spdlog { namespace details { +namespace spdlog { +namespace details { class async_log_helper { @@ -184,7 +185,8 @@ private: // wait until the queue is empty void wait_empty_q(); }; -}} // namespace spdlog::details +} // namespace details +} // namespace spdlog /////////////////////////////////////////////////////////////////////////////// // async_sink class implementation diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index 0d24a91b..dc0fa141 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -19,7 +19,8 @@ #include #include -namespace spdlog { namespace details { +namespace spdlog { +namespace details { class file_helper { @@ -136,4 +137,5 @@ private: FILE *_fd{nullptr}; filename_t _filename; }; -}} // namespace spdlog::details +} // namespace details +} // namespace spdlog diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index a1e8b2ee..9a03318d 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -11,7 +11,8 @@ #include #include -namespace spdlog { namespace details { +namespace spdlog { +namespace details { struct log_msg { log_msg() = default; @@ -40,4 +41,5 @@ struct log_msg fmt::MemoryWriter formatted; size_t msg_id{0}; }; -}} // namespace spdlog::details +} // namespace details +} // namespace spdlog diff --git a/include/spdlog/details/mpmc_bounded_q.h b/include/spdlog/details/mpmc_bounded_q.h index 29ec316b..13c7f605 100644 --- a/include/spdlog/details/mpmc_bounded_q.h +++ b/include/spdlog/details/mpmc_bounded_q.h @@ -48,7 +48,8 @@ Distributed under the MIT License (http://opensource.org/licenses/MIT) #include #include -namespace spdlog { namespace details { +namespace spdlog { +namespace details { template class mpmc_bounded_queue @@ -166,4 +167,5 @@ private: cacheline_pad_t pad3_; }; -}} // namespace spdlog::details +} // namespace details +} // namespace spdlog diff --git a/include/spdlog/details/null_mutex.h b/include/spdlog/details/null_mutex.h index 5f4ce46a..3f495bd9 100644 --- a/include/spdlog/details/null_mutex.h +++ b/include/spdlog/details/null_mutex.h @@ -8,7 +8,8 @@ #include // null, no cost dummy "mutex" and dummy "atomic" int -namespace spdlog { namespace details { +namespace spdlog { +namespace details { struct null_mutex { void lock() {} @@ -40,4 +41,5 @@ struct null_atomic_int } }; -}} // namespace spdlog::details +} // namespace details +} // namespace spdlog diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 271348da..c51eb6ce 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -53,7 +53,9 @@ #define __has_feature(x) 0 // Compatibility with non-clang compilers. #endif -namespace spdlog { namespace details { namespace os { +namespace spdlog { +namespace details { +namespace os { inline spdlog::log_clock::time_point now() { @@ -445,4 +447,6 @@ inline bool in_terminal(FILE *file) return isatty(fileno(file)) != 0; #endif } -}}} // namespace spdlog::details::os +} // namespace os +} // namespace details +} // namespace spdlog diff --git a/include/spdlog/details/pattern_formatter_impl.h b/include/spdlog/details/pattern_formatter_impl.h index 670538d5..c12c3d68 100644 --- a/include/spdlog/details/pattern_formatter_impl.h +++ b/include/spdlog/details/pattern_formatter_impl.h @@ -20,7 +20,8 @@ #include #include -namespace spdlog { namespace details { +namespace spdlog { +namespace details { class flag_formatter { public: @@ -466,7 +467,8 @@ class full_formatter SPDLOG_FINAL : public flag_formatter } }; -}} // namespace spdlog::details +} // namespace details +} // namespace spdlog /////////////////////////////////////////////////////////////////////////////// // pattern_formatter inline impl /////////////////////////////////////////////////////////////////////////////// diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index ac0a58a5..46397302 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -22,7 +22,8 @@ #include #include -namespace spdlog { namespace details { +namespace spdlog { +namespace details { template class registry_t { @@ -232,4 +233,5 @@ using registry = registry_t; using registry = registry_t; #endif -}} // namespace spdlog::details +} // namespace details +} // namespace spdlog diff --git a/include/spdlog/fmt/bundled/format.h b/include/spdlog/fmt/bundled/format.h index 9b2fe3b4..b4295cd7 100644 --- a/include/spdlog/fmt/bundled/format.h +++ b/include/spdlog/fmt/bundled/format.h @@ -345,7 +345,8 @@ typedef __int64 intmax_t; #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(_MANAGED) #include // _BitScanReverse, _BitScanReverse64 -namespace fmt { namespace internal { +namespace fmt { +namespace internal { // avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning #ifndef __clang__ #pragma intrinsic(_BitScanReverse) @@ -391,10 +392,12 @@ inline uint32_t clzll(uint64_t x) return 63 - r; } #define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) -}} // namespace fmt::internal +} // namespace internal +} // namespace fmt #endif -namespace fmt { namespace internal { +namespace fmt { +namespace internal { struct DummyInt { int data[2]; @@ -439,7 +442,8 @@ inline T const_check(T value) { return value; } -}} // namespace fmt::internal +} // namespace internal +} // namespace fmt namespace std { // Standard permits specialization of std::numeric_limits. This specialization diff --git a/include/spdlog/sinks/android_sink.h b/include/spdlog/sinks/android_sink.h index 1284441e..dd811633 100644 --- a/include/spdlog/sinks/android_sink.h +++ b/include/spdlog/sinks/android_sink.h @@ -20,7 +20,8 @@ #define SPDLOG_ANDROID_RETRIES 2 #endif -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { /* * Android sink (logging using __android_log_write) @@ -84,6 +85,7 @@ private: bool _use_raw_msg; }; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog #endif diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index 2a5203c3..9e7f1a59 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -12,7 +12,8 @@ #include #include -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { /** * This sink prefixes the output with an ANSI escape sequence color code depending on the severity @@ -133,4 +134,5 @@ public: using ansicolor_stderr_sink_mt = ansicolor_stderr_sink; using ansicolor_stderr_sink_st = ansicolor_stderr_sink; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog diff --git a/include/spdlog/sinks/base_sink.h b/include/spdlog/sinks/base_sink.h index 16035ec9..96cd001e 100644 --- a/include/spdlog/sinks/base_sink.h +++ b/include/spdlog/sinks/base_sink.h @@ -17,7 +17,8 @@ #include -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { template class base_sink : public sink { @@ -44,4 +45,5 @@ protected: virtual void _flush() = 0; Mutex _mutex; }; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog diff --git a/include/spdlog/sinks/dist_sink.h b/include/spdlog/sinks/dist_sink.h index 3191783a..1265cc7e 100644 --- a/include/spdlog/sinks/dist_sink.h +++ b/include/spdlog/sinks/dist_sink.h @@ -17,7 +17,8 @@ // Distribution sink (mux). Stores a vector of sinks which get called when log is called -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { template class dist_sink : public base_sink { @@ -66,4 +67,5 @@ public: using dist_sink_mt = dist_sink; using dist_sink_st = dist_sink; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog diff --git a/include/spdlog/sinks/file_sinks.h b/include/spdlog/sinks/file_sinks.h index 6f8517e8..7d755587 100644 --- a/include/spdlog/sinks/file_sinks.h +++ b/include/spdlog/sinks/file_sinks.h @@ -18,7 +18,8 @@ #include #include -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { /* * Trivial file sink with single file as target */ @@ -246,4 +247,5 @@ private: using daily_file_sink_mt = daily_file_sink; using daily_file_sink_st = daily_file_sink; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog diff --git a/include/spdlog/sinks/msvc_sink.h b/include/spdlog/sinks/msvc_sink.h index fa83a18c..09a5d671 100644 --- a/include/spdlog/sinks/msvc_sink.h +++ b/include/spdlog/sinks/msvc_sink.h @@ -15,7 +15,8 @@ #include #include -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { /* * MSVC sink (logging using OutputDebugStringA) */ @@ -37,6 +38,7 @@ protected: using msvc_sink_mt = msvc_sink; using msvc_sink_st = msvc_sink; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog #endif diff --git a/include/spdlog/sinks/null_sink.h b/include/spdlog/sinks/null_sink.h index c0ae4167..c254bc59 100644 --- a/include/spdlog/sinks/null_sink.h +++ b/include/spdlog/sinks/null_sink.h @@ -10,7 +10,8 @@ #include -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { template class null_sink : public base_sink @@ -24,4 +25,5 @@ protected: using null_sink_mt = null_sink; using null_sink_st = null_sink; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog diff --git a/include/spdlog/sinks/ostream_sink.h b/include/spdlog/sinks/ostream_sink.h index 7d91a1ee..97281384 100644 --- a/include/spdlog/sinks/ostream_sink.h +++ b/include/spdlog/sinks/ostream_sink.h @@ -11,7 +11,8 @@ #include #include -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { template class ostream_sink : public base_sink { @@ -44,4 +45,5 @@ protected: using ostream_sink_mt = ostream_sink; using ostream_sink_st = ostream_sink; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog diff --git a/include/spdlog/sinks/sink.h b/include/spdlog/sinks/sink.h index f3c146d9..b4e38068 100644 --- a/include/spdlog/sinks/sink.h +++ b/include/spdlog/sinks/sink.h @@ -7,7 +7,8 @@ #include "../details/log_msg.h" -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { class sink { public: @@ -39,4 +40,5 @@ inline level::level_enum sink::level() const return static_cast(_level.load(std::memory_order_relaxed)); } -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog diff --git a/include/spdlog/sinks/stdout_sinks.h b/include/spdlog/sinks/stdout_sinks.h index 35324370..b15d0803 100644 --- a/include/spdlog/sinks/stdout_sinks.h +++ b/include/spdlog/sinks/stdout_sinks.h @@ -12,7 +12,8 @@ #include #include -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { template class stdout_sink SPDLOG_FINAL : public base_sink @@ -74,4 +75,5 @@ protected: using stderr_sink_mt = stderr_sink; using stderr_sink_st = stderr_sink; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog diff --git a/include/spdlog/sinks/syslog_sink.h b/include/spdlog/sinks/syslog_sink.h index e4472f2f..17bbb1df 100644 --- a/include/spdlog/sinks/syslog_sink.h +++ b/include/spdlog/sinks/syslog_sink.h @@ -16,7 +16,8 @@ #include #include -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { /** * Sink that write to syslog using the `syscall()` library call. * @@ -69,6 +70,7 @@ private: return _priorities[static_cast(msg.level)]; } }; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog #endif diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index bc036d44..60f4286f 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -14,7 +14,8 @@ #include #include -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { /* * Windows color console sink. Uses WriteConsoleA to write to the console with colors */ @@ -119,4 +120,5 @@ public: using wincolor_stderr_sink_mt = wincolor_stderr_sink; using wincolor_stderr_sink_st = wincolor_stderr_sink; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog diff --git a/include/spdlog/sinks/windebug_sink.h b/include/spdlog/sinks/windebug_sink.h index 353a7bde..2c7f1bc2 100644 --- a/include/spdlog/sinks/windebug_sink.h +++ b/include/spdlog/sinks/windebug_sink.h @@ -9,7 +9,8 @@ #include "msvc_sink.h" -namespace spdlog { namespace sinks { +namespace spdlog { +namespace sinks { /* * Windows debug sink (logging using OutputDebugStringA, synonym for msvc_sink) @@ -20,6 +21,7 @@ using windebug_sink = msvc_sink; using windebug_sink_mt = msvc_sink_mt; using windebug_sink_st = msvc_sink_st; -}} // namespace spdlog::sinks +} // namespace sinks +} // namespace spdlog #endif From 5a0f90bc8255e38b6d63b4f3aa864c03d9c0aaa5 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 17 Mar 2018 12:49:31 +0200 Subject: [PATCH 27/62] clang format namespace fix --- format.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/format.sh b/format.sh index 51b987e4..7bb076d0 100755 --- a/format.sh +++ b/format.sh @@ -1,5 +1,5 @@ #!/bin/bash -echo -n "Running dos2unix " +echo -n "Running dos2unix " find . -name "*\.h" -o -name "*\.cpp"|xargs -I {} sh -c "dos2unix '{}' 2>/dev/null; echo -n '.'" echo echo -n "Running clang-format " From 7eb6ca63374123deae93bfcc814c9072d7f1f480 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 17 Mar 2018 12:49:45 +0200 Subject: [PATCH 28/62] formatting --- include/spdlog/logger.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index e05867ef..aa4a2c5d 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -84,7 +84,7 @@ public: template void critical(const wchar_t *fmt, const Args &... args); #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT - + template void log(level::level_enum lvl, const T &); From 200815892f7fa036b2ec77ba3545452ba24cf4b9 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 17 Mar 2018 13:42:09 +0200 Subject: [PATCH 29/62] Fix clang-tidy warnings about missing braces around if and for statements --- example/example.cpp | 4 +++ include/spdlog/details/async_log_helper.h | 14 ++++++++++ include/spdlog/details/async_logger_impl.h | 2 ++ include/spdlog/details/file_helper.h | 10 +++++++ include/spdlog/details/logger_impl.h | 12 +++++++++ include/spdlog/details/mpmc_bounded_q.h | 12 +++++++++ include/spdlog/details/os.h | 26 +++++++++++++++++++ .../spdlog/details/pattern_formatter_impl.h | 8 ++++++ include/spdlog/details/registry.h | 26 +++++++++++++++++++ include/spdlog/sinks/file_sinks.h | 4 +++ 10 files changed, 118 insertions(+) diff --git a/example/example.cpp b/example/example.cpp index 48c4b19e..b1b2e32f 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -47,7 +47,9 @@ int main(int, char *[]) // Create a file rotating logger with 5mb size max and 3 rotated files auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); for (int i = 0; i < 10; ++i) + { rotating_logger->info("{} * {} equals {:>10}", i, i, i * i); + } // Create a daily logger - a new file is created every day on 2:30am auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); @@ -106,7 +108,9 @@ void async_example() spdlog::set_async_mode(q_size); auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt"); for (int i = 0; i < 100; ++i) + { async_file->info("Async message #{}", i); + } } // syslog example (linux/osx/freebsd) diff --git a/include/spdlog/details/async_log_helper.h b/include/spdlog/details/async_log_helper.h index 569e8e48..a7780740 100644 --- a/include/spdlog/details/async_log_helper.h +++ b/include/spdlog/details/async_log_helper.h @@ -247,13 +247,17 @@ inline void spdlog::details::async_log_helper::flush(bool wait_for_q) { push_msg(async_msg(async_msg_type::flush)); if (wait_for_q) + { wait_empty_q(); // return when queue is empty + } } inline void spdlog::details::async_log_helper::worker_loop() { if (_worker_warmup_cb) + { _worker_warmup_cb(); + } auto last_pop = details::os::now(); auto last_flush = last_pop; auto active = true; @@ -273,7 +277,9 @@ inline void spdlog::details::async_log_helper::worker_loop() } } if (_worker_teardown_cb) + { _worker_teardown_cb(); + } } // process next message in the queue @@ -327,7 +333,9 @@ inline void spdlog::details::async_log_helper::handle_flush_interval(log_clock:: if (should_flush) { for (auto &s : _sinks) + { s->flush(); + } now = last_flush = details::os::now(); _flush_requested = false; } @@ -349,15 +357,21 @@ inline void spdlog::details::async_log_helper::sleep_or_yield( // spin upto 50 micros if (time_since_op <= microseconds(50)) + { return; + } // yield upto 150 micros if (time_since_op <= microseconds(100)) + { return std::this_thread::yield(); + } // sleep for 20 ms upto 200 ms if (time_since_op <= milliseconds(200)) + { return details::os::sleep_for_millis(20); + } // sleep for 500 ms return details::os::sleep_for_millis(500); diff --git a/include/spdlog/details/async_logger_impl.h b/include/spdlog/details/async_logger_impl.h index 36e2ec68..748a53ac 100644 --- a/include/spdlog/details/async_logger_impl.h +++ b/include/spdlog/details/async_logger_impl.h @@ -79,7 +79,9 @@ inline void spdlog::async_logger::_sink_it(details::log_msg &msg) #endif _async_log_helper->log(msg); if (_should_flush_on(msg)) + { _async_log_helper->flush(false); // do async flush + } } catch (const std::exception &ex) { diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index dc0fa141..d30a79b7 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -47,7 +47,9 @@ public: for (int tries = 0; tries < open_tries; ++tries) { if (!os::fopen_s(&_fd, fname, mode)) + { return; + } details::os::sleep_for_millis(open_interval); } @@ -58,7 +60,9 @@ public: void reopen(bool truncate) { if (_filename.empty()) + { throw spdlog_ex("Failed re opening file - was not opened before"); + } open(_filename, truncate); } @@ -81,7 +85,9 @@ public: size_t msg_size = msg.formatted.size(); auto data = msg.formatted.data(); if (std::fwrite(data, 1, msg_size, _fd) != msg_size) + { throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno); + } } size_t size() const @@ -122,12 +128,16 @@ public: // no valid extension found - return whole path and empty string as extension if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1) + { return std::make_tuple(fname, spdlog::filename_t()); + } // treat casese like "/etc/rc.d/somelogfile or "/abc/.hiddenfile" auto folder_index = fname.rfind(details::os::folder_sep); if (folder_index != fname.npos && folder_index >= ext_index - 1) + { return std::make_tuple(fname, spdlog::filename_t()); + } // finally - return a valid base and extension tuple return std::make_tuple(fname.substr(0, ext_index), fname.substr(ext_index)); diff --git a/include/spdlog/details/logger_impl.h b/include/spdlog/details/logger_impl.h index 38ff0b8f..d5487249 100644 --- a/include/spdlog/details/logger_impl.h +++ b/include/spdlog/details/logger_impl.h @@ -54,7 +54,9 @@ template inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) { if (!should_log(lvl)) + { return; + } try { @@ -82,7 +84,9 @@ template inline void spdlog::logger::log(level::level_enum lvl, const char *msg) { if (!should_log(lvl)) + { return; + } try { details::log_msg log_msg(&_name, lvl); @@ -104,7 +108,9 @@ template inline void spdlog::logger::log(level::level_enum lvl, const T &msg) { if (!should_log(lvl)) + { return; + } try { details::log_msg log_msg(&_name, lvl); @@ -309,7 +315,9 @@ inline void spdlog::logger::_sink_it(details::log_msg &msg) } if (_should_flush_on(msg)) + { flush(); + } } inline void spdlog::logger::_set_pattern(const std::string &pattern, pattern_time_type pattern_time) @@ -325,14 +333,18 @@ inline void spdlog::logger::_set_formatter(formatter_ptr msg_formatter) inline void spdlog::logger::flush() { for (auto &sink : _sinks) + { sink->flush(); + } } inline void spdlog::logger::_default_err_handler(const std::string &msg) { auto now = time(nullptr); if (now - _last_err_time < 60) + { return; + } auto tm_time = details::os::localtime(now); char date_buf[100]; std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", &tm_time); diff --git a/include/spdlog/details/mpmc_bounded_q.h b/include/spdlog/details/mpmc_bounded_q.h index 13c7f605..fd41e4c8 100644 --- a/include/spdlog/details/mpmc_bounded_q.h +++ b/include/spdlog/details/mpmc_bounded_q.h @@ -64,10 +64,14 @@ public: { // queue size must be power of two if (!((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0))) + { throw spdlog_ex("async logger queue size must be power of two"); + } for (size_t i = 0; i != buffer_size; i += 1) + { buffer_[i].sequence_.store(i, std::memory_order_relaxed); + } enqueue_pos_.store(0, std::memory_order_relaxed); dequeue_pos_.store(0, std::memory_order_relaxed); } @@ -92,7 +96,9 @@ public: if (dif == 0) { if (enqueue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed)) + { break; + } } else if (dif < 0) { @@ -120,12 +126,18 @@ public: if (dif == 0) { if (dequeue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed)) + { break; + } } else if (dif < 0) + { return false; + } else + { pos = dequeue_pos_.load(std::memory_order_relaxed); + } } data = std::move(cell->data_); cell->sequence_.store(pos + buffer_mask_ + 1, std::memory_order_release); diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index c51eb6ce..b87f00fd 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -148,7 +148,9 @@ inline void prevent_child_fd(FILE *f) #else auto fd = fileno(f); if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) + { throw spdlog_ex("fcntl with FD_CLOEXEC failed", errno); + } #endif } @@ -167,7 +169,9 @@ inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mod #ifdef SPDLOG_PREVENT_CHILD_FD if (*fp != nullptr) + { prevent_child_fd(*fp); + } #endif return *fp == nullptr; } @@ -210,18 +214,24 @@ inline bool file_exists(const filename_t &filename) inline size_t filesize(FILE *f) { if (f == nullptr) + { throw spdlog_ex("Failed getting file size. fd is null"); + } #if defined(_WIN32) && !defined(__CYGWIN__) int fd = _fileno(f); #if _WIN64 // 64 bits struct _stat64 st; if (_fstat64(fd, &st) == 0) + { return st.st_size; + } #else // windows 32 bits long ret = _filelength(fd); if (ret >= 0) + { return static_cast(ret); + } #endif #else // unix @@ -230,11 +240,15 @@ inline size_t filesize(FILE *f) #if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__) struct stat64 st; if (fstat64(fd, &st) == 0) + { return static_cast(st.st_size); + } #else // unix 32 bits or cygwin struct stat st; if (fstat(fd, &st) == 0) + { return static_cast(st.st_size); + } #endif #endif throw spdlog_ex("Failed getting file size from fd", errno); @@ -257,9 +271,13 @@ inline int utc_minutes_offset(const std::tm &tm = details::os::localtime()) int offset = -tzinfo.Bias; if (tm.tm_isdst) + { offset -= tzinfo.DaylightBias; + } else + { offset -= tzinfo.StandardBias; + } return offset; #else @@ -386,17 +404,25 @@ inline std::string errno_str(int err_num) #ifdef _WIN32 if (strerror_s(buf, buf_size, err_num) == 0) + { return std::string(buf); + } else + { return "Unknown error"; + } #elif defined(__FreeBSD__) || defined(__APPLE__) || defined(ANDROID) || defined(__SUNPRO_CC) || \ ((_POSIX_C_SOURCE >= 200112L) && !defined(_GNU_SOURCE)) // posix version if (strerror_r(err_num, buf, buf_size) == 0) + { return std::string(buf); + } else + { return "Unknown error"; + } #else // gnu version (might not use the given buf, so its retval pointer must be used) auto err = strerror_r(err_num, buf, buf_size); // let compiler choose type diff --git a/include/spdlog/details/pattern_formatter_impl.h b/include/spdlog/details/pattern_formatter_impl.h index c12c3d68..9aa634e7 100644 --- a/include/spdlog/details/pattern_formatter_impl.h +++ b/include/spdlog/details/pattern_formatter_impl.h @@ -488,16 +488,24 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string &patter if (*it == '%') { if (user_chars) // append user chars found so far + { _formatters.push_back(std::move(user_chars)); + } if (++it != end) + { handle_flag(*it); + } else + { break; + } } else // chars not following the % sign should be displayed as is { if (!user_chars) + { user_chars = std::unique_ptr(new details::aggregate_formatter()); + } user_chars->add_ch(*it); } } diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 46397302..339b025d 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -53,16 +53,24 @@ public: throw_if_exists(logger_name); std::shared_ptr new_logger; if (_async_mode) + { new_logger = std::make_shared(logger_name, sinks_begin, sinks_end, _async_q_size, _overflow_policy, _worker_warmup_cb, _flush_interval_ms, _worker_teardown_cb); + } else + { new_logger = std::make_shared(logger_name, sinks_begin, sinks_end); + } if (_formatter) + { new_logger->set_formatter(_formatter); + } if (_err_handler) + { new_logger->set_error_handler(_err_handler); + } new_logger->set_level(_level); new_logger->flush_on(_flush_level); @@ -84,10 +92,14 @@ public: logger_name, sinks_begin, sinks_end, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb); if (_formatter) + { new_logger->set_formatter(_formatter); + } if (_err_handler) + { new_logger->set_error_handler(_err_handler); + } new_logger->set_level(_level); new_logger->flush_on(_flush_level); @@ -101,7 +113,9 @@ public: { std::lock_guard lock(_mutex); for (auto &l : _loggers) + { fun(l.second); + } } void drop(const std::string &logger_name) @@ -146,7 +160,9 @@ public: std::lock_guard lock(_mutex); _formatter = f; for (auto &l : _loggers) + { l.second->set_formatter(_formatter); + } } void set_pattern(const std::string &pattern) @@ -154,14 +170,18 @@ public: std::lock_guard lock(_mutex); _formatter = std::make_shared(pattern); for (auto &l : _loggers) + { l.second->set_formatter(_formatter); + } } void set_level(level::level_enum log_level) { std::lock_guard lock(_mutex); for (auto &l : _loggers) + { l.second->set_level(log_level); + } _level = log_level; } @@ -169,14 +189,18 @@ public: { std::lock_guard lock(_mutex); for (auto &l : _loggers) + { l.second->flush_on(log_level); + } _flush_level = log_level; } void set_error_handler(log_err_handler handler) { for (auto &l : _loggers) + { l.second->set_error_handler(handler); + } _err_handler = handler; } @@ -210,7 +234,9 @@ private: void throw_if_exists(const std::string &logger_name) { if (_loggers.find(logger_name) != _loggers.end()) + { throw spdlog_ex("logger with name '" + logger_name + "' already exists"); + } } Mutex _mutex; diff --git a/include/spdlog/sinks/file_sinks.h b/include/spdlog/sinks/file_sinks.h index 7d755587..109c493a 100644 --- a/include/spdlog/sinks/file_sinks.h +++ b/include/spdlog/sinks/file_sinks.h @@ -43,7 +43,9 @@ protected: { _file_helper.write(msg); if (_force_flush) + { _file_helper.flush(); + } } void _flush() override @@ -199,7 +201,9 @@ public: , _rotation_m(rotation_minute) { if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59) + { throw spdlog_ex("daily_file_sink: Invalid rotation time in ctor"); + } _rotation_tp = _next_rotation_tp(); _file_helper.open(FileNameCalc::calc_filename(_base_filename)); } From 18c99682a816ccb98898efc035774a1ac8ff5bda Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 17 Mar 2018 14:08:10 +0200 Subject: [PATCH 30/62] fixed clang warning about uninitialized values --- include/spdlog/details/os.h | 8 ++++++-- include/spdlog/details/registry.h | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index b87f00fd..e6b5cd2a 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -238,13 +238,17 @@ inline size_t filesize(FILE *f) int fd = fileno(f); // 64 bits(but not in osx or cygwin, where fstat64 is deprecated) #if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__) - struct stat64 st; + struct stat64 st + { + }; if (fstat64(fd, &st) == 0) { return static_cast(st.st_size); } #else // unix 32 bits or cygwin - struct stat st; + struct stat st + { + }; if (fstat(fd, &st) == 0) { return static_cast(st.st_size); diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 339b025d..614220d5 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -249,7 +249,7 @@ private: size_t _async_q_size = 0; async_overflow_policy _overflow_policy = async_overflow_policy::block_retry; std::function _worker_warmup_cb; - std::chrono::milliseconds _flush_interval_ms; + std::chrono::milliseconds _flush_interval_ms{std::chrono::milliseconds::zero()}; std::function _worker_teardown_cb; }; From c83dd5d60ef28fba30ca5abd9ae217a65b8d2300 Mon Sep 17 00:00:00 2001 From: Alexander Kiselev Date: Mon, 19 Mar 2018 19:17:26 +0300 Subject: [PATCH 31/62] Added: g3log, log4cplus, log4cpp, p7. Changes: boost, easylogging, g2log, glog, spdlog. --- bench/easyl-mt.conf | 10 ++++ bench/g3log-async.cpp | 62 +++++++++++++++++++++++ bench/log4cplus-bench-mt.cpp | 80 +++++++++++++++++++++++++++++ bench/log4cplus-bench.cpp | 54 ++++++++++++++++++++ bench/log4cpp-bench-mt.cpp | 74 +++++++++++++++++++++++++++ bench/log4cpp-bench.cpp | 48 ++++++++++++++++++ bench/p7-bench-mt.cpp | 97 ++++++++++++++++++++++++++++++++++++ bench/p7-bench.cpp | 70 ++++++++++++++++++++++++++ 8 files changed, 495 insertions(+) create mode 100644 bench/easyl-mt.conf create mode 100644 bench/g3log-async.cpp create mode 100644 bench/log4cplus-bench-mt.cpp create mode 100644 bench/log4cplus-bench.cpp create mode 100644 bench/log4cpp-bench-mt.cpp create mode 100644 bench/log4cpp-bench.cpp create mode 100644 bench/p7-bench-mt.cpp create mode 100644 bench/p7-bench.cpp diff --git a/bench/easyl-mt.conf b/bench/easyl-mt.conf new file mode 100644 index 00000000..8895b281 --- /dev/null +++ b/bench/easyl-mt.conf @@ -0,0 +1,10 @@ +* GLOBAL: + FORMAT = "[%datetime]: %msg" + FILENAME = ./logs/easylogging-mt.log + ENABLED = true + TO_FILE = true + TO_STANDARD_OUTPUT = false + MILLISECONDS_WIDTH = 3 + PERFORMANCE_TRACKING = false + MAX_LOG_FILE_SIZE = 10485760 + Log_Flush_Threshold = 10485760 diff --git a/bench/g3log-async.cpp b/bench/g3log-async.cpp new file mode 100644 index 00000000..b5e15a2b --- /dev/null +++ b/bench/g3log-async.cpp @@ -0,0 +1,62 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include +#include +#include +#include +#include + +#include "g3log/g3log.hpp" +#include "g3log/logworker.hpp" + +using namespace std; +template std::string format(const T &value); + +int main(int argc, char *argv[]) +{ + using namespace std::chrono; + using clock = steady_clock; + int thread_count = 10; + + if (argc > 1) + thread_count = atoi(argv[1]); + + int howmany = 1000000; + + auto worker = g3::LogWorker::createLogWorker(); + auto handle= worker->addDefaultLogger(argv[0], "logs"); + g3::initializeLogging(worker.get()); + + std::atomic msg_counter{0}; + vector threads; + auto start = clock::now(); + for (int t = 0; t < thread_count; ++t) + { + threads.push_back(std::thread([&]() { + while (true) + { + int counter = ++msg_counter; + if (counter > howmany) + break; + LOG(INFO) << "g3log message #" << counter << ": This is some text for your pleasure"; + } + })); + } + + for (auto &t : threads) + { + t.join(); + } + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + cout << "Total: " << howmany << std::endl; + cout << "Threads: " << thread_count << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; +} diff --git a/bench/log4cplus-bench-mt.cpp b/bench/log4cplus-bench-mt.cpp new file mode 100644 index 00000000..6acbf3fa --- /dev/null +++ b/bench/log4cplus-bench-mt.cpp @@ -0,0 +1,80 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include +#include +#include +#include +#include +#include + +#include "log4cplus/logger.h" +#include "log4cplus/fileappender.h" +#include "log4cplus/layout.h" +#include "log4cplus/ndc.h" +#include "log4cplus/helpers/loglog.h" +#include "log4cplus/helpers/property.h" +#include "log4cplus/loggingmacros.h" + +using namespace log4cplus; + +int main(int argc, char * argv[]) +{ + using namespace std::chrono; + using clock = steady_clock; + + int thread_count = 10; + if (argc > 1) + thread_count = std::atoi(argv[1]); + + int howmany = 1000000; + + log4cplus::initialize(); + SharedFileAppenderPtr append( + new FileAppender(LOG4CPLUS_TEXT("logs/log4cplus-bench-mt.log"), std::ios_base::trunc, + true, true)); + append->setName(LOG4CPLUS_TEXT("File")); + + log4cplus::tstring pattern = LOG4CPLUS_TEXT("%d{%Y-%m-%d %H:%M:%S.%Q}: %p - %m %n"); + append->setLayout( std::auto_ptr(new PatternLayout(pattern)) ); + append->getloc(); + Logger::getRoot().addAppender(SharedAppenderPtr(append.get())); + + Logger root = Logger::getRoot(); + + std::atomic msg_counter{0}; + std::vector threads; + + auto start = clock::now(); + for (int t = 0; t < thread_count; ++t) + { + threads.push_back(std::thread([&]() { + while (true) + { + int counter = ++msg_counter; + if (counter > howmany) + break; + LOG4CPLUS_INFO(root, "log4cplus message #" << counter << ": This is some text for your pleasure"); + } + })); + } + + for (auto &t : threads) + { + t.join(); + } + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Threads: " << thread_count << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + + log4cplus::Logger::shutdown(); + return 0; +} diff --git a/bench/log4cplus-bench.cpp b/bench/log4cplus-bench.cpp new file mode 100644 index 00000000..e522e85a --- /dev/null +++ b/bench/log4cplus-bench.cpp @@ -0,0 +1,54 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include +#include +#include + +#include "log4cplus/logger.h" +#include "log4cplus/fileappender.h" +#include "log4cplus/layout.h" +#include "log4cplus/ndc.h" +#include "log4cplus/helpers/loglog.h" +#include "log4cplus/helpers/property.h" +#include "log4cplus/loggingmacros.h" + +using namespace log4cplus; + +int main(int, char *[]) +{ + using namespace std::chrono; + using clock = steady_clock; + + int howmany = 1000000; + + log4cplus::initialize(); + SharedFileAppenderPtr append( + new FileAppender(LOG4CPLUS_TEXT("logs/log4cplus-bench.log"), std::ios_base::trunc, + true, true)); + append->setName(LOG4CPLUS_TEXT("File")); + + log4cplus::tstring pattern = LOG4CPLUS_TEXT("%d{%Y-%m-%d %H:%M:%S.%Q}: %p - %m %n"); + append->setLayout( std::auto_ptr(new PatternLayout(pattern)) ); + append->getloc(); + Logger::getRoot().addAppender(SharedAppenderPtr(append.get())); + + Logger root = Logger::getRoot(); + + auto start = clock::now(); + for (int i = 0; i < howmany; ++i) + LOG4CPLUS_INFO(root, "log4cplus message #" << i << ": This is some text for your pleasure"); + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + + log4cplus::Logger::shutdown(); + return 0; +} diff --git a/bench/log4cpp-bench-mt.cpp b/bench/log4cpp-bench-mt.cpp new file mode 100644 index 00000000..82f3a40f --- /dev/null +++ b/bench/log4cpp-bench-mt.cpp @@ -0,0 +1,74 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include +#include +#include +#include +#include +#include + +#include "log4cpp/Category.hh" +#include "log4cpp/Appender.hh" +#include "log4cpp/FileAppender.hh" +#include "log4cpp/Layout.hh" +#include "log4cpp/BasicLayout.hh" +#include "log4cpp/Priority.hh" +#include "log4cpp/PatternLayout.hh" + +int main(int argc, char * argv[]) +{ + using namespace std::chrono; + using clock = steady_clock; + + int thread_count = 10; + if (argc > 1) + thread_count = std::atoi(argv[1]); + + int howmany = 1000000; + + log4cpp::Appender *appender = new log4cpp::FileAppender("default", "logs/log4cpp-bench-mt.log"); + log4cpp::PatternLayout *layout = new log4cpp::PatternLayout(); + layout->setConversionPattern("{%Y-%m-%d %H:%M:%S.%l}: %p - %m %n"); + appender->setLayout(layout); + + log4cpp::Category& root = log4cpp::Category::getRoot(); + root.addAppender(appender); + root.setPriority(log4cpp::Priority::INFO); + + std::atomic msg_counter{0}; + std::vector threads; + + auto start = clock::now(); + for (int t = 0; t < thread_count; ++t) + { + threads.push_back(std::thread([&]() { + while (true) + { + int counter = ++msg_counter; + if (counter > howmany) + break; + root << log4cpp::Priority::INFO << "log4cpp message #" << counter << ": This is some text for your pleasure"; + } + })); + } + + for (auto &t : threads) + { + t.join(); + } + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Threads: " << thread_count << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + + root.shutdown(); + return 0; +} diff --git a/bench/log4cpp-bench.cpp b/bench/log4cpp-bench.cpp new file mode 100644 index 00000000..a21526c8 --- /dev/null +++ b/bench/log4cpp-bench.cpp @@ -0,0 +1,48 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include +#include +#include + +#include "log4cpp/Category.hh" +#include "log4cpp/Appender.hh" +#include "log4cpp/FileAppender.hh" +#include "log4cpp/Layout.hh" +#include "log4cpp/BasicLayout.hh" +#include "log4cpp/Priority.hh" +#include "log4cpp/PatternLayout.hh" + +int main(int, char *[]) +{ + using namespace std::chrono; + using clock = steady_clock; + + int howmany = 1000000; + + log4cpp::Appender *appender = new log4cpp::FileAppender("default", "logs/log4cpp-bench.log"); + log4cpp::PatternLayout *layout = new log4cpp::PatternLayout(); + layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S.%l}: %p - %m %n"); + appender->setLayout(layout); + + log4cpp::Category& root = log4cpp::Category::getRoot(); + root.addAppender(appender); + root.setPriority(log4cpp::Priority::INFO); + + auto start = clock::now(); + for (int i = 0; i < howmany; ++i) + root << log4cpp::Priority::INFO << "log4cpp message #" << i << ": This is some text for your pleasure"; + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + + root.shutdown(); + return 0; +} diff --git a/bench/p7-bench-mt.cpp b/bench/p7-bench-mt.cpp new file mode 100644 index 00000000..a3195208 --- /dev/null +++ b/bench/p7-bench-mt.cpp @@ -0,0 +1,97 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include +#include +#include +#include +#include +#include +#include + +#include "P7_Trace.h" + + +int main(int argc, char *argv[]) +{ + using namespace std::chrono; + using clock = steady_clock; + + int thread_count = 10; + if (argc > 1) + thread_count = std::atoi(argv[1]); + + int howmany = 1000000; + + IP7_Trace::hModule module = NULL; + + //create P7 client object + std::unique_ptr> client( + P7_Create_Client(TM("/P7.Pool=1024 /P7.Sink=FileTxt /P7.Dir=logs/p7-bench-mt")), + [&](IP7_Client *ptr){ + if (ptr) + ptr->Release(); + }); + + if (!client) + { + std::cout << "Can't create IP7_Client" << std::endl; + return 1; + } + + //create P7 trace object 1 + std::unique_ptr> trace( + P7_Create_Trace(client.get(), TM("Trace channel 1")), + [&](IP7_Trace *ptr){ + if (ptr) + ptr->Release(); + }); + + if (!trace) + { + std::cout << "Can't create IP7_Trace" << std::endl; + return 1; + } + + trace->Register_Thread(TM("Application"), 0); + trace->Register_Module(TM("Main"), &module); + + std::atomic msg_counter{0}; + std::vector threads; + + auto start = clock::now(); + for (int t = 0; t < thread_count; ++t) + { + threads.push_back(std::thread([&]() { + trace->Register_Thread(TM("Application"), t+1); + while (true) + { + int counter = ++msg_counter; + if (counter > howmany) + break; + trace->P7_INFO(module, TM("p7 message #%d: This is some text for your pleasure"), counter); + } + trace->Register_Thread(TM("Application"), t+1); + })); + } + + for (auto &t : threads) + { + t.join(); + } + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Threads: " << thread_count << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + + trace->Unregister_Thread(0); + + return 0; +} diff --git a/bench/p7-bench.cpp b/bench/p7-bench.cpp new file mode 100644 index 00000000..15513ca5 --- /dev/null +++ b/bench/p7-bench.cpp @@ -0,0 +1,70 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include +#include +#include +#include + +#include "P7_Trace.h" + + +int main(int, char *[]) +{ + using namespace std::chrono; + using clock = steady_clock; + + int howmany = 1000000; + + IP7_Trace::hModule module = NULL; + + //create P7 client object + std::unique_ptr> client( + P7_Create_Client(TM("/P7.Pool=1024 /P7.Sink=FileTxt /P7.Dir=logs/p7-bench")), + [&](IP7_Client *ptr){ + if (ptr) + ptr->Release(); + }); + + if (!client) + { + std::cout << "Can't create IP7_Client" << std::endl; + return 1; + } + + //create P7 trace object 1 + std::unique_ptr> trace( + P7_Create_Trace(client.get(), TM("Trace channel 1")), + [&](IP7_Trace *ptr){ + if (ptr) + ptr->Release(); + }); + + if (!trace) + { + std::cout << "Can't create IP7_Trace" << std::endl; + return 1; + } + + trace->Register_Thread(TM("Application"), 0); + trace->Register_Module(TM("Main"), &module); + + auto start = clock::now(); + for (int i = 0; i < howmany; ++i) + trace->P7_INFO(module, TM("p7 message #%d: This is some text for your pleasure"), i); + + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + + trace->Unregister_Thread(0); + + return 0; +} From 70ad1aa40942f5fe6cfb8a49643dba13528ab2b9 Mon Sep 17 00:00:00 2001 From: Alexander Kiselev Date: Mon, 19 Mar 2018 19:22:02 +0300 Subject: [PATCH 32/62] Changes: boost, easylogging, g2log, glog, spdlog. --- .gitignore | 1 + bench/Makefile | 51 ++++++++++++++++++++++++--------- bench/boost-bench-mt.cpp | 20 +++++++++++-- bench/boost-bench.cpp | 21 ++++++++++++-- bench/easylogging-bench-mt.cpp | 23 ++++++++++++--- bench/easylogging-bench.cpp | 22 ++++++++++++-- bench/g2log-async.cpp | 2 +- bench/glog-bench-mt.cpp | 16 ++++++++++- bench/glog-bench.cpp | 18 +++++++++++- bench/mem | 19 ++++++++++++ bench/p7-bench | Bin 0 -> 14704 bytes bench/spdlog-async.cpp | 12 ++++---- bench/spdlog-bench-mt.cpp | 26 ++++++++++++----- bench/spdlog-bench.cpp | 23 ++++++++++++--- bench/spdlog-null-async.cpp | 2 +- 15 files changed, 211 insertions(+), 45 deletions(-) create mode 100755 bench/mem create mode 100755 bench/p7-bench diff --git a/.gitignore b/.gitignore index 2f3cb33d..b1a41919 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ # Auto generated files +build/* *.slo *.lo *.o diff --git a/bench/Makefile b/bench/Makefile index 418a5285..c619a5ae 100644 --- a/bench/Makefile +++ b/bench/Makefile @@ -3,7 +3,15 @@ CXXFLAGS = -march=native -Wall -Wextra -pedantic -std=c++11 -pthread -I../includ CXX_RELEASE_FLAGS = -O3 -flto -DNDEBUG -binaries=spdlog-bench spdlog-bench-mt spdlog-async spdlog-null-async boost-bench boost-bench-mt glog-bench glog-bench-mt g2log-async easylogging-bench easylogging-bench-mt +# g2log-async +binaries=spdlog-bench spdlog-bench-mt spdlog-async spdlog-null-async \ + boost-bench boost-bench-mt \ + glog-bench glog-bench-mt \ + g3log-async \ + p7-bench p7-bench-mt \ + log4cpp-bench log4cpp-bench-mt \ + log4cplus-bench log4cplus-bench-mt \ + easylogging-bench easylogging-bench-mt all: $(binaries) @@ -16,13 +24,10 @@ spdlog-bench-mt: spdlog-bench-mt.cpp spdlog-async: spdlog-async.cpp $(CXX) spdlog-async.cpp -o spdlog-async $(CXXFLAGS) $(CXX_RELEASE_FLAGS) - spdlog-null-async: spdlog-null-async.cpp $(CXX) spdlog-null-async.cpp -o spdlog-null-async $(CXXFLAGS) $(CXX_RELEASE_FLAGS) - - -BOOST_FLAGS = -DBOOST_LOG_DYN_LINK -I/usr/include -lboost_log -lboost_log_setup -lboost_filesystem -lboost_system -lboost_thread -lboost_regex -lboost_date_time -lboost_chrono +BOOST_FLAGS = -DBOOST_LOG_DYN_LINK -I$(HOME)/include -I/usr/include -L$(HOME)/lib -lboost_log_setup -lboost_log -lboost_filesystem -lboost_system -lboost_thread -lboost_regex -lboost_date_time -lboost_chrono boost-bench: boost-bench.cpp $(CXX) boost-bench.cpp -o boost-bench $(CXXFLAGS) $(BOOST_FLAGS) $(CXX_RELEASE_FLAGS) @@ -30,21 +35,43 @@ boost-bench: boost-bench.cpp boost-bench-mt: boost-bench-mt.cpp $(CXX) boost-bench-mt.cpp -o boost-bench-mt $(CXXFLAGS) $(BOOST_FLAGS) $(CXX_RELEASE_FLAGS) - -GLOG_FLAGS = -lglog +GLOG_FLAGS = -I$(HOME)/include -L$(HOME)/lib -lglog glog-bench: glog-bench.cpp $(CXX) glog-bench.cpp -o glog-bench $(CXXFLAGS) $(GLOG_FLAGS) $(CXX_RELEASE_FLAGS) glog-bench-mt: glog-bench-mt.cpp $(CXX) glog-bench-mt.cpp -o glog-bench-mt $(CXXFLAGS) $(GLOG_FLAGS) $(CXX_RELEASE_FLAGS) - -G2LOG_FLAGS = -I/home/gabi/devel/g2log/g2log/src -L/home/gabi/devel/g2log/g2log -llib_g2logger +G2LOG_FLAGS = -I$(HOME)/include -L$(HOME)/lib -llib_g2logger g2log-async: g2log-async.cpp $(CXX) g2log-async.cpp -o g2log-async $(CXXFLAGS) $(G2LOG_FLAGS) $(CXX_RELEASE_FLAGS) +G3LOG_FLAGS = -I$(HOME)/include -L$(HOME)/lib -lg3logger +g3log-async: g3log-async.cpp + $(CXX) g3log-async.cpp -o g3log-async $(CXXFLAGS) $(G3LOG_FLAGS) $(CXX_RELEASE_FLAGS) + +P7_FLAGS = -I$(HOME)/P7/Headers -I$(HOME)/include -L$(HOME)/lib -lP7 +p7-bench: p7-bench.cpp + $(CXX) p7-bench.cpp -o p7-bench $(CXXFLAGS) $(P7_FLAGS) $(CXX_RELEASE_FLAGS) + +p7-bench-mt: p7-bench-mt.cpp + $(CXX) p7-bench-mt.cpp -o p7-bench-mt $(CXXFLAGS) $(P7_FLAGS) $(CXX_RELEASE_FLAGS) + +LOG4CPP_FLAGS = -I$(HOME)/include -L$(HOME)/lib -llog4cpp +log4cpp-bench: log4cpp-bench.cpp + $(CXX) log4cpp-bench.cpp -o log4cpp-bench $(CXXFLAGS) $(LOG4CPP_FLAGS) $(CXX_RELEASE_FLAGS) -EASYL_FLAGS = -I../../easylogging/src/ +log4cpp-bench-mt: log4cpp-bench-mt.cpp + $(CXX) log4cpp-bench-mt.cpp -o log4cpp-bench-mt $(CXXFLAGS) $(LOG4CPP_FLAGS) $(CXX_RELEASE_FLAGS) + +LOG4CPLUS_FLAGS = -I$(HOME)/include -L$(HOME)/lib -llog4cplus +log4cplus-bench: log4cplus-bench.cpp + $(CXX) log4cplus-bench.cpp -o log4cplus-bench $(CXXFLAGS) $(LOG4CPLUS_FLAGS) $(CXX_RELEASE_FLAGS) + +log4cplus-bench-mt: log4cplus-bench-mt.cpp + $(CXX) log4cplus-bench-mt.cpp -o log4cplus-bench-mt $(CXXFLAGS) $(LOG4CPLUS_FLAGS) $(CXX_RELEASE_FLAGS) + +EASYL_FLAGS = -I$(HOME)/easyloggingpp/src easylogging-bench: easylogging-bench.cpp $(CXX) easylogging-bench.cpp -o easylogging-bench $(CXXFLAGS) $(EASYL_FLAGS) $(CXX_RELEASE_FLAGS) easylogging-bench-mt: easylogging-bench-mt.cpp @@ -55,8 +82,4 @@ easylogging-bench-mt: easylogging-bench-mt.cpp clean: rm -f *.o logs/* $(binaries) - rebuild: clean all - - - diff --git a/bench/boost-bench-mt.cpp b/bench/boost-bench-mt.cpp index 73219b91..3a6eeea8 100644 --- a/bench/boost-bench-mt.cpp +++ b/bench/boost-bench-mt.cpp @@ -4,6 +4,8 @@ // #include +#include +#include #include #include @@ -23,7 +25,7 @@ namespace keywords = boost::log::keywords; void init() { - logging::add_file_log(keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/ + logging::add_file_log(keywords::file_name = "logs/boost-bench-mt_%N.log", /*< file name pattern >*/ keywords::auto_flush = false, keywords::format = "[%TimeStamp%]: %Message%"); logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info); @@ -33,6 +35,9 @@ using namespace std; int main(int argc, char *argv[]) { + using namespace std::chrono; + using clock = steady_clock; + int thread_count = 10; if (argc > 1) thread_count = atoi(argv[1]); @@ -49,6 +54,7 @@ int main(int argc, char *argv[]) std::atomic msg_counter{0}; vector threads; + auto start = clock::now(); for (int t = 0; t < thread_count; ++t) { threads.push_back(std::thread([&]() { @@ -65,7 +71,17 @@ int main(int argc, char *argv[]) for (auto &t : threads) { t.join(); - }; + } + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Threads: " << thread_count << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + return 0; } diff --git a/bench/boost-bench.cpp b/bench/boost-bench.cpp index cb432578..334fcb93 100644 --- a/bench/boost-bench.cpp +++ b/bench/boost-bench.cpp @@ -2,6 +2,10 @@ // Copyright(c) 2015 Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) // + +#include +#include + #include #include #include @@ -18,22 +22,35 @@ namespace keywords = boost::log::keywords; void init() { - logging::add_file_log(keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/ + logging::add_file_log(keywords::file_name = "logs/boost-bench_%N.log", /*< file name pattern >*/ keywords::auto_flush = false, keywords::format = "[%TimeStamp%]: %Message%"); logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info); } -int main(int argc, char *[]) +int main(int, char *[]) { + using namespace std::chrono; + using clock = steady_clock; + int howmany = 1000000; init(); logging::add_common_attributes(); using namespace logging::trivial; src::severity_logger_mt lg; + + auto start = clock::now(); for (int i = 0; i < howmany; ++i) BOOST_LOG_SEV(lg, info) << "boost message #" << i << ": This is some text for your pleasure"; + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + return 0; } diff --git a/bench/easylogging-bench-mt.cpp b/bench/easylogging-bench-mt.cpp index 00f507c6..cfcf3348 100644 --- a/bench/easylogging-bench-mt.cpp +++ b/bench/easylogging-bench-mt.cpp @@ -4,17 +4,22 @@ // #include +#include +#include #include #include -#define _ELPP_THREAD_SAFE +#define ELPP_THREAD_SAFE #include "easylogging++.h" -_INITIALIZE_EASYLOGGINGPP +#include "easylogging++.cc" +INITIALIZE_EASYLOGGINGPP using namespace std; int main(int argc, char *argv[]) { + using namespace std::chrono; + using clock = steady_clock; int thread_count = 10; if (argc > 1) @@ -23,12 +28,13 @@ int main(int argc, char *argv[]) int howmany = 1000000; // Load configuration from file - el::Configurations conf("easyl.conf"); + el::Configurations conf("easyl-mt.conf"); el::Loggers::reconfigureLogger("default", conf); std::atomic msg_counter{0}; vector threads; + auto start = clock::now(); for (int t = 0; t < thread_count; ++t) { threads.push_back(std::thread([&]() { @@ -45,7 +51,16 @@ int main(int argc, char *argv[]) for (auto &t : threads) { t.join(); - }; + } + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Threads: " << thread_count << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; return 0; } diff --git a/bench/easylogging-bench.cpp b/bench/easylogging-bench.cpp index 5306435f..06b66134 100644 --- a/bench/easylogging-bench.cpp +++ b/bench/easylogging-bench.cpp @@ -3,19 +3,37 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#include "easylogging++.h" +#include +#include -_INITIALIZE_EASYLOGGINGPP +#include "easylogging++.h" +#include "easylogging++.cc" +INITIALIZE_EASYLOGGINGPP int main(int, char *[]) { + using namespace std::chrono; + using clock = steady_clock; + int howmany = 1000000; // Load configuration from file el::Configurations conf("easyl.conf"); el::Loggers::reconfigureLogger("default", conf); + el::Logger* defaultLogger = el::Loggers::getLogger("default"); + + auto start = clock::now(); for (int i = 0; i < howmany; ++i) LOG(INFO) << "easylog message #" << i << ": This is some text for your pleasure"; + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + return 0; } diff --git a/bench/g2log-async.cpp b/bench/g2log-async.cpp index 97cac5dc..ad21a0e5 100644 --- a/bench/g2log-async.cpp +++ b/bench/g2log-async.cpp @@ -47,7 +47,7 @@ int main(int argc, char *argv[]) for (auto &t : threads) { t.join(); - }; + } duration delta = clock::now() - start; float deltaf = delta.count(); diff --git a/bench/glog-bench-mt.cpp b/bench/glog-bench-mt.cpp index 5e43de78..2f0aef19 100644 --- a/bench/glog-bench-mt.cpp +++ b/bench/glog-bench-mt.cpp @@ -4,6 +4,8 @@ // #include +#include +#include #include #include @@ -13,6 +15,8 @@ using namespace std; int main(int argc, char *argv[]) { + using namespace std::chrono; + using clock = steady_clock; int thread_count = 10; if (argc > 1) @@ -27,6 +31,7 @@ int main(int argc, char *argv[]) std::atomic msg_counter{0}; vector threads; + auto start = clock::now(); for (int t = 0; t < thread_count; ++t) { threads.push_back(std::thread([&]() { @@ -43,7 +48,16 @@ int main(int argc, char *argv[]) for (auto &t : threads) { t.join(); - }; + } + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Threads: " << thread_count << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; return 0; } diff --git a/bench/glog-bench.cpp b/bench/glog-bench.cpp index 2a8db891..6b4445a9 100644 --- a/bench/glog-bench.cpp +++ b/bench/glog-bench.cpp @@ -3,17 +3,33 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // +#include +#include + #include "glog/logging.h" + int main(int, char *argv[]) { + using namespace std::chrono; + using clock = steady_clock; + int howmany = 1000000; FLAGS_logtostderr = 0; FLAGS_log_dir = "logs"; google::InitGoogleLogging(argv[0]); + auto start = clock::now(); for (int i = 0; i < howmany; ++i) - LOG(INFO) << "glog message # " << i << ": This is some text for your pleasure"; + LOG(INFO) << "glog message #" << i << ": This is some text for your pleasure"; + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; return 0; } diff --git a/bench/mem b/bench/mem new file mode 100755 index 00000000..c49744e7 --- /dev/null +++ b/bench/mem @@ -0,0 +1,19 @@ +#!/bin/sh + +if [ $# -lt 1 ]; then + echo "usage: $0 " +fi + +PROG=$1 + +if [ ! -x "$PROG" ]; then + echo $PROG not found or not executable. + exit 1 +fi + +$* & +PID=$! + +while `kill -0 $PID 2>/dev/null`; do + ps -eo size,pid,user,pcpu,command --sort -size | awk '{ line=1 ; hr=$1/1024 ; printf("%13.2f Mb ",hr); } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' | grep -v grep | grep -v $0 | grep $PROG +done diff --git a/bench/p7-bench b/bench/p7-bench new file mode 100755 index 0000000000000000000000000000000000000000..566ec56b04ab3c6f4147b140ac46c0785d7607de GIT binary patch literal 14704 zcmeHOdvIG-dOwol*m=oz9^g&r=4O{i0uy05PU66%NVer%1t%Ckf(azoiloFMvZR%+ z5<62$z)3b*W7eh1lI?6~J)JGf>>q8q(=q|JiKz*u)5jPXwzO<_Q+A;;PcxLP6Bg9p zckVgz)wNWZ9om1IlU#l0`_q!q%919Tpq2Dd_?J1xt6$qh+3dMuMf2nw+H!1Wcg`T8}D8Hn#eq@H8PLbYe z_kbhbLxeT+-&rcNZF^G>QT*gGL*V2x506M1HDD&G)VmXURL(CNs)S&>$gfnpJSoaA zsqBZFqmg}^>TiyQ)<+|;bpQJPhE3}?)w@!0R~@f6*(cd;JG*#JvK&kv|YSn#XM;_{+G--qCb@I7d+nO@Z0>Y?iR^Vy$z54Ep4=#N9 z*CL#`S(i5 zA1Q%vFJb4w67s7`$p38#`H2$p50$_dmB25Qz4BuKX-td6B0AIdgOF584+U?! zi6l1>+n0|W2nMwjac;sBdT%lu2oYaPe9(~7G>Qw`eSt`fX}d$wwnHGX!+i`{_xEdw za55E-1)>psKs!{6qz=7qqo%=P{IIq!5YqOiV?jNFG6nJH06cSV6dOynB znrp`vY1)5BH;DZJV_wlvEFEP0>g=W(GQwfneCMzA1>zWAP2zt~z&JN=MBG zv|uzIJh&kiKg_f0(CdToG#Uz}ji&q^y4xM>4J0)^8Hng9f6(V^2ettvj0ClKN=Kf3 z{$Qu(>)5EZ-5%uG#G@%+gj=W&$3jtm@QYdL)H-WnXA}AgEfL?M?LeQU!b#m9qFm#h zNa%_kj>JM*dpMQuqdIl&+Uc&<&=CEBeUU?M_h!VSfmBM<2NGeZ?~nVK77hjU06JwK za6TLW#X@XbQH=4193_r-UCYWsDh{M`hi6xzaH-q1xnuwD$~;| zBMaz@yD^_$#%>VlB%gU;9a74f7r&$vnRy(s`RoqCzw(y{@wuMI_6lBK_b5J*4i*u7 zh|Akq8a##R)jgcjobTi@<7dW%SDJ7+f6$ts+JwvbfN-%S;HfoY9x4YXUVV-$CR`MS z<7-VgwVw>NCR~1lDXqbTo7X8G6K?)at0tVvBtx4Cmum`2>o(!&n0)9l;S2L9W4$K) zY7?F?;TQn<&~L(NPM6`R311>X(32*-#)PYb?^dWoWsj{;n0kCnx929+!RIT+S#IN_ zfO6M;2fvl8J%|xcUllfWA%}3?w}_{%nVRJML&Q^;OpS5=2=NZ$Pjfy=Jaxg;DCh4Z zo|=AYg!B7|rzW2|%K6>IQ&UeRINwe@HStsr=eHA2O*_@b`9|WYNvAxVzlC^evZ-3m z*AY)mHKlO=M&hZ7rm8sqHR5R~PciV+F6aJgO%KaH1n!wrXuh+=o}&*8HPO^c;QL*b ztB*m2v95E}6l&&8@2(E@!FNZAnea`5fFAFKEJd>`5IMJYDNJO1V-R>vsX`or9?
    SnTL{C*7dmR}XnNIkQa^q*X`u(Tf zFP}Zlvp7yI2kR%9k;~Ch%H=~Nm!rt#f;u$JWrqH=pF}grd#LLq@)|>4l=o{quVLh+ z4pqSLzi`77xjSprq5ChW!;ewb&i;zfq4HeY+H4c7yI=QbUf5r`x|y^fg|_rQorR41 zqW4S#%8G1B?-?2{?y=UPt2=soklcGWR?*&Ed&A(k4Q;GE_=%^nlBJ)`zW-@1cYfxs zv9ljT>f9(gqjlZ%^Z#-A#*W02mw-KXFR<*lp?;Q3 zshNrF8(@fTC-75gFMH5{&tJL=Hg_Ky z_Rc?_9m}WwM5G?cr~XLIjGv!5%&k6;CRQ`Q%r2%<4DGb@}xtHE~byh?_G&lJv(jM|1rJ3SJb@*>+=$H*mzB5F1GP2Kp4_QwgraqZDJQW8u zX}?=cduqE7z8!S-)#BsG{hmMb(q1+5hC2A`>9$V)#8?$tK%IDQw3^7oC|=9liWjOB z_Fr87%#Scgy43YFR@A{6C*I6MtInXVe44A?!#gi`0fW?dfA@^>g={&nVd#KsDnq;m2Q2 zm#Y)yJs8yPvGM&QyeQ>}iu_C3cNDYlEM-42$Nq@Xo*nAYVFiV!dM;E4AE;uwE7yTZ zsHsYwXi}&tXjImynO|VI^FetJx;NjS_l#%#mvXrg+23D+y-PC~rP7}FF7GaHCg<() zcD4>*_rxLvgJ*dCUx0S_GZ+1tS6kP;$-lMFed@@56PoJr_jJqwQol9xc5CKhGc4qm z|6HZ{Z_B@@-=+`EJ$te^7(-x0Mx4LWV z>J{QTBC&&8TO!eLXTQ#Y=16jDG=3m;b7J%Qec@P;f7BD3mA-H)6*v%9zJ6Wk7NxT{ zl2Y(L74Hix*ih)o{&-Ruh^LcEA{q{)(#bH-uPG3_L05u&qoMd|&tYsf_!dLKMj;jp zM-?}lBWLVEyop3K5)9CuhwY$UlPr@fm`JeBxE_e!qOj(0R1YXy6{e)Z!FVi`V(r-1 z5O6a9UXB}g*VC@c*A;DZ*Upy1r}0$AOzB%FnP=~-)fnHaVSOa_w+aRz1<88^zxH5k zC%abn+g3SljUt^E64{Hn9KE;M-{f+Wn3rqNty$3iPjb1F!22;HUjU_fdj|9jDD7iw zFc&wF9OzNd7eSvS9G^})pE?Q3S5nYfj)#KnNISFjSJ_rAF0UA|l~)md4W2CCq?<@U zgyQmyU5j**UyCyH1+}xP#aXkxa?#<6qwKbox8Atn+OLrb(#L0;ji3%+AwUGe@5OV< zf|Fex&nWP_L7D2T8nkyW9Cuczi`wu@7y`+CAJ1!_BS&SVU^~**%4=Nipsl{csJCH< zY)!+?Hqd#Cufmdn@=PssR_P<_;PN7T@n(-WiJt`l6LmHh` z-?le8YaVgIc%8Lg=h{Z60y)SxB7Z8^Khl^$ z`HeT5tQ#ShvtfzKAJ_F|6J@Nq?1yD+&{pa=h zJr;hag{L!N3ba0@An#%1S)jaUk!w47ze@Ku6sin@n;;|figmGEm&x_q$DifmByq~_ zA;QnGi8hpZi152uq8IEQ{4yrbI**CPjImn6`i7?(_k<$K36@+&P&9}&DPcaM-?AgIhAOKx7D>2eQG!RDLuvK-Tb|EWk9>i=g%-eX%c zJh9Njq3;U%grH9e`huW86Z9=XFA6$ejQgtuyK2=Z+sLLoqw|L7rO0`u^U}?aX~&PH_2U zbKb|t1#W$Rf6VQmHcAg=ln-OTi}{5-fQC}AO0d3P6OgZ_b`$f@JYnf)z?bH&&PM*T z1pW^CWhwfd&h;tK84QIQ7%XO|2Y9u8C8LWvbLazJ%ztGM?ueG+=31_Yq|OgY*nheN zK8SXpax(GW$+NhBDj~m=%gfwm>3NRN{VrSwoa#l_5a!?}yoi5{TEhPQz^Nat{q-o? zwF-8uemvje@^k0O@0PItEXUDb;(ZK@!u~@E`HuunhkNF*ocD_vG2%Csz;7*qcW`_O zqgx^h7*0F{OUOS2ToE#6@<&3x$5KufOzJ5;jT<9)xMvSDIKj1&L5xI}nZU3q-Y$9#5vUK)Rm=<9#?w*TW&#rcImN#f7+gk`_oN0|RhT z(USvge=^V))AjwbzD5n&4#S8RhYyx<-2hjik|sqhzi@#}jfwXAGRjk6 zQ52^(9gBP;9o7pZnNI3-Ty&rTk9Q--d0UZrT1xm zv@G{#>(E;pG%XT0yykX`-f-7xT1(f?rcVDIJISYRcV|bbezGLamV~ZhV5Qx=!>9Rn zHj^3tM#(sQPc@$^1k~nsrZwNa)4Rjp1UV{Ae$0mo0pZytYI8?RONS30W!}bC+zLq- zF#jEJ01HK8S~?XD&Gni4JQqEWhx>{N|1kJ^k;3oh<5pk_6$z!{n(@9;!+pM2o5y4F zMk5C}=?N$d3x77lEzy$M@8;TPH3COR3#4`KXp&t@4MUEE77=oB{2V950u2}3?$9`x zjil$E*^95Z!(@R0XmeN1U@FZ=4_ddlZ()HJeE*91a27T?86r=|0!`DPGVVMJT^1oL zybev};y$T!TuOym*^w4+*11(DpU}dhFjs1zPY>(^)sqJ8m9a<+->d|4#o~I{1+T{S zdfSeCbKn(T_swa(+gvUt7!7I3a5O*)B9@5i z%*Ce?7u_y17q7A_8Rwpvu5hpTvh{|bD>)d2FK)O$7*6OKiXROdHjD|tup#631))gB zC}-H^r3~~%f-n+Ce)w_mLKqps6O_5|LGB|@*)Ji`evkG9a@`@%H{{<@Sa+HvYYtxr zLuXi0ztipkH~V)A3g>2ju-q&NZg6IO-R|M(x-fVx=VpJb`prnf)n{Dhf6DIR!lwkF za&C6NR3Ugt=v?y9XSd2Xex?1;z4;x0BSD=W)A$V`-Y#m*{g`m+AVgnpxtljlg&LQtNAl0NN0t@@7uqcKJ0qae?LyTw7QJTEm; zjk3x((F`85zC4#o$b($VfR+1oNxx&&7whMQIQacDSun~BLFySCV}F8(Ie)oNTP`+# z3#6c+*6}+k^kw_Y{iq`JW&24p*8HEe=*xY#{Cl6MR20;j|5FxydA>HY%urY^3nuhs z{|T0jAwu<+V)7hrv2c>UMG6XP=??ZXa3>xbn-t`JU;h1&wZ1ZcNq+$y^52&F@?5W1 z{C$;_Bij@tFX`LBs7z8{o|7d$N1tp__yCVtzh9gm_6z-PE;aij^OeYN5s~jEVe&jt z{(YDt8deTNsW02544Iqrm*dG)APNpfZ0+ms#}XzI{aK zm&#w7{R;HSmTZ4{elRNZYmjaZ0?tEU75UfZ5hEh?MK|PAr8zT|V>d5^$e3bqlcJ(u u1-liGthb#1=>3*uH#Cgjk#z=rN_Lz`l=({8YD9|Zw}=YeU{SEJ?7sm8AXkI{ literal 0 HcmV?d00001 diff --git a/bench/spdlog-async.cpp b/bench/spdlog-async.cpp index 0db4f6c6..1c0ce41d 100644 --- a/bench/spdlog-async.cpp +++ b/bench/spdlog-async.cpp @@ -15,22 +15,22 @@ using namespace std; int main(int argc, char *argv[]) { - using namespace std::chrono; using clock = steady_clock; - namespace spd = spdlog; int thread_count = 10; if (argc > 1) thread_count = ::atoi(argv[1]); + int howmany = 1000000; - spd::set_async_mode(1048576); - auto logger = spdlog::create("file_logger", "logs/spd-bench-async.txt", false); - logger->set_pattern("[%Y-%b-%d %T.%e]: %v"); + spdlog::set_async_mode(1048576); + auto logger = spdlog::create("file_logger", "logs/spdlog-bench-async.log", false); + logger->set_pattern("[%Y-%b-%d %T.%e]: %f"); std::atomic msg_counter{0}; vector threads; + auto start = clock::now(); for (int t = 0; t < thread_count; ++t) { @@ -48,7 +48,7 @@ int main(int argc, char *argv[]) for (auto &t : threads) { t.join(); - }; + } duration delta = clock::now() - start; float deltaf = delta.count(); diff --git a/bench/spdlog-bench-mt.cpp b/bench/spdlog-bench-mt.cpp index 5feb7044..d6dfeb51 100644 --- a/bench/spdlog-bench-mt.cpp +++ b/bench/spdlog-bench-mt.cpp @@ -3,16 +3,21 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#include "spdlog/spdlog.h" #include +#include +#include #include #include #include +#include "spdlog/spdlog.h" + using namespace std; int main(int argc, char *argv[]) { + using namespace std::chrono; + using clock = steady_clock; int thread_count = 10; if (argc > 1) @@ -20,15 +25,13 @@ int main(int argc, char *argv[]) int howmany = 1000000; - namespace spd = spdlog; - - auto logger = spdlog::create("file_logger", "logs/spd-bench-mt.txt", false); - - logger->set_pattern("[%Y-%b-%d %T.%e]: %v"); + auto logger = spdlog::create("file_logger", "logs/spdlog-bench-mt.log", false); + logger->set_pattern("[%Y-%b-%d %T.%f]: %v"); std::atomic msg_counter{0}; std::vector threads; + auto start = clock::now(); for (int t = 0; t < thread_count; ++t) { threads.push_back(std::thread([&]() { @@ -45,7 +48,16 @@ int main(int argc, char *argv[]) for (auto &t : threads) { t.join(); - }; + } + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Threads: " << thread_count << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; return 0; } diff --git a/bench/spdlog-bench.cpp b/bench/spdlog-bench.cpp index 8d122249..e241fa5e 100644 --- a/bench/spdlog-bench.cpp +++ b/bench/spdlog-bench.cpp @@ -3,17 +3,32 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // +#include +#include + #include "spdlog/spdlog.h" int main(int, char *[]) { + using namespace std::chrono; + using clock = steady_clock; + int howmany = 1000000; - namespace spd = spdlog; - /// Create a file rotating logger with 5mb size max and 3 rotated files - auto logger = spdlog::create("file_logger", "logs/spd-bench-st.txt", false); - logger->set_pattern("[%Y-%b-%d %T.%e]: %v"); + auto logger = spdlog::create("file_logger", "logs/spdlog-bench.log", false); + logger->set_pattern("[%Y-%b-%d %T.%f]: %v"); + + auto start = clock::now(); for (int i = 0; i < howmany; ++i) logger->info("spdlog message #{} : This is some text for your pleasure", i); + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + return 0; } diff --git a/bench/spdlog-null-async.cpp b/bench/spdlog-null-async.cpp index df07f834..e9b33c9d 100644 --- a/bench/spdlog-null-async.cpp +++ b/bench/spdlog-null-async.cpp @@ -93,7 +93,7 @@ size_t bench_as(int howmany, std::shared_ptr log, int thread_cou for (auto &t : threads) { t.join(); - }; + } auto delta = system_clock::now() - start; auto delta_d = duration_cast>(delta).count(); From fd1c4d78775a5a3ad5d5cc3f95469b9501cc39af Mon Sep 17 00:00:00 2001 From: Alexander Kiselev Date: Mon, 19 Mar 2018 20:03:47 +0300 Subject: [PATCH 33/62] Fix: unknown conversion specifier 'Y' --- bench/log4cpp-bench-mt.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bench/log4cpp-bench-mt.cpp b/bench/log4cpp-bench-mt.cpp index 82f3a40f..dc6a5f58 100644 --- a/bench/log4cpp-bench-mt.cpp +++ b/bench/log4cpp-bench-mt.cpp @@ -31,7 +31,7 @@ int main(int argc, char * argv[]) log4cpp::Appender *appender = new log4cpp::FileAppender("default", "logs/log4cpp-bench-mt.log"); log4cpp::PatternLayout *layout = new log4cpp::PatternLayout(); - layout->setConversionPattern("{%Y-%m-%d %H:%M:%S.%l}: %p - %m %n"); + layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S.%l}: %p - %m %n"); appender->setLayout(layout); log4cpp::Category& root = log4cpp::Category::getRoot(); From 0f66c63f72b3b0b3e0ea9073d5bf47af02057172 Mon Sep 17 00:00:00 2001 From: Alexander Kiselev Date: Wed, 21 Mar 2018 16:46:52 +0300 Subject: [PATCH 34/62] Update easyloggingpp, Add plog --- bench/Makefile | 20 +++++++-- bench/easyl-async.conf | 10 +++++ bench/easyl-mt.conf | 2 +- bench/easyl.conf | 2 +- bench/easylogging-bench-async.cpp | 67 +++++++++++++++++++++++++++++++ bench/plog-bench-mt.cpp | 61 ++++++++++++++++++++++++++++ bench/plog-bench.cpp | 34 ++++++++++++++++ 7 files changed, 190 insertions(+), 6 deletions(-) create mode 100644 bench/easyl-async.conf create mode 100644 bench/easylogging-bench-async.cpp create mode 100644 bench/plog-bench-mt.cpp create mode 100644 bench/plog-bench.cpp diff --git a/bench/Makefile b/bench/Makefile index c619a5ae..8328c5cd 100644 --- a/bench/Makefile +++ b/bench/Makefile @@ -11,7 +11,8 @@ binaries=spdlog-bench spdlog-bench-mt spdlog-async spdlog-null-async \ p7-bench p7-bench-mt \ log4cpp-bench log4cpp-bench-mt \ log4cplus-bench log4cplus-bench-mt \ - easylogging-bench easylogging-bench-mt + easylogging-bench easylogging-bench-mt easylogging-bench-async \ + plog-bench plog-bench-mt all: $(binaries) @@ -22,7 +23,7 @@ spdlog-bench-mt: spdlog-bench-mt.cpp $(CXX) spdlog-bench-mt.cpp -o spdlog-bench-mt $(CXXFLAGS) $(CXX_RELEASE_FLAGS) spdlog-async: spdlog-async.cpp - $(CXX) spdlog-async.cpp -o spdlog-async $(CXXFLAGS) $(CXX_RELEASE_FLAGS) + $(CXX) spdlog-async.cpp -o spdlog-async $(CXXFLAGS) $(CXX_RELEASE_FLAGS) -g spdlog-null-async: spdlog-null-async.cpp $(CXX) spdlog-null-async.cpp -o spdlog-null-async $(CXXFLAGS) $(CXX_RELEASE_FLAGS) @@ -74,9 +75,20 @@ log4cplus-bench-mt: log4cplus-bench-mt.cpp EASYL_FLAGS = -I$(HOME)/easyloggingpp/src easylogging-bench: easylogging-bench.cpp $(CXX) easylogging-bench.cpp -o easylogging-bench $(CXXFLAGS) $(EASYL_FLAGS) $(CXX_RELEASE_FLAGS) + easylogging-bench-mt: easylogging-bench-mt.cpp - $(CXX) easylogging-bench-mt.cpp -o easylogging-bench-mt $(CXXFLAGS) $(EASYL_FLAGS) $(CXX_RELEASE_FLAGS) - + $(CXX) easylogging-bench-mt.cpp -o easylogging-bench-mt $(CXXFLAGS) $(EASYL_FLAGS) $(CXX_RELEASE_FLAGS) + +easylogging-bench-async: easylogging-bench-async.cpp + $(CXX) easylogging-bench-async.cpp -o easylogging-bench-async $(CXXFLAGS) $(EASYL_FLAGS) $(CXX_RELEASE_FLAGS) + +PLOG_FLAGS = -I$(HOME)/include +plog-bench: plog-bench.cpp + $(CXX) plog-bench.cpp -o plog-bench $(CXXFLAGS) $(PLOG_FLAGS) $(CXX_RELEASE_FLAGS) + +plog-bench-mt: plog-bench-mt.cpp + $(CXX) plog-bench-mt.cpp -o plog-bench-mt $(CXXFLAGS) $(PLOG_FLAGS) $(CXX_RELEASE_FLAGS) + .PHONY: clean clean: diff --git a/bench/easyl-async.conf b/bench/easyl-async.conf new file mode 100644 index 00000000..a6c52050 --- /dev/null +++ b/bench/easyl-async.conf @@ -0,0 +1,10 @@ +* GLOBAL: + FORMAT = "[%datetime]: %levshort %thread %msg" + FILENAME = ./logs/easylogging-async.log + ENABLED = true + TO_FILE = true + TO_STANDARD_OUTPUT = false + MILLISECONDS_WIDTH = 3 + PERFORMANCE_TRACKING = false + MAX_LOG_FILE_SIZE = 10485760 + Log_Flush_Threshold = 10485760 diff --git a/bench/easyl-mt.conf b/bench/easyl-mt.conf index 8895b281..ceff467c 100644 --- a/bench/easyl-mt.conf +++ b/bench/easyl-mt.conf @@ -1,5 +1,5 @@ * GLOBAL: - FORMAT = "[%datetime]: %msg" + FORMAT = "[%datetime]: %levshort %thread %msg" FILENAME = ./logs/easylogging-mt.log ENABLED = true TO_FILE = true diff --git a/bench/easyl.conf b/bench/easyl.conf index 3bfb5440..c54f6c83 100644 --- a/bench/easyl.conf +++ b/bench/easyl.conf @@ -1,5 +1,5 @@ * GLOBAL: - FORMAT = "[%datetime]: %msg" + FORMAT = "[%datetime]: %levshort %msg" FILENAME = ./logs/easylogging.log ENABLED = true TO_FILE = true diff --git a/bench/easylogging-bench-async.cpp b/bench/easylogging-bench-async.cpp new file mode 100644 index 00000000..81985a6a --- /dev/null +++ b/bench/easylogging-bench-async.cpp @@ -0,0 +1,67 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include +#include +#include +#include +#include + +#define ELPP_THREAD_SAFE +#define ELPP_EXPERIMENTAL_ASYNC +#include "easylogging++.h" +#include "easylogging++.cc" +INITIALIZE_EASYLOGGINGPP + +using namespace std; + +int main(int argc, char *argv[]) +{ + using namespace std::chrono; + using clock = steady_clock; + + int thread_count = 10; + if (argc > 1) + thread_count = atoi(argv[1]); + + int howmany = 1000000; + + // Load configuration from file + el::Configurations conf("easyl-async.conf"); + el::Loggers::reconfigureLogger("default", conf); + + std::atomic msg_counter{0}; + vector threads; + + auto start = clock::now(); + for (int t = 0; t < thread_count; ++t) + { + threads.push_back(std::thread([&]() { + while (true) + { + int counter = ++msg_counter; + if (counter > howmany) + break; + LOG(INFO) << "easylog message #" << counter << ": This is some text for your pleasure"; + } + })); + } + + for (auto &t : threads) + { + t.join(); + } + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Threads: " << thread_count << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + + return 0; +} diff --git a/bench/plog-bench-mt.cpp b/bench/plog-bench-mt.cpp new file mode 100644 index 00000000..5951643f --- /dev/null +++ b/bench/plog-bench-mt.cpp @@ -0,0 +1,61 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include +#include +#include +#include +#include + +#include "plog/Log.h" + +using namespace std; + +int main(int argc, char *argv[]) +{ + using namespace std::chrono; + using clock = steady_clock; + + int thread_count = 10; + if (argc > 1) + thread_count = atoi(argv[1]); + + int howmany = 1000000; + + plog::init(plog::debug, "logs/plog-bench-mt.log"); + + std::atomic msg_counter{0}; + vector threads; + + auto start = clock::now(); + for (int t = 0; t < thread_count; ++t) + { + threads.push_back(std::thread([&]() { + while (true) + { + int counter = ++msg_counter; + if (counter > howmany) + break; + LOG_INFO << "plog message #" << counter << ": This is some text for your pleasure"; + } + })); + } + + for (auto &t : threads) + { + t.join(); + } + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Threads: " << thread_count << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + + return 0; +} diff --git a/bench/plog-bench.cpp b/bench/plog-bench.cpp new file mode 100644 index 00000000..3e017fc7 --- /dev/null +++ b/bench/plog-bench.cpp @@ -0,0 +1,34 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include +#include +#include + +#include "plog/Log.h" + +int main(int, char *[]) +{ + using namespace std::chrono; + using clock = steady_clock; + + int howmany = 1000000; + + plog::init(plog::debug, "logs/plog-bench.log"); + + auto start = clock::now(); + for (int i = 0; i < howmany; ++i) + LOG_INFO << "plog message #" << i << ": This is some text for your pleasure"; + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Delta = " << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << rate << "/sec" << std::endl; + + return 0; +} From 37f209079e5108f70689766c32c0c1b9e15c7cd7 Mon Sep 17 00:00:00 2001 From: Alexander Kiselev Date: Wed, 21 Mar 2018 16:50:45 +0300 Subject: [PATCH 35/62] Update spdlog-bench --- bench/Makefile | 2 +- bench/spdlog-async.cpp | 75 +++++++++++++++++++++++---------------- bench/spdlog-bench-mt.cpp | 6 ++-- bench/spdlog-bench.cpp | 6 ++-- 4 files changed, 52 insertions(+), 37 deletions(-) diff --git a/bench/Makefile b/bench/Makefile index 8328c5cd..0dd4b19d 100644 --- a/bench/Makefile +++ b/bench/Makefile @@ -23,7 +23,7 @@ spdlog-bench-mt: spdlog-bench-mt.cpp $(CXX) spdlog-bench-mt.cpp -o spdlog-bench-mt $(CXXFLAGS) $(CXX_RELEASE_FLAGS) spdlog-async: spdlog-async.cpp - $(CXX) spdlog-async.cpp -o spdlog-async $(CXXFLAGS) $(CXX_RELEASE_FLAGS) -g + $(CXX) spdlog-async.cpp -o spdlog-async $(CXXFLAGS) $(CXX_RELEASE_FLAGS) spdlog-null-async: spdlog-null-async.cpp $(CXX) spdlog-null-async.cpp -o spdlog-null-async $(CXXFLAGS) $(CXX_RELEASE_FLAGS) diff --git a/bench/spdlog-async.cpp b/bench/spdlog-async.cpp index 1c0ce41d..e1d1a95f 100644 --- a/bench/spdlog-async.cpp +++ b/bench/spdlog-async.cpp @@ -3,14 +3,15 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#include "spdlog/spdlog.h" #include #include -#include #include +#include #include #include +#include "spdlog/spdlog.h" + using namespace std; int main(int argc, char *argv[]) @@ -20,42 +21,56 @@ int main(int argc, char *argv[]) int thread_count = 10; if (argc > 1) - thread_count = ::atoi(argv[1]); + thread_count = std::atoi(argv[1]); int howmany = 1000000; spdlog::set_async_mode(1048576); auto logger = spdlog::create("file_logger", "logs/spdlog-bench-async.log", false); - logger->set_pattern("[%Y-%b-%d %T.%e]: %f"); + logger->set_pattern("[%Y-%m-%d %T.%F]: %L %t %v"); - std::atomic msg_counter{0}; - vector threads; + std::cout << "To stop, press " << std::endl; + std::atomic run{true}; + std::thread stoper(std::thread([&run]() { + std::cin.get(); + run = false; + })); - auto start = clock::now(); - for (int t = 0; t < thread_count; ++t) + while(run) { - threads.push_back(std::thread([&]() { - while (true) - { - int counter = ++msg_counter; - if (counter > howmany) - break; - logger->info("spdlog message #{}: This is some text for your pleasure", counter); - } - })); - } - - for (auto &t : threads) - { - t.join(); - } + std::atomic msg_counter{0}; + std::vector threads; + + auto start = clock::now(); + for (int t = 0; t < thread_count; ++t) + { + threads.push_back(std::thread([&]() { + while (true) + { + int counter = ++msg_counter; + if (counter > howmany) + break; + logger->info("spdlog message #{}: This is some text for your pleasure", counter); + } + })); + } + + for (auto &t : threads) + { + t.join(); + } + + duration delta = clock::now() - start; + float deltaf = delta.count(); + auto rate = howmany / deltaf; + + std::cout << "Total: " << howmany << std::endl; + std::cout << "Threads: " << thread_count << std::endl; + std::cout << "Delta = " << std::fixed << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << std::fixed << rate << "/sec" << std::endl; + } //while - duration delta = clock::now() - start; - float deltaf = delta.count(); - auto rate = howmany / deltaf; + stoper.join(); - cout << "Total: " << howmany << std::endl; - cout << "Threads: " << thread_count << std::endl; - std::cout << "Delta = " << deltaf << " seconds" << std::endl; - std::cout << "Rate = " << rate << "/sec" << std::endl; + return 0; } diff --git a/bench/spdlog-bench-mt.cpp b/bench/spdlog-bench-mt.cpp index d6dfeb51..b4948e73 100644 --- a/bench/spdlog-bench-mt.cpp +++ b/bench/spdlog-bench-mt.cpp @@ -26,7 +26,7 @@ int main(int argc, char *argv[]) int howmany = 1000000; auto logger = spdlog::create("file_logger", "logs/spdlog-bench-mt.log", false); - logger->set_pattern("[%Y-%b-%d %T.%f]: %v"); + logger->set_pattern("[%Y-%m-%d %T.%F]: %L %t %v"); std::atomic msg_counter{0}; std::vector threads; @@ -56,8 +56,8 @@ int main(int argc, char *argv[]) std::cout << "Total: " << howmany << std::endl; std::cout << "Threads: " << thread_count << std::endl; - std::cout << "Delta = " << deltaf << " seconds" << std::endl; - std::cout << "Rate = " << rate << "/sec" << std::endl; + std::cout << "Delta = " << std::fixed << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << std::fixed << rate << "/sec" << std::endl; return 0; } diff --git a/bench/spdlog-bench.cpp b/bench/spdlog-bench.cpp index e241fa5e..bb8a5ef8 100644 --- a/bench/spdlog-bench.cpp +++ b/bench/spdlog-bench.cpp @@ -16,7 +16,7 @@ int main(int, char *[]) int howmany = 1000000; auto logger = spdlog::create("file_logger", "logs/spdlog-bench.log", false); - logger->set_pattern("[%Y-%b-%d %T.%f]: %v"); + logger->set_pattern("[%Y-%m-%d %T.%F]: %L %v"); auto start = clock::now(); for (int i = 0; i < howmany; ++i) @@ -27,8 +27,8 @@ int main(int, char *[]) auto rate = howmany / deltaf; std::cout << "Total: " << howmany << std::endl; - std::cout << "Delta = " << deltaf << " seconds" << std::endl; - std::cout << "Rate = " << rate << "/sec" << std::endl; + std::cout << "Delta = " << std::fixed << deltaf << " seconds" << std::endl; + std::cout << "Rate = " << std::fixed << rate << "/sec" << std::endl; return 0; } From 5e1e897d109616d2b53ea8830f3467e29ab94307 Mon Sep 17 00:00:00 2001 From: Alexander Kiselev Date: Wed, 21 Mar 2018 16:51:43 +0300 Subject: [PATCH 36/62] Remove p7-bench binary --- bench/p7-bench | Bin 14704 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100755 bench/p7-bench diff --git a/bench/p7-bench b/bench/p7-bench deleted file mode 100755 index 566ec56b04ab3c6f4147b140ac46c0785d7607de..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 14704 zcmeHOdvIG-dOwol*m=oz9^g&r=4O{i0uy05PU66%NVer%1t%Ckf(azoiloFMvZR%+ z5<62$z)3b*W7eh1lI?6~J)JGf>>q8q(=q|JiKz*u)5jPXwzO<_Q+A;;PcxLP6Bg9p zckVgz)wNWZ9om1IlU#l0`_q!q%919Tpq2Dd_?J1xt6$qh+3dMuMf2nw+H!1Wcg`T8}D8Hn#eq@H8PLbYe z_kbhbLxeT+-&rcNZF^G>QT*gGL*V2x506M1HDD&G)VmXURL(CNs)S&>$gfnpJSoaA zsqBZFqmg}^>TiyQ)<+|;bpQJPhE3}?)w@!0R~@f6*(cd;JG*#JvK&kv|YSn#XM;_{+G--qCb@I7d+nO@Z0>Y?iR^Vy$z54Ep4=#N9 z*CL#`S(i5 zA1Q%vFJb4w67s7`$p38#`H2$p50$_dmB25Qz4BuKX-td6B0AIdgOF584+U?! zi6l1>+n0|W2nMwjac;sBdT%lu2oYaPe9(~7G>Qw`eSt`fX}d$wwnHGX!+i`{_xEdw za55E-1)>psKs!{6qz=7qqo%=P{IIq!5YqOiV?jNFG6nJH06cSV6dOynB znrp`vY1)5BH;DZJV_wlvEFEP0>g=W(GQwfneCMzA1>zWAP2zt~z&JN=MBG zv|uzIJh&kiKg_f0(CdToG#Uz}ji&q^y4xM>4J0)^8Hng9f6(V^2ettvj0ClKN=Kf3 z{$Qu(>)5EZ-5%uG#G@%+gj=W&$3jtm@QYdL)H-WnXA}AgEfL?M?LeQU!b#m9qFm#h zNa%_kj>JM*dpMQuqdIl&+Uc&<&=CEBeUU?M_h!VSfmBM<2NGeZ?~nVK77hjU06JwK za6TLW#X@XbQH=4193_r-UCYWsDh{M`hi6xzaH-q1xnuwD$~;| zBMaz@yD^_$#%>VlB%gU;9a74f7r&$vnRy(s`RoqCzw(y{@wuMI_6lBK_b5J*4i*u7 zh|Akq8a##R)jgcjobTi@<7dW%SDJ7+f6$ts+JwvbfN-%S;HfoY9x4YXUVV-$CR`MS z<7-VgwVw>NCR~1lDXqbTo7X8G6K?)at0tVvBtx4Cmum`2>o(!&n0)9l;S2L9W4$K) zY7?F?;TQn<&~L(NPM6`R311>X(32*-#)PYb?^dWoWsj{;n0kCnx929+!RIT+S#IN_ zfO6M;2fvl8J%|xcUllfWA%}3?w}_{%nVRJML&Q^;OpS5=2=NZ$Pjfy=Jaxg;DCh4Z zo|=AYg!B7|rzW2|%K6>IQ&UeRINwe@HStsr=eHA2O*_@b`9|WYNvAxVzlC^evZ-3m z*AY)mHKlO=M&hZ7rm8sqHR5R~PciV+F6aJgO%KaH1n!wrXuh+=o}&*8HPO^c;QL*b ztB*m2v95E}6l&&8@2(E@!FNZAnea`5fFAFKEJd>`5IMJYDNJO1V-R>vsX`or9?
      SnTL{C*7dmR}XnNIkQa^q*X`u(Tf zFP}Zlvp7yI2kR%9k;~Ch%H=~Nm!rt#f;u$JWrqH=pF}grd#LLq@)|>4l=o{quVLh+ z4pqSLzi`77xjSprq5ChW!;ewb&i;zfq4HeY+H4c7yI=QbUf5r`x|y^fg|_rQorR41 zqW4S#%8G1B?-?2{?y=UPt2=soklcGWR?*&Ed&A(k4Q;GE_=%^nlBJ)`zW-@1cYfxs zv9ljT>f9(gqjlZ%^Z#-A#*W02mw-KXFR<*lp?;Q3 zshNrF8(@fTC-75gFMH5{&tJL=Hg_Ky z_Rc?_9m}WwM5G?cr~XLIjGv!5%&k6;CRQ`Q%r2%<4DGb@}xtHE~byh?_G&lJv(jM|1rJ3SJb@*>+=$H*mzB5F1GP2Kp4_QwgraqZDJQW8u zX}?=cduqE7z8!S-)#BsG{hmMb(q1+5hC2A`>9$V)#8?$tK%IDQw3^7oC|=9liWjOB z_Fr87%#Scgy43YFR@A{6C*I6MtInXVe44A?!#gi`0fW?dfA@^>g={&nVd#KsDnq;m2Q2 zm#Y)yJs8yPvGM&QyeQ>}iu_C3cNDYlEM-42$Nq@Xo*nAYVFiV!dM;E4AE;uwE7yTZ zsHsYwXi}&tXjImynO|VI^FetJx;NjS_l#%#mvXrg+23D+y-PC~rP7}FF7GaHCg<() zcD4>*_rxLvgJ*dCUx0S_GZ+1tS6kP;$-lMFed@@56PoJr_jJqwQol9xc5CKhGc4qm z|6HZ{Z_B@@-=+`EJ$te^7(-x0Mx4LWV z>J{QTBC&&8TO!eLXTQ#Y=16jDG=3m;b7J%Qec@P;f7BD3mA-H)6*v%9zJ6Wk7NxT{ zl2Y(L74Hix*ih)o{&-Ruh^LcEA{q{)(#bH-uPG3_L05u&qoMd|&tYsf_!dLKMj;jp zM-?}lBWLVEyop3K5)9CuhwY$UlPr@fm`JeBxE_e!qOj(0R1YXy6{e)Z!FVi`V(r-1 z5O6a9UXB}g*VC@c*A;DZ*Upy1r}0$AOzB%FnP=~-)fnHaVSOa_w+aRz1<88^zxH5k zC%abn+g3SljUt^E64{Hn9KE;M-{f+Wn3rqNty$3iPjb1F!22;HUjU_fdj|9jDD7iw zFc&wF9OzNd7eSvS9G^})pE?Q3S5nYfj)#KnNISFjSJ_rAF0UA|l~)md4W2CCq?<@U zgyQmyU5j**UyCyH1+}xP#aXkxa?#<6qwKbox8Atn+OLrb(#L0;ji3%+AwUGe@5OV< zf|Fex&nWP_L7D2T8nkyW9Cuczi`wu@7y`+CAJ1!_BS&SVU^~**%4=Nipsl{csJCH< zY)!+?Hqd#Cufmdn@=PssR_P<_;PN7T@n(-WiJt`l6LmHh` z-?le8YaVgIc%8Lg=h{Z60y)SxB7Z8^Khl^$ z`HeT5tQ#ShvtfzKAJ_F|6J@Nq?1yD+&{pa=h zJr;hag{L!N3ba0@An#%1S)jaUk!w47ze@Ku6sin@n;;|figmGEm&x_q$DifmByq~_ zA;QnGi8hpZi152uq8IEQ{4yrbI**CPjImn6`i7?(_k<$K36@+&P&9}&DPcaM-?AgIhAOKx7D>2eQG!RDLuvK-Tb|EWk9>i=g%-eX%c zJh9Njq3;U%grH9e`huW86Z9=XFA6$ejQgtuyK2=Z+sLLoqw|L7rO0`u^U}?aX~&PH_2U zbKb|t1#W$Rf6VQmHcAg=ln-OTi}{5-fQC}AO0d3P6OgZ_b`$f@JYnf)z?bH&&PM*T z1pW^CWhwfd&h;tK84QIQ7%XO|2Y9u8C8LWvbLazJ%ztGM?ueG+=31_Yq|OgY*nheN zK8SXpax(GW$+NhBDj~m=%gfwm>3NRN{VrSwoa#l_5a!?}yoi5{TEhPQz^Nat{q-o? zwF-8uemvje@^k0O@0PItEXUDb;(ZK@!u~@E`HuunhkNF*ocD_vG2%Csz;7*qcW`_O zqgx^h7*0F{OUOS2ToE#6@<&3x$5KufOzJ5;jT<9)xMvSDIKj1&L5xI}nZU3q-Y$9#5vUK)Rm=<9#?w*TW&#rcImN#f7+gk`_oN0|RhT z(USvge=^V))AjwbzD5n&4#S8RhYyx<-2hjik|sqhzi@#}jfwXAGRjk6 zQ52^(9gBP;9o7pZnNI3-Ty&rTk9Q--d0UZrT1xm zv@G{#>(E;pG%XT0yykX`-f-7xT1(f?rcVDIJISYRcV|bbezGLamV~ZhV5Qx=!>9Rn zHj^3tM#(sQPc@$^1k~nsrZwNa)4Rjp1UV{Ae$0mo0pZytYI8?RONS30W!}bC+zLq- zF#jEJ01HK8S~?XD&Gni4JQqEWhx>{N|1kJ^k;3oh<5pk_6$z!{n(@9;!+pM2o5y4F zMk5C}=?N$d3x77lEzy$M@8;TPH3COR3#4`KXp&t@4MUEE77=oB{2V950u2}3?$9`x zjil$E*^95Z!(@R0XmeN1U@FZ=4_ddlZ()HJeE*91a27T?86r=|0!`DPGVVMJT^1oL zybev};y$T!TuOym*^w4+*11(DpU}dhFjs1zPY>(^)sqJ8m9a<+->d|4#o~I{1+T{S zdfSeCbKn(T_swa(+gvUt7!7I3a5O*)B9@5i z%*Ce?7u_y17q7A_8Rwpvu5hpTvh{|bD>)d2FK)O$7*6OKiXROdHjD|tup#631))gB zC}-H^r3~~%f-n+Ce)w_mLKqps6O_5|LGB|@*)Ji`evkG9a@`@%H{{<@Sa+HvYYtxr zLuXi0ztipkH~V)A3g>2ju-q&NZg6IO-R|M(x-fVx=VpJb`prnf)n{Dhf6DIR!lwkF za&C6NR3Ugt=v?y9XSd2Xex?1;z4;x0BSD=W)A$V`-Y#m*{g`m+AVgnpxtljlg&LQtNAl0NN0t@@7uqcKJ0qae?LyTw7QJTEm; zjk3x((F`85zC4#o$b($VfR+1oNxx&&7whMQIQacDSun~BLFySCV}F8(Ie)oNTP`+# z3#6c+*6}+k^kw_Y{iq`JW&24p*8HEe=*xY#{Cl6MR20;j|5FxydA>HY%urY^3nuhs z{|T0jAwu<+V)7hrv2c>UMG6XP=??ZXa3>xbn-t`JU;h1&wZ1ZcNq+$y^52&F@?5W1 z{C$;_Bij@tFX`LBs7z8{o|7d$N1tp__yCVtzh9gm_6z-PE;aij^OeYN5s~jEVe&jt z{(YDt8deTNsW02544Iqrm*dG)APNpfZ0+ms#}XzI{aK zm&#w7{R;HSmTZ4{elRNZYmjaZ0?tEU75UfZ5hEh?MK|PAr8zT|V>d5^$e3bqlcJ(u u1-liGthb#1=>3*uH#Cgjk#z=rN_Lz`l=({8YD9|Zw}=YeU{SEJ?7sm8AXkI{ From ad2c7b3959ec1f422defc1dd18e50cbb385c8c04 Mon Sep 17 00:00:00 2001 From: Alexander Kiselev Date: Wed, 21 Mar 2018 17:15:33 +0300 Subject: [PATCH 37/62] Add README --- bench/README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 bench/README.md diff --git a/bench/README.md b/bench/README.md new file mode 100644 index 00000000..aed6ee9b --- /dev/null +++ b/bench/README.md @@ -0,0 +1,14 @@ +# loggers + +Name | License | Lang. | Year | Platform | Compiler | Dependence | URL +--- | --- | --- | --- | --- | --- | --- | --- +Pantheios | BSD | C++ | 2017 | Windows, Linux, MacOSX | VC++, GCC(3.2+), Intel, Borland, Comeau, Digital Mars, Metrowerks | STLSoft | http://www.pantheios.org/
      http://blog.pantheios.org/
      https://github.com/synesissoftware/Pantheios
      http://www.pantheios.org/performance.html +Glog | 3-clause BSD| C++| 2017 | Windows, Linux, MacOSX | VC++, GCC, Clang, intel| Google gflags | https://github.com/google/glog +G3log | Public Domain | C++11 | 2018 | Windows, Linux, MacOSX, iPhoneOS | VC++, GCC, Clang, MinGW | None | https://github.com/KjellKod/g3log
      https://github.com/KjellKod/g3sinks
      https://kjellkod.wordpress.com/2014/08/16/presenting-g3log-the-next-version-of-the-next-generation-of-loggers/
      https://kjellkod.wordpress.com/2015/06/30/the-worlds-fastest-logger-vs-g3log/ +P7 | LGPL | C++, C, C#, Python | 2017 | Windows, Linux | VC++, GCC, Clang, MinGW | None | http://baical.net/p7.html +log4cpp | LGPL | C++ | 2017 | Windows, Linux, MacOSX | VC++, GCC, Sun CC, OpenVMS | Boost | http://log4cpp.sourceforge.net/ +log4cplus | 2-clause BSD or Apache 2 | C++ | 2017 | Windows, Linux, MacOSX, Android | VC++, GCC, Clang | Boost | https://github.com/log4cplus/log4cplus
      https://sourceforge.net/p/log4cplus/wiki/Home/ +Easylogging | MIT | C++11 | 2018 | Windows, Linux, MacOSX, iPhoneOS, Android | VC++, GCC, Clang, Intel, MinGW | None | https://github.com/muflihun/easyloggingpp +Spdlog | MIT | C++11 | 2018 | Windows, Linux, MacOSX, iPhoneOS, Android(logcat) | VC++, GCC, Clang, MinGW | None, Headers only library | https://github.com/gabime/spdlog
      https://github.com/fmtlib/fmt +Boost.Log v2 | Boost | C++ | 2016 | Windows, Linux, MacOSX, iPhoneOS, Android | VC++, GCC, Clang | Boost | https://github.com/boostorg/log
      http://www.boost.org/doc/libs/1_66_0/libs/log/doc/html/index.html +plog | MPL 2.0 | C++ | 2017 | Windows, Linux, MacOSX, iPhoneOS, Android | gcc, clang, msvc, mingw, mingw-w64, icc, c++builder | None, Headers only library | https://github.com/SergiusTheBest/plog From 93d41b2c0ecd0db7075e2386596ce39cb20546c9 Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 22 Mar 2018 20:35:49 +0200 Subject: [PATCH 38/62] fixed gcc warning about struct stat --- include/spdlog/details/os.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index e6b5cd2a..5a5dbde8 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -238,9 +238,7 @@ inline size_t filesize(FILE *f) int fd = fileno(f); // 64 bits(but not in osx or cygwin, where fstat64 is deprecated) #if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__) - struct stat64 st - { - }; + struct stat64 st; if (fstat64(fd, &st) == 0) { return static_cast(st.st_size); From c8610d9a86ae8b237895f7c2d6baa42cdf292d96 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 6 Apr 2018 02:24:07 +0300 Subject: [PATCH 39/62] support for color formatting --- bench/boost-bench-mt.cpp | 1 - bench/easylogging-bench-async.cpp | 2 +- bench/easylogging-bench-mt.cpp | 2 +- bench/easylogging-bench.cpp | 4 +-- bench/g3log-async.cpp | 5 +-- bench/glog-bench.cpp | 1 - bench/log4cplus-bench-mt.cpp | 14 ++++----- bench/log4cplus-bench.cpp | 12 +++---- bench/log4cpp-bench-mt.cpp | 12 +++---- bench/log4cpp-bench.cpp | 10 +++--- bench/p7-bench-mt.cpp | 23 ++++++-------- bench/p7-bench.cpp | 18 +++++------ bench/spdlog-async.cpp | 6 ++-- bench/spdlog-bench-mt.cpp | 2 +- include/spdlog/details/log_msg.h | 3 ++ include/spdlog/details/os.h | 2 +- .../spdlog/details/pattern_formatter_impl.h | 31 ++++++++++++++++++- include/spdlog/sinks/ansicolor_sink.h | 30 ++++++++++++------ 18 files changed, 105 insertions(+), 73 deletions(-) diff --git a/bench/boost-bench-mt.cpp b/bench/boost-bench-mt.cpp index 3a6eeea8..a076e6e4 100644 --- a/bench/boost-bench-mt.cpp +++ b/bench/boost-bench-mt.cpp @@ -82,6 +82,5 @@ int main(int argc, char *argv[]) std::cout << "Delta = " << deltaf << " seconds" << std::endl; std::cout << "Rate = " << rate << "/sec" << std::endl; - return 0; } diff --git a/bench/easylogging-bench-async.cpp b/bench/easylogging-bench-async.cpp index 81985a6a..e9b0dc84 100644 --- a/bench/easylogging-bench-async.cpp +++ b/bench/easylogging-bench-async.cpp @@ -11,8 +11,8 @@ #define ELPP_THREAD_SAFE #define ELPP_EXPERIMENTAL_ASYNC -#include "easylogging++.h" #include "easylogging++.cc" +#include "easylogging++.h" INITIALIZE_EASYLOGGINGPP using namespace std; diff --git a/bench/easylogging-bench-mt.cpp b/bench/easylogging-bench-mt.cpp index cfcf3348..7601d3c0 100644 --- a/bench/easylogging-bench-mt.cpp +++ b/bench/easylogging-bench-mt.cpp @@ -10,8 +10,8 @@ #include #define ELPP_THREAD_SAFE -#include "easylogging++.h" #include "easylogging++.cc" +#include "easylogging++.h" INITIALIZE_EASYLOGGINGPP using namespace std; diff --git a/bench/easylogging-bench.cpp b/bench/easylogging-bench.cpp index 06b66134..15c093d8 100644 --- a/bench/easylogging-bench.cpp +++ b/bench/easylogging-bench.cpp @@ -6,8 +6,8 @@ #include #include -#include "easylogging++.h" #include "easylogging++.cc" +#include "easylogging++.h" INITIALIZE_EASYLOGGINGPP int main(int, char *[]) @@ -21,7 +21,7 @@ int main(int, char *[]) el::Configurations conf("easyl.conf"); el::Loggers::reconfigureLogger("default", conf); - el::Logger* defaultLogger = el::Loggers::getLogger("default"); + el::Logger *defaultLogger = el::Loggers::getLogger("default"); auto start = clock::now(); for (int i = 0; i < howmany; ++i) diff --git a/bench/g3log-async.cpp b/bench/g3log-async.cpp index b5e15a2b..61ed72df 100644 --- a/bench/g3log-async.cpp +++ b/bench/g3log-async.cpp @@ -13,7 +13,8 @@ #include "g3log/logworker.hpp" using namespace std; -template std::string format(const T &value); +template +std::string format(const T &value); int main(int argc, char *argv[]) { @@ -27,7 +28,7 @@ int main(int argc, char *argv[]) int howmany = 1000000; auto worker = g3::LogWorker::createLogWorker(); - auto handle= worker->addDefaultLogger(argv[0], "logs"); + auto handle = worker->addDefaultLogger(argv[0], "logs"); g3::initializeLogging(worker.get()); std::atomic msg_counter{0}; diff --git a/bench/glog-bench.cpp b/bench/glog-bench.cpp index 6b4445a9..7469896c 100644 --- a/bench/glog-bench.cpp +++ b/bench/glog-bench.cpp @@ -8,7 +8,6 @@ #include "glog/logging.h" - int main(int, char *argv[]) { using namespace std::chrono; diff --git a/bench/log4cplus-bench-mt.cpp b/bench/log4cplus-bench-mt.cpp index 6acbf3fa..72e2681c 100644 --- a/bench/log4cplus-bench-mt.cpp +++ b/bench/log4cplus-bench-mt.cpp @@ -10,17 +10,17 @@ #include #include -#include "log4cplus/logger.h" #include "log4cplus/fileappender.h" -#include "log4cplus/layout.h" -#include "log4cplus/ndc.h" #include "log4cplus/helpers/loglog.h" #include "log4cplus/helpers/property.h" +#include "log4cplus/layout.h" +#include "log4cplus/logger.h" #include "log4cplus/loggingmacros.h" +#include "log4cplus/ndc.h" using namespace log4cplus; -int main(int argc, char * argv[]) +int main(int argc, char *argv[]) { using namespace std::chrono; using clock = steady_clock; @@ -32,13 +32,11 @@ int main(int argc, char * argv[]) int howmany = 1000000; log4cplus::initialize(); - SharedFileAppenderPtr append( - new FileAppender(LOG4CPLUS_TEXT("logs/log4cplus-bench-mt.log"), std::ios_base::trunc, - true, true)); + SharedFileAppenderPtr append(new FileAppender(LOG4CPLUS_TEXT("logs/log4cplus-bench-mt.log"), std::ios_base::trunc, true, true)); append->setName(LOG4CPLUS_TEXT("File")); log4cplus::tstring pattern = LOG4CPLUS_TEXT("%d{%Y-%m-%d %H:%M:%S.%Q}: %p - %m %n"); - append->setLayout( std::auto_ptr(new PatternLayout(pattern)) ); + append->setLayout(std::auto_ptr(new PatternLayout(pattern))); append->getloc(); Logger::getRoot().addAppender(SharedAppenderPtr(append.get())); diff --git a/bench/log4cplus-bench.cpp b/bench/log4cplus-bench.cpp index e522e85a..e738aecd 100644 --- a/bench/log4cplus-bench.cpp +++ b/bench/log4cplus-bench.cpp @@ -7,13 +7,13 @@ #include #include -#include "log4cplus/logger.h" #include "log4cplus/fileappender.h" -#include "log4cplus/layout.h" -#include "log4cplus/ndc.h" #include "log4cplus/helpers/loglog.h" #include "log4cplus/helpers/property.h" +#include "log4cplus/layout.h" +#include "log4cplus/logger.h" #include "log4cplus/loggingmacros.h" +#include "log4cplus/ndc.h" using namespace log4cplus; @@ -25,13 +25,11 @@ int main(int, char *[]) int howmany = 1000000; log4cplus::initialize(); - SharedFileAppenderPtr append( - new FileAppender(LOG4CPLUS_TEXT("logs/log4cplus-bench.log"), std::ios_base::trunc, - true, true)); + SharedFileAppenderPtr append(new FileAppender(LOG4CPLUS_TEXT("logs/log4cplus-bench.log"), std::ios_base::trunc, true, true)); append->setName(LOG4CPLUS_TEXT("File")); log4cplus::tstring pattern = LOG4CPLUS_TEXT("%d{%Y-%m-%d %H:%M:%S.%Q}: %p - %m %n"); - append->setLayout( std::auto_ptr(new PatternLayout(pattern)) ); + append->setLayout(std::auto_ptr(new PatternLayout(pattern))); append->getloc(); Logger::getRoot().addAppender(SharedAppenderPtr(append.get())); diff --git a/bench/log4cpp-bench-mt.cpp b/bench/log4cpp-bench-mt.cpp index dc6a5f58..b96b8e1b 100644 --- a/bench/log4cpp-bench-mt.cpp +++ b/bench/log4cpp-bench-mt.cpp @@ -10,15 +10,15 @@ #include #include -#include "log4cpp/Category.hh" #include "log4cpp/Appender.hh" +#include "log4cpp/BasicLayout.hh" +#include "log4cpp/Category.hh" #include "log4cpp/FileAppender.hh" #include "log4cpp/Layout.hh" -#include "log4cpp/BasicLayout.hh" -#include "log4cpp/Priority.hh" #include "log4cpp/PatternLayout.hh" +#include "log4cpp/Priority.hh" -int main(int argc, char * argv[]) +int main(int argc, char *argv[]) { using namespace std::chrono; using clock = steady_clock; @@ -29,12 +29,12 @@ int main(int argc, char * argv[]) int howmany = 1000000; - log4cpp::Appender *appender = new log4cpp::FileAppender("default", "logs/log4cpp-bench-mt.log"); + log4cpp::Appender *appender = new log4cpp::FileAppender("default", "logs/log4cpp-bench-mt.log"); log4cpp::PatternLayout *layout = new log4cpp::PatternLayout(); layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S.%l}: %p - %m %n"); appender->setLayout(layout); - log4cpp::Category& root = log4cpp::Category::getRoot(); + log4cpp::Category &root = log4cpp::Category::getRoot(); root.addAppender(appender); root.setPriority(log4cpp::Priority::INFO); diff --git a/bench/log4cpp-bench.cpp b/bench/log4cpp-bench.cpp index a21526c8..75029817 100644 --- a/bench/log4cpp-bench.cpp +++ b/bench/log4cpp-bench.cpp @@ -7,13 +7,13 @@ #include #include -#include "log4cpp/Category.hh" #include "log4cpp/Appender.hh" +#include "log4cpp/BasicLayout.hh" +#include "log4cpp/Category.hh" #include "log4cpp/FileAppender.hh" #include "log4cpp/Layout.hh" -#include "log4cpp/BasicLayout.hh" -#include "log4cpp/Priority.hh" #include "log4cpp/PatternLayout.hh" +#include "log4cpp/Priority.hh" int main(int, char *[]) { @@ -22,12 +22,12 @@ int main(int, char *[]) int howmany = 1000000; - log4cpp::Appender *appender = new log4cpp::FileAppender("default", "logs/log4cpp-bench.log"); + log4cpp::Appender *appender = new log4cpp::FileAppender("default", "logs/log4cpp-bench.log"); log4cpp::PatternLayout *layout = new log4cpp::PatternLayout(); layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S.%l}: %p - %m %n"); appender->setLayout(layout); - log4cpp::Category& root = log4cpp::Category::getRoot(); + log4cpp::Category &root = log4cpp::Category::getRoot(); root.addAppender(appender); root.setPriority(log4cpp::Priority::INFO); diff --git a/bench/p7-bench-mt.cpp b/bench/p7-bench-mt.cpp index a3195208..996922c9 100644 --- a/bench/p7-bench-mt.cpp +++ b/bench/p7-bench-mt.cpp @@ -5,15 +5,14 @@ #include #include +#include #include +#include #include #include -#include -#include #include "P7_Trace.h" - int main(int argc, char *argv[]) { using namespace std::chrono; @@ -27,10 +26,9 @@ int main(int argc, char *argv[]) IP7_Trace::hModule module = NULL; - //create P7 client object - std::unique_ptr> client( - P7_Create_Client(TM("/P7.Pool=1024 /P7.Sink=FileTxt /P7.Dir=logs/p7-bench-mt")), - [&](IP7_Client *ptr){ + // create P7 client object + std::unique_ptr> client( + P7_Create_Client(TM("/P7.Pool=1024 /P7.Sink=FileTxt /P7.Dir=logs/p7-bench-mt")), [&](IP7_Client *ptr) { if (ptr) ptr->Release(); }); @@ -41,10 +39,9 @@ int main(int argc, char *argv[]) return 1; } - //create P7 trace object 1 - std::unique_ptr> trace( - P7_Create_Trace(client.get(), TM("Trace channel 1")), - [&](IP7_Trace *ptr){ + // create P7 trace object 1 + std::unique_ptr> trace( + P7_Create_Trace(client.get(), TM("Trace channel 1")), [&](IP7_Trace *ptr) { if (ptr) ptr->Release(); }); @@ -65,7 +62,7 @@ int main(int argc, char *argv[]) for (int t = 0; t < thread_count; ++t) { threads.push_back(std::thread([&]() { - trace->Register_Thread(TM("Application"), t+1); + trace->Register_Thread(TM("Application"), t + 1); while (true) { int counter = ++msg_counter; @@ -73,7 +70,7 @@ int main(int argc, char *argv[]) break; trace->P7_INFO(module, TM("p7 message #%d: This is some text for your pleasure"), counter); } - trace->Register_Thread(TM("Application"), t+1); + trace->Register_Thread(TM("Application"), t + 1); })); } diff --git a/bench/p7-bench.cpp b/bench/p7-bench.cpp index 15513ca5..25c39b03 100644 --- a/bench/p7-bench.cpp +++ b/bench/p7-bench.cpp @@ -4,13 +4,12 @@ // #include +#include #include #include -#include #include "P7_Trace.h" - int main(int, char *[]) { using namespace std::chrono; @@ -20,10 +19,9 @@ int main(int, char *[]) IP7_Trace::hModule module = NULL; - //create P7 client object - std::unique_ptr> client( - P7_Create_Client(TM("/P7.Pool=1024 /P7.Sink=FileTxt /P7.Dir=logs/p7-bench")), - [&](IP7_Client *ptr){ + // create P7 client object + std::unique_ptr> client( + P7_Create_Client(TM("/P7.Pool=1024 /P7.Sink=FileTxt /P7.Dir=logs/p7-bench")), [&](IP7_Client *ptr) { if (ptr) ptr->Release(); }); @@ -34,10 +32,9 @@ int main(int, char *[]) return 1; } - //create P7 trace object 1 - std::unique_ptr> trace( - P7_Create_Trace(client.get(), TM("Trace channel 1")), - [&](IP7_Trace *ptr){ + // create P7 trace object 1 + std::unique_ptr> trace( + P7_Create_Trace(client.get(), TM("Trace channel 1")), [&](IP7_Trace *ptr) { if (ptr) ptr->Release(); }); @@ -55,7 +52,6 @@ int main(int, char *[]) for (int i = 0; i < howmany; ++i) trace->P7_INFO(module, TM("p7 message #%d: This is some text for your pleasure"), i); - duration delta = clock::now() - start; float deltaf = delta.count(); auto rate = howmany / deltaf; diff --git a/bench/spdlog-async.cpp b/bench/spdlog-async.cpp index e1d1a95f..e8b70009 100644 --- a/bench/spdlog-async.cpp +++ b/bench/spdlog-async.cpp @@ -5,8 +5,8 @@ #include #include -#include #include +#include #include #include @@ -36,7 +36,7 @@ int main(int argc, char *argv[]) run = false; })); - while(run) + while (run) { std::atomic msg_counter{0}; std::vector threads; @@ -68,7 +68,7 @@ int main(int argc, char *argv[]) std::cout << "Threads: " << thread_count << std::endl; std::cout << "Delta = " << std::fixed << deltaf << " seconds" << std::endl; std::cout << "Rate = " << std::fixed << rate << "/sec" << std::endl; - } //while + } // while stoper.join(); diff --git a/bench/spdlog-bench-mt.cpp b/bench/spdlog-bench-mt.cpp index b4948e73..62dd9cc7 100644 --- a/bench/spdlog-bench-mt.cpp +++ b/bench/spdlog-bench-mt.cpp @@ -5,8 +5,8 @@ #include #include -#include #include +#include #include #include diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 9a03318d..1d079aaf 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -40,6 +40,9 @@ struct log_msg fmt::MemoryWriter raw; fmt::MemoryWriter formatted; size_t msg_id{0}; + // wrap this range with color codes + size_t color_range_start{0}; + size_t color_range_end{0}; }; } // namespace details } // namespace spdlog diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 5a5dbde8..2eeeeb38 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -238,7 +238,7 @@ inline size_t filesize(FILE *f) int fd = fileno(f); // 64 bits(but not in osx or cygwin, where fstat64 is deprecated) #if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__) - struct stat64 st; + struct stat64 st; if (fstat64(fd, &st) == 0) { return static_cast(st.st_size); diff --git a/include/spdlog/details/pattern_formatter_impl.h b/include/spdlog/details/pattern_formatter_impl.h index 9aa634e7..d8b92f9b 100644 --- a/include/spdlog/details/pattern_formatter_impl.h +++ b/include/spdlog/details/pattern_formatter_impl.h @@ -421,7 +421,24 @@ private: std::string _str; }; +// set the color range. expect it to be in the form of "%^colored text%$" +class start_color_formatter SPDLOG_FINAL : public flag_formatter +{ + void format(details::log_msg &msg, const std::tm &) override + { + msg.color_range_start = msg.formatted.size(); + } +}; +class stop_color_formatter SPDLOG_FINAL : public flag_formatter +{ + void format(details::log_msg &msg, const std::tm &) override + { + msg.color_range_end = msg.formatted.size(); + } +}; + // Full info formatter + // pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v class full_formatter SPDLOG_FINAL : public flag_formatter { @@ -462,8 +479,13 @@ class full_formatter SPDLOG_FINAL : public flag_formatter msg.formatted << '[' << *msg.logger_name << "] "; #endif - msg.formatted << '[' << level::to_str(msg.level) << "] "; + const char *level_name = level::to_str(msg.level); + size_t level_name_size = strlen(level_name); + msg.formatted << '[' << fmt::StringRef(level_name, level_name_size) << "] "; msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size()); + // wrap the level with color + msg.color_range_start = 37; + msg.color_range_end = 37 + level_name_size; } }; @@ -491,6 +513,7 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string &patter { _formatters.push_back(std::move(user_chars)); } + // if( if (++it != end) { handle_flag(*it); @@ -644,6 +667,12 @@ inline void spdlog::pattern_formatter::handle_flag(char flag) case ('i'): _formatters.emplace_back(new details::i_formatter()); break; + case ('^'): + _formatters.emplace_back(new details::start_color_formatter()); + break; + case ('$'): + _formatters.emplace_back(new details::stop_color_formatter()); + break; default: // Unknown flag appears as is _formatters.emplace_back(new details::ch_formatter('%')); diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index 9e7f1a59..8f086c8e 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -28,9 +28,9 @@ public: : target_file_(file) { should_do_colors_ = details::os::in_terminal(file) && details::os::is_color_terminal(); - colors_[level::trace] = cyan; + colors_[level::trace] = magenta; colors_[level::debug] = cyan; - colors_[level::info] = reset; + colors_[level::info] = green; colors_[level::warn] = yellow + bold; colors_[level::err] = red + bold; colors_[level::critical] = bold + on_red; @@ -83,17 +83,20 @@ protected: { // Wrap the originally formatted message in color codes. // If color is not supported in the terminal, log as is instead. - if (should_do_colors_) + if (should_do_colors_ && msg.color_range_end > msg.color_range_start) { - const std::string &prefix = colors_[msg.level]; - fwrite(prefix.data(), sizeof(char), prefix.size(), target_file_); - fwrite(msg.formatted.data(), sizeof(char), msg.formatted.size(), target_file_); - fwrite(reset.data(), sizeof(char), reset.size(), target_file_); - fwrite(clear_line.data(), sizeof(char), clear_line.size(), target_file_); + // before color range + _print_range(msg, 0, msg.color_range_start); + // in color range + _print_ccode(colors_[msg.level]); + _print_range(msg, msg.color_range_start, msg.color_range_end); + _print_ccode(reset); + // after color range + _print_range(msg, msg.color_range_end, msg.formatted.size()); } else { - fwrite(msg.formatted.data(), sizeof(char), msg.formatted.size(), target_file_); + _print_range(msg, 0, msg.formatted.size()); } _flush(); } @@ -103,6 +106,15 @@ protected: fflush(target_file_); } +private: + void _print_ccode(const std::string &color_code) + { + fwrite(color_code.data(), sizeof(char), color_code.size(), target_file_); + } + void _print_range(const details::log_msg &msg, size_t start, size_t end) + { + fwrite(msg.formatted.data() + start, sizeof(char), end - start, target_file_); + } FILE *target_file_; bool should_do_colors_; std::unordered_map colors_; From d040ab93ea4e372998048c8b270aaffd6e5ce663 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 6 Apr 2018 03:04:18 +0300 Subject: [PATCH 40/62] wincolor color formatting support --- example/example.cpp | 4 ++-- include/spdlog/sinks/ansicolor_sink.h | 2 +- include/spdlog/sinks/wincolor_sink.h | 32 ++++++++++++++++++++++----- 3 files changed, 29 insertions(+), 9 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index b1b2e32f..90abd916 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -58,8 +58,8 @@ int main(int, char *[]) daily_logger->info(123.44); // Customize msg format for all messages - spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***"); - rotating_logger->info("This is another message with custom format"); + spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v"); + console->info("This a message with custom format (and custom color range between the '%^' and '%$')"); // Runtime log levels spd::set_level(spd::level::info); // Set global log level to info diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index 8f086c8e..e74389c9 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -28,7 +28,7 @@ public: : target_file_(file) { should_do_colors_ = details::os::in_terminal(file) && details::os::is_color_terminal(); - colors_[level::trace] = magenta; + colors_[level::trace] = white; colors_[level::debug] = cyan; colors_[level::info] = green; colors_[level::warn] = yellow + bold; diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index 60f4286f..d21151db 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -25,6 +25,7 @@ class wincolor_sink : public base_sink public: const WORD BOLD = FOREGROUND_INTENSITY; const WORD RED = FOREGROUND_RED; + const WORD GREEN = FOREGROUND_GREEN; const WORD CYAN = FOREGROUND_GREEN | FOREGROUND_BLUE; const WORD WHITE = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; const WORD YELLOW = FOREGROUND_RED | FOREGROUND_GREEN; @@ -32,9 +33,9 @@ public: wincolor_sink(HANDLE std_handle) : out_handle_(std_handle) { - colors_[level::trace] = CYAN; + colors_[level::trace] = WHITE; colors_[level::debug] = CYAN; - colors_[level::info] = WHITE | BOLD; + colors_[level::info] = GREEN; colors_[level::warn] = YELLOW | BOLD; colors_[level::err] = RED | BOLD; // red bold colors_[level::critical] = BACKGROUND_RED | WHITE | BOLD; // white bold on red background @@ -59,10 +60,22 @@ public: protected: void _sink_it(const details::log_msg &msg) override { - auto color = colors_[msg.level]; - auto orig_attribs = set_console_attribs(color); - WriteConsoleA(out_handle_, msg.formatted.data(), static_cast(msg.formatted.size()), nullptr, nullptr); - SetConsoleTextAttribute(out_handle_, orig_attribs); // reset to orig colors + if (msg.color_range_end > msg.color_range_start) + { + // before color range + _print_range(msg, 0, msg.color_range_start); + + // in color range + auto orig_attribs = set_console_attribs(colors_[msg.level]); + _print_range(msg, msg.color_range_start, msg.color_range_end); + ::SetConsoleTextAttribute(out_handle_, orig_attribs); // reset to orig colors + // after color range + _print_range(msg, msg.color_range_end, msg.formatted.size()); + } + else // print without colors if color range is invalid + { + _print_range(msg, 0, msg.formatted.size()); + } } void _flush() override @@ -86,6 +99,13 @@ private: SetConsoleTextAttribute(out_handle_, attribs | back_color); return orig_buffer_info.wAttributes; // return orig attribs } + + // print a range of formatted message to console + void _print_range(const details::log_msg &msg, size_t start, size_t end) + { + DWORD size = static_cast(end - start); + WriteConsoleA(out_handle_, msg.formatted.data() + start, size, nullptr, nullptr); + } }; // From 2f7fdf266330f39b9f4556053573ed8236727005 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 6 Apr 2018 03:06:41 +0300 Subject: [PATCH 41/62] wincolor color formatting support --- example/example.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 90abd916..ea6e5f06 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -59,8 +59,9 @@ int main(int, char *[]) // Customize msg format for all messages spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v"); - console->info("This a message with custom format (and custom color range between the '%^' and '%$')"); - + console->info("This an info message with custom format (and custom color range between the '%^' and '%$')"); + console->error("This an error message with custom format (and custom color range between the '%^' and '%$')"); + // Runtime log levels spd::set_level(spd::level::info); // Set global log level to info console->debug("This message should not be displayed!"); From 3452892f76a9794f1200d41d95b7c39b4bacc464 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 6 Apr 2018 03:22:27 +0300 Subject: [PATCH 42/62] minor renaming --- include/spdlog/details/pattern_formatter_impl.h | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/include/spdlog/details/pattern_formatter_impl.h b/include/spdlog/details/pattern_formatter_impl.h index d8b92f9b..a7259e96 100644 --- a/include/spdlog/details/pattern_formatter_impl.h +++ b/include/spdlog/details/pattern_formatter_impl.h @@ -421,15 +421,15 @@ private: std::string _str; }; -// set the color range. expect it to be in the form of "%^colored text%$" -class start_color_formatter SPDLOG_FINAL : public flag_formatter +// mark the color range. expect it to be in the form of "%^colored text%$" +class color_start_formatter SPDLOG_FINAL : public flag_formatter { void format(details::log_msg &msg, const std::tm &) override { msg.color_range_start = msg.formatted.size(); } }; -class stop_color_formatter SPDLOG_FINAL : public flag_formatter +class color_stop_formatter SPDLOG_FINAL : public flag_formatter { void format(details::log_msg &msg, const std::tm &) override { @@ -438,7 +438,6 @@ class stop_color_formatter SPDLOG_FINAL : public flag_formatter }; // Full info formatter - // pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v class full_formatter SPDLOG_FINAL : public flag_formatter { @@ -667,11 +666,13 @@ inline void spdlog::pattern_formatter::handle_flag(char flag) case ('i'): _formatters.emplace_back(new details::i_formatter()); break; + case ('^'): - _formatters.emplace_back(new details::start_color_formatter()); + _formatters.emplace_back(new details::color_start_formatter()); break; + case ('$'): - _formatters.emplace_back(new details::stop_color_formatter()); + _formatters.emplace_back(new details::color_stop_formatter()); break; default: // Unknown flag appears as is From 644c81b9fb845a940044bc4afeb9a3dd2e4be875 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 6 Apr 2018 03:42:24 +0300 Subject: [PATCH 43/62] Added color ranges to formatter tests --- tests/test_pattern_formatter.cpp | 65 +++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 2 deletions(-) diff --git a/tests/test_pattern_formatter.cpp b/tests/test_pattern_formatter.cpp index 5c2be1f2..644cb80e 100644 --- a/tests/test_pattern_formatter.cpp +++ b/tests/test_pattern_formatter.cpp @@ -7,8 +7,10 @@ static std::string log_to_str(const std::string &msg, const std::shared_ptr(oss); spdlog::logger oss_logger("pattern_tester", oss_sink); oss_logger.set_level(spdlog::level::info); - if (formatter) - oss_logger.set_formatter(formatter); + if (formatter) + { + oss_logger.set_formatter(formatter); + } oss_logger.info(msg); return oss.str(); } @@ -61,3 +63,62 @@ TEST_CASE("date MM/DD/YY ", "[pattern_formatter]") << (now_tm.tm_year + 1900) % 1000 << " Some message\n"; REQUIRE(log_to_str("Some message", formatter) == oss.str()); } + +TEST_CASE("color range test1", "[pattern_formatter]") +{ + auto formatter = std::make_shared("%^%v%$", spdlog::pattern_time_type::local, "\n"); + spdlog::details::log_msg msg; + msg.raw << "Hello"; + formatter->format(msg); + REQUIRE(msg.color_range_start == 0); + REQUIRE(msg.color_range_end == 5); + REQUIRE(log_to_str("hello", formatter) == "hello\n"); +} + +TEST_CASE("color range test2", "[pattern_formatter]") +{ + auto formatter = std::make_shared("%^%$", spdlog::pattern_time_type::local, "\n"); + spdlog::details::log_msg msg; + formatter->format(msg); + REQUIRE(msg.color_range_start == 0); + REQUIRE(msg.color_range_end == 0); + REQUIRE(log_to_str("", formatter) == "\n"); +} + +TEST_CASE("color range test3", "[pattern_formatter]") +{ + auto formatter = std::make_shared("%^***%$"); + spdlog::details::log_msg msg; + formatter->format(msg); + REQUIRE(msg.color_range_start == 0); + 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"); + spdlog::details::log_msg msg; + msg.raw << "ignored"; + formatter->format(msg); + REQUIRE(msg.color_range_start == 2); + REQUIRE(msg.color_range_end == 5); + REQUIRE(log_to_str("ignored", formatter) == "XXYYY\n"); +} + +TEST_CASE("color range test5", "[pattern_formatter]") +{ + auto formatter = std::make_shared("**%^"); + spdlog::details::log_msg msg; + formatter->format(msg); + REQUIRE(msg.color_range_start == 2); + REQUIRE(msg.color_range_end == 0); +} + +TEST_CASE("color range test6", "[pattern_formatter]") +{ + auto formatter = std::make_shared("**%$"); + spdlog::details::log_msg msg; + formatter->format(msg); + REQUIRE(msg.color_range_start == 0); + REQUIRE(msg.color_range_end == 2); +} From 21d437fbf54e86a39570296643f64a227576b9e2 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Fri, 6 Apr 2018 04:04:50 +0300 Subject: [PATCH 44/62] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 73347139..940b61ff 100644 --- a/README.md +++ b/README.md @@ -120,8 +120,9 @@ int main(int, char*[]) daily_logger->info(123.44); // Customize msg format for all messages - spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***"); - rotating_logger->info("This is another message with custom format"); + spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v"); + console->info("This an info message with custom format (and custom color range between the '%^' and '%$')"); + console->error("This an error message with custom format (and custom color range between the '%^' and '%$')"); // Runtime log levels From 4abe40354488bbd14bc677cce6393cb32de629d5 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Fri, 6 Apr 2018 04:05:23 +0300 Subject: [PATCH 45/62] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 940b61ff..1146b176 100644 --- a/README.md +++ b/README.md @@ -120,11 +120,10 @@ int main(int, char*[]) daily_logger->info(123.44); // Customize msg format for all messages - spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v"); + spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v"); console->info("This an info message with custom format (and custom color range between the '%^' and '%$')"); console->error("This an error message with custom format (and custom color range between the '%^' and '%$')"); - // Runtime log levels spd::set_level(spd::level::info); //Set global log level to info console->debug("This message should not be displayed!"); From 1dea46e1abcaffa5ffc9f343af86a7c853b2a09c Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 6 Apr 2018 04:06:02 +0300 Subject: [PATCH 46/62] code formatting --- example/example.cpp | 4 +- include/spdlog/sinks/wincolor_sink.h | 46 ++++++++-------- tests/test_pattern_formatter.cpp | 80 ++++++++++++++-------------- 3 files changed, 65 insertions(+), 65 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index ea6e5f06..0597ec75 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -60,8 +60,8 @@ int main(int, char *[]) // Customize msg format for all messages spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v"); console->info("This an info message with custom format (and custom color range between the '%^' and '%$')"); - console->error("This an error message with custom format (and custom color range between the '%^' and '%$')"); - + console->error("This an error message with custom format (and custom color range between the '%^' and '%$')"); + // Runtime log levels spd::set_level(spd::level::info); // Set global log level to info console->debug("This message should not be displayed!"); diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index d21151db..402fa121 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -25,7 +25,7 @@ class wincolor_sink : public base_sink public: const WORD BOLD = FOREGROUND_INTENSITY; const WORD RED = FOREGROUND_RED; - const WORD GREEN = FOREGROUND_GREEN; + const WORD GREEN = FOREGROUND_GREEN; const WORD CYAN = FOREGROUND_GREEN | FOREGROUND_BLUE; const WORD WHITE = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; const WORD YELLOW = FOREGROUND_RED | FOREGROUND_GREEN; @@ -60,22 +60,22 @@ public: protected: void _sink_it(const details::log_msg &msg) override { - if (msg.color_range_end > msg.color_range_start) - { - // before color range - _print_range(msg, 0, msg.color_range_start); - - // in color range - auto orig_attribs = set_console_attribs(colors_[msg.level]); - _print_range(msg, msg.color_range_start, msg.color_range_end); - ::SetConsoleTextAttribute(out_handle_, orig_attribs); // reset to orig colors - // after color range - _print_range(msg, msg.color_range_end, msg.formatted.size()); - } - else // print without colors if color range is invalid - { - _print_range(msg, 0, msg.formatted.size()); - } + if (msg.color_range_end > msg.color_range_start) + { + // before color range + _print_range(msg, 0, msg.color_range_start); + + // in color range + auto orig_attribs = set_console_attribs(colors_[msg.level]); + _print_range(msg, msg.color_range_start, msg.color_range_end); + ::SetConsoleTextAttribute(out_handle_, orig_attribs); // reset to orig colors + // after color range + _print_range(msg, msg.color_range_end, msg.formatted.size()); + } + else // print without colors if color range is invalid + { + _print_range(msg, 0, msg.formatted.size()); + } } void _flush() override @@ -100,12 +100,12 @@ private: return orig_buffer_info.wAttributes; // return orig attribs } - // print a range of formatted message to console - void _print_range(const details::log_msg &msg, size_t start, size_t end) - { - DWORD size = static_cast(end - start); - WriteConsoleA(out_handle_, msg.formatted.data() + start, size, nullptr, nullptr); - } + // print a range of formatted message to console + void _print_range(const details::log_msg &msg, size_t start, size_t end) + { + DWORD size = static_cast(end - start); + WriteConsoleA(out_handle_, msg.formatted.data() + start, size, nullptr, nullptr); + } }; // diff --git a/tests/test_pattern_formatter.cpp b/tests/test_pattern_formatter.cpp index 644cb80e..c6700041 100644 --- a/tests/test_pattern_formatter.cpp +++ b/tests/test_pattern_formatter.cpp @@ -7,10 +7,10 @@ static std::string log_to_str(const std::string &msg, const std::shared_ptr(oss); spdlog::logger oss_logger("pattern_tester", oss_sink); oss_logger.set_level(spdlog::level::info); - if (formatter) - { - oss_logger.set_formatter(formatter); - } + if (formatter) + { + oss_logger.set_formatter(formatter); + } oss_logger.info(msg); return oss.str(); } @@ -65,60 +65,60 @@ TEST_CASE("date MM/DD/YY ", "[pattern_formatter]") } TEST_CASE("color range test1", "[pattern_formatter]") -{ - auto formatter = std::make_shared("%^%v%$", spdlog::pattern_time_type::local, "\n"); - spdlog::details::log_msg msg; - msg.raw << "Hello"; - formatter->format(msg); - REQUIRE(msg.color_range_start == 0); - REQUIRE(msg.color_range_end == 5); - REQUIRE(log_to_str("hello", formatter) == "hello\n"); +{ + auto formatter = std::make_shared("%^%v%$", spdlog::pattern_time_type::local, "\n"); + spdlog::details::log_msg msg; + msg.raw << "Hello"; + formatter->format(msg); + REQUIRE(msg.color_range_start == 0); + REQUIRE(msg.color_range_end == 5); + REQUIRE(log_to_str("hello", formatter) == "hello\n"); } TEST_CASE("color range test2", "[pattern_formatter]") { - auto formatter = std::make_shared("%^%$", spdlog::pattern_time_type::local, "\n"); - spdlog::details::log_msg msg; - formatter->format(msg); - REQUIRE(msg.color_range_start == 0); - REQUIRE(msg.color_range_end == 0); - REQUIRE(log_to_str("", formatter) == "\n"); + auto formatter = std::make_shared("%^%$", spdlog::pattern_time_type::local, "\n"); + spdlog::details::log_msg msg; + formatter->format(msg); + REQUIRE(msg.color_range_start == 0); + REQUIRE(msg.color_range_end == 0); + REQUIRE(log_to_str("", formatter) == "\n"); } TEST_CASE("color range test3", "[pattern_formatter]") { - auto formatter = std::make_shared("%^***%$"); - spdlog::details::log_msg msg; - formatter->format(msg); - REQUIRE(msg.color_range_start == 0); - REQUIRE(msg.color_range_end == 3); + auto formatter = std::make_shared("%^***%$"); + spdlog::details::log_msg msg; + formatter->format(msg); + REQUIRE(msg.color_range_start == 0); + 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"); - spdlog::details::log_msg msg; - msg.raw << "ignored"; - formatter->format(msg); - REQUIRE(msg.color_range_start == 2); - REQUIRE(msg.color_range_end == 5); - REQUIRE(log_to_str("ignored", formatter) == "XXYYY\n"); + auto formatter = std::make_shared("XX%^YYY%$", spdlog::pattern_time_type::local, "\n"); + spdlog::details::log_msg msg; + msg.raw << "ignored"; + formatter->format(msg); + REQUIRE(msg.color_range_start == 2); + REQUIRE(msg.color_range_end == 5); + REQUIRE(log_to_str("ignored", formatter) == "XXYYY\n"); } TEST_CASE("color range test5", "[pattern_formatter]") { - auto formatter = std::make_shared("**%^"); - spdlog::details::log_msg msg; - formatter->format(msg); - REQUIRE(msg.color_range_start == 2); - REQUIRE(msg.color_range_end == 0); + auto formatter = std::make_shared("**%^"); + spdlog::details::log_msg msg; + formatter->format(msg); + REQUIRE(msg.color_range_start == 2); + REQUIRE(msg.color_range_end == 0); } TEST_CASE("color range test6", "[pattern_formatter]") { - auto formatter = std::make_shared("**%$"); - spdlog::details::log_msg msg; - formatter->format(msg); - REQUIRE(msg.color_range_start == 0); - REQUIRE(msg.color_range_end == 2); + auto formatter = std::make_shared("**%$"); + spdlog::details::log_msg msg; + formatter->format(msg); + REQUIRE(msg.color_range_start == 0); + REQUIRE(msg.color_range_end == 2); } From 309327187a397dae3db9c8766904fc02cc32c053 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 6 Apr 2018 04:36:22 +0300 Subject: [PATCH 47/62] Fixed example makefile for clang --- example/Makefile | 58 +++++++++++++++++++------------------- example/Makefile.clang | 64 +++++++++++++++++++++--------------------- example/Makefile.mingw | 64 +++++++++++++++++++++--------------------- 3 files changed, 93 insertions(+), 93 deletions(-) diff --git a/example/Makefile b/example/Makefile index 6d169e41..8b17c7f2 100644 --- a/example/Makefile +++ b/example/Makefile @@ -1,29 +1,29 @@ -CXX ?= g++ -CXXFLAGS = -CXX_FLAGS = -Wall -Wshadow -Wextra -pedantic -std=c++11 -pthread -I../include -CXX_RELEASE_FLAGS = -O3 -march=native -CXX_DEBUG_FLAGS= -g - - -all: example bench -debug: example-debug bench-debug - -example: example.cpp - $(CXX) example.cpp -o example $(CXX_FLAGS) $(CXX_RELEASE_FLAGS) $(CXXFLAGS) - -bench: bench.cpp - $(CXX) bench.cpp -o bench $(CXX_FLAGS) $(CXX_RELEASE_FLAGS) $(CXXFLAGS) - - -example-debug: example.cpp - $(CXX) example.cpp -o example-debug $(CXX_FLAGS) $(CXX_DEBUG_FLAGS) $(CXXFLAGS) - -bench-debug: bench.cpp - $(CXX) bench.cpp -o bench-debug $(CXX_FLAGS) $(CXX_DEBUG_FLAGS) $(CXXFLAGS) - -clean: - rm -f *.o logs/*.txt example example-debug bench bench-debug - - -rebuild: clean all -rebuild-debug: clean debug +CXX ?= g++ +CXXFLAGS = +CXX_FLAGS = -Wall -Wshadow -Wextra -pedantic -std=c++11 -pthread -I../include +CXX_RELEASE_FLAGS = -O3 -march=native +CXX_DEBUG_FLAGS= -g + + +all: example bench +debug: example-debug bench-debug + +example: example.cpp + $(CXX) example.cpp -o example $(CXX_FLAGS) $(CXX_RELEASE_FLAGS) $(CXXFLAGS) + +bench: bench.cpp + $(CXX) bench.cpp -o bench $(CXX_FLAGS) $(CXX_RELEASE_FLAGS) $(CXXFLAGS) + + +example-debug: example.cpp + $(CXX) example.cpp -o example-debug $(CXX_FLAGS) $(CXX_DEBUG_FLAGS) $(CXXFLAGS) + +bench-debug: bench.cpp + $(CXX) bench.cpp -o bench-debug $(CXX_FLAGS) $(CXX_DEBUG_FLAGS) $(CXXFLAGS) + +clean: + rm -f *.o logs/*.txt example example-debug bench bench-debug + + +rebuild: clean all +rebuild-debug: clean debug diff --git a/example/Makefile.clang b/example/Makefile.clang index 0ed004d0..78488446 100644 --- a/example/Makefile.clang +++ b/example/Makefile.clang @@ -1,32 +1,32 @@ -CXX ?= clang++ -CXXFLAGS = -march=native -Wall -Wextra -Wshadow -pedantic -std=c++11 -pthread -I../include -CXX_RELEASE_FLAGS = -O2 -CXX_DEBUG_FLAGS= -g - - -all: example bench -debug: example-debug bench-debug - -example: example.cpp - $(CXX) example.cpp -o example-clang $(CXXFLAGS) $(CXX_RELEASE_FLAGS) - -bench: bench.cpp - $(CXX) bench.cpp -o bench-clang $(CXXFLAGS) $(CXX_RELEASE_FLAGS) - - -example-debug: example.cpp - $(CXX) example.cpp -o example-clang-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS) - -bench-debug: bench.cpp - $(CXX) bench.cpp -o bench-clang-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS) - - - -clean: - rm -f *.o logs/*.txt example-clang example-clang-debug bench-clang bench-clang-debug - - -rebuild: clean all -rebuild-debug: clean debug - - +CXX = clang++ +CXXFLAGS = -march=native -Wall -Wextra -Wshadow -pedantic -std=c++11 -pthread -I../include +CXX_RELEASE_FLAGS = -O2 +CXX_DEBUG_FLAGS= -g + + +all: example bench +debug: example-debug bench-debug + +example: example.cpp + $(CXX) example.cpp -o example-clang $(CXXFLAGS) $(CXX_RELEASE_FLAGS) + +bench: bench.cpp + $(CXX) bench.cpp -o bench-clang $(CXXFLAGS) $(CXX_RELEASE_FLAGS) + + +example-debug: example.cpp + $(CXX) example.cpp -o example-clang-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS) + +bench-debug: bench.cpp + $(CXX) bench.cpp -o bench-clang-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS) + + + +clean: + rm -f *.o logs/*.txt example-clang example-clang-debug bench-clang bench-clang-debug + + +rebuild: clean all +rebuild-debug: clean debug + + diff --git a/example/Makefile.mingw b/example/Makefile.mingw index 5ee5ab6f..302e0722 100644 --- a/example/Makefile.mingw +++ b/example/Makefile.mingw @@ -1,32 +1,32 @@ -CXX ?= g++ -CXXFLAGS = -D_WIN32_WINNT=0x600 -march=native -Wall -Wextra -Wshadow -pedantic -std=gnu++0x -pthread -Wl,--no-as-needed -I../include -CXX_RELEASE_FLAGS = -O3 -CXX_DEBUG_FLAGS= -g - - -all: example bench -debug: example-debug bench-debug - -example: example.cpp - $(CXX) example.cpp -o example $(CXXFLAGS) $(CXX_RELEASE_FLAGS) - -bench: bench.cpp - $(CXX) bench.cpp -o bench $(CXXFLAGS) $(CXX_RELEASE_FLAGS) - - -example-debug: example.cpp - $(CXX) example.cpp -o example-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS) - -bench-debug: bench.cpp - $(CXX) bench.cpp -o bench-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS) - - - -clean: - rm -f *.o logs/*.txt example example-debug bench bench-debug - - -rebuild: clean all -rebuild-debug: clean debug - - +CXX ?= g++ +CXXFLAGS = -D_WIN32_WINNT=0x600 -march=native -Wall -Wextra -Wshadow -pedantic -std=gnu++0x -pthread -Wl,--no-as-needed -I../include +CXX_RELEASE_FLAGS = -O3 +CXX_DEBUG_FLAGS= -g + + +all: example bench +debug: example-debug bench-debug + +example: example.cpp + $(CXX) example.cpp -o example $(CXXFLAGS) $(CXX_RELEASE_FLAGS) + +bench: bench.cpp + $(CXX) bench.cpp -o bench $(CXXFLAGS) $(CXX_RELEASE_FLAGS) + + +example-debug: example.cpp + $(CXX) example.cpp -o example-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS) + +bench-debug: bench.cpp + $(CXX) bench.cpp -o bench-debug $(CXXFLAGS) $(CXX_DEBUG_FLAGS) + + + +clean: + rm -f *.o logs/*.txt example example-debug bench bench-debug + + +rebuild: clean all +rebuild-debug: clean debug + + From 64c2fe180b5d2d7d217672bc1a700ccfc329706d Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 8 Apr 2018 18:27:18 +0300 Subject: [PATCH 48/62] Fixed bug in wrapping colors around level name in default pattern --- include/spdlog/details/pattern_formatter_impl.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/include/spdlog/details/pattern_formatter_impl.h b/include/spdlog/details/pattern_formatter_impl.h index a7259e96..f1de628b 100644 --- a/include/spdlog/details/pattern_formatter_impl.h +++ b/include/spdlog/details/pattern_formatter_impl.h @@ -478,13 +478,13 @@ class full_formatter SPDLOG_FINAL : public flag_formatter msg.formatted << '[' << *msg.logger_name << "] "; #endif - const char *level_name = level::to_str(msg.level); - size_t level_name_size = strlen(level_name); - msg.formatted << '[' << fmt::StringRef(level_name, level_name_size) << "] "; - msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size()); - // wrap the level with color - msg.color_range_start = 37; - msg.color_range_end = 37 + level_name_size; + msg.formatted << '['; + // wrap the level name with color + msg.color_range_start = msg.formatted.size(); + msg.formatted << level::to_str(msg.level); + msg.color_range_end = msg.formatted.size(); + msg.formatted << "] " << fmt::StringRef(msg.raw.data(), msg.raw.size()); + } }; From b416685d6f601a12a9fd6428aa605a6f12330ef2 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Mon, 9 Apr 2018 02:06:33 +0300 Subject: [PATCH 49/62] Fix gcc warning on stat (32 bits) --- include/spdlog/details/os.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 2eeeeb38..cd3e702b 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -244,9 +244,8 @@ inline size_t filesize(FILE *f) return static_cast(st.st_size); } #else // unix 32 bits or cygwin - struct stat st - { - }; + struct stat st; + if (fstat(fd, &st) == 0) { return static_cast(st.st_size); From cfb450c059ceaccaf6289ac6d2ce98db84ef69a3 Mon Sep 17 00:00:00 2001 From: gabime Date: Mon, 9 Apr 2018 14:14:52 +0300 Subject: [PATCH 50/62] Fixed eol write in pattern_formatter_impl --- example/example.cpp | 10 ++++++++++ include/spdlog/details/pattern_formatter_impl.h | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/example/example.cpp b/example/example.cpp index 0597ec75..a55a7db6 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -26,8 +26,17 @@ int main(int, char *[]) { try { + spdlog::set_async_mode(1024); // Console logger with color auto console = spd::stdout_color_mt("console"); + + for (int i = 0; i < 2000; i++) + { + console->info("{} Hello thread pool!", i); + } + + return 0; + console->info("Welcome to spdlog!"); console->error("Some error message with arg{}..", 1); @@ -39,6 +48,7 @@ int main(int, char *[]) console->info("{:<30}", "left aligned"); spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function"); + return 0; // Create basic file logger (not rotated) auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt"); diff --git a/include/spdlog/details/pattern_formatter_impl.h b/include/spdlog/details/pattern_formatter_impl.h index f1de628b..b801221b 100644 --- a/include/spdlog/details/pattern_formatter_impl.h +++ b/include/spdlog/details/pattern_formatter_impl.h @@ -704,5 +704,5 @@ inline void spdlog::pattern_formatter::format(details::log_msg &msg) f->format(msg, tm_time); } // write eol - msg.formatted.write(_eol.data(), _eol.size()); + msg.formatted << _eol; } From d352aa0990493e66cc659cfc023f8e2f5e35968f Mon Sep 17 00:00:00 2001 From: gabime Date: Mon, 9 Apr 2018 15:11:42 +0300 Subject: [PATCH 51/62] Fixed example --- example/example.cpp | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index a55a7db6..0597ec75 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -26,17 +26,8 @@ int main(int, char *[]) { try { - spdlog::set_async_mode(1024); // Console logger with color auto console = spd::stdout_color_mt("console"); - - for (int i = 0; i < 2000; i++) - { - console->info("{} Hello thread pool!", i); - } - - return 0; - console->info("Welcome to spdlog!"); console->error("Some error message with arg{}..", 1); @@ -48,7 +39,6 @@ int main(int, char *[]) console->info("{:<30}", "left aligned"); spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function"); - return 0; // Create basic file logger (not rotated) auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt"); From e9bb008f157bb767381e4e47fb318a49386e3af2 Mon Sep 17 00:00:00 2001 From: gabime Date: Mon, 9 Apr 2018 15:12:51 +0300 Subject: [PATCH 52/62] Fixed example --- example/example.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 0597ec75..6144c065 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -59,8 +59,8 @@ int main(int, char *[]) // Customize msg format for all messages spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v"); - console->info("This an info message with custom format (and custom color range between the '%^' and '%$')"); - console->error("This an error message with custom format (and custom color range between the '%^' and '%$')"); + console->info("This an info message with custom format"); + console->error("This an error message with custom format"); // Runtime log levels spd::set_level(spd::level::info); // Set global log level to info From 3fdc7996db80019074b0753fee589de2260e5d76 Mon Sep 17 00:00:00 2001 From: gabime Date: Mon, 9 Apr 2018 15:14:13 +0300 Subject: [PATCH 53/62] code formatting --- include/spdlog/details/os.h | 2 +- include/spdlog/details/pattern_formatter_impl.h | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index cd3e702b..e48f8272 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -245,7 +245,7 @@ inline size_t filesize(FILE *f) } #else // unix 32 bits or cygwin struct stat st; - + if (fstat(fd, &st) == 0) { return static_cast(st.st_size); diff --git a/include/spdlog/details/pattern_formatter_impl.h b/include/spdlog/details/pattern_formatter_impl.h index b801221b..e3d70878 100644 --- a/include/spdlog/details/pattern_formatter_impl.h +++ b/include/spdlog/details/pattern_formatter_impl.h @@ -480,11 +480,10 @@ class full_formatter SPDLOG_FINAL : public flag_formatter msg.formatted << '['; // wrap the level name with color - msg.color_range_start = msg.formatted.size(); - msg.formatted << level::to_str(msg.level); - msg.color_range_end = msg.formatted.size(); + msg.color_range_start = msg.formatted.size(); + msg.formatted << level::to_str(msg.level); + msg.color_range_end = msg.formatted.size(); msg.formatted << "] " << fmt::StringRef(msg.raw.data(), msg.raw.size()); - } }; From 31ce7ef3a56ff8b9535d767ae6e927c244923ec0 Mon Sep 17 00:00:00 2001 From: Puasonych Date: Tue, 10 Apr 2018 16:57:29 +0300 Subject: [PATCH 54/62] Update .gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index b1a41919..be48891f 100644 --- a/.gitignore +++ b/.gitignore @@ -65,4 +65,5 @@ install_manifest.txt /tests/logs/* # idea -.idea/ \ No newline at end of file +.idea/ +.vscode/ \ No newline at end of file From 11c99892d7ae38966cde9115d9dcc0865fac65d8 Mon Sep 17 00:00:00 2001 From: Puasonych Date: Wed, 11 Apr 2018 11:40:34 +0300 Subject: [PATCH 55/62] Add new logger: step_logger --- include/spdlog/details/spdlog_impl.h | 13 ++++ include/spdlog/sinks/file_sinks.h | 92 ++++++++++++++++++++++++++++ include/spdlog/spdlog.h | 6 ++ tests/file_log.cpp | 65 ++++++++++++++++++++ 4 files changed, 176 insertions(+) diff --git a/include/spdlog/details/spdlog_impl.h b/include/spdlog/details/spdlog_impl.h index 4c363834..7d9195bc 100644 --- a/include/spdlog/details/spdlog_impl.h +++ b/include/spdlog/details/spdlog_impl.h @@ -83,6 +83,19 @@ inline std::shared_ptr spdlog::daily_logger_st( return create(logger_name, filename, hour, minute); } +// Create a file logger that creates new files with a specified increment +inline std::shared_ptr spdlog::step_logger_mt( + const std::string &logger_name, const filename_t &filename_fmt, unsigned seconds, size_t max_file_size) +{ + return create(logger_name, filename_fmt, seconds, max_file_size); +} + +inline std::shared_ptr spdlog::step_logger_st( + const std::string &logger_name, const filename_t &filename_fmt, unsigned seconds, size_t max_file_size) +{ + return create(logger_name, filename_fmt, seconds, max_file_size); +} + // // stdout/stderr loggers // diff --git a/include/spdlog/sinks/file_sinks.h b/include/spdlog/sinks/file_sinks.h index 109c493a..407c5b83 100644 --- a/include/spdlog/sinks/file_sinks.h +++ b/include/spdlog/sinks/file_sinks.h @@ -251,5 +251,97 @@ private: using daily_file_sink_mt = daily_file_sink; using daily_file_sink_st = daily_file_sink; +/* + * Default generator of step log file names. + */ +struct default_step_file_name_calculator +{ + // Create filename for the form filename_YYYY-MM-DD_hh-mm-ss.ext + static std::tuple calc_filename(const filename_t &filename) + { + std::tm tm = spdlog::details::os::localtime(); + filename_t basename, ext; + std::tie(basename, ext) = details::file_helper::split_by_extenstion(filename); + std::conditional::value, fmt::MemoryWriter, fmt::WMemoryWriter>::type w; + w.write(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}-{:02d}-{:02d}"), basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec); + return std::make_tuple(w.str(), ext); + } +}; + +/* + * Rotating file sink based on size and a specified time step + */ +template +class step_file_sink SPDLOG_FINAL : public base_sink +{ +public: + step_file_sink(filename_t base_filename, unsigned step_seconds, std::size_t max_size) + : _base_filename(std::move(base_filename)) + , _step_seconds(step_seconds) + , _max_size(max_size) + { + _tp = _next_tp(); + std::tie(_current_filename, _ext) = FileNameCalc::calc_filename(_base_filename); + _file_helper.open(_current_filename); + _current_size = _file_helper.size(); // expensive. called only once + } + +protected: + void _sink_it(const details::log_msg &msg) override + { + _current_size += msg.formatted.size(); + if (std::chrono::system_clock::now() >= _tp || _current_size > _max_size) + { + close_current_file(); + + std::tie(_current_filename, std::ignore) = FileNameCalc::calc_filename(_base_filename); + _file_helper.open(_current_filename); + _tp = _next_tp(); + _current_size = msg.formatted.size(); + } + _file_helper.write(msg); + } + + void _flush() override + { + _file_helper.flush(); + close_current_file(); + } + +private: + std::chrono::system_clock::time_point _next_tp() + { + return std::chrono::system_clock::now() + _step_seconds; + } + + void close_current_file() + { + using details::os::filename_to_str; + + filename_t src =_current_filename; + filename_t target = _current_filename + _ext; + + if (details::file_helper::file_exists(src) && details::os::rename(src, target) != 0) + { + throw spdlog_ex("step_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno); + } + } + + filename_t _base_filename; + std::chrono::seconds _step_seconds; + std::size_t _max_size; + + std::chrono::system_clock::time_point _tp; + filename_t _current_filename; + filename_t _ext; + std::size_t _current_size; + + details::file_helper _file_helper; +}; + +using step_file_sink_mt = step_file_sink; +using step_file_sink_st = step_file_sink; + } // namespace sinks } // namespace spdlog diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 21f5951b..f65fe57e 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -91,6 +91,12 @@ std::shared_ptr rotating_logger_st( std::shared_ptr daily_logger_mt(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0); std::shared_ptr daily_logger_st(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0); +// +// Create a file logger which creates new files with a specified time step and fixed file size: +// +std::shared_ptr step_logger_mt(const std::string &logger_name, const filename_t &filename, unsigned seconds = 60, size_t max_file_size = std::numeric_limits::max()); +std::shared_ptr step_logger_st(const std::string &logger_name, const filename_t &filename, unsigned seconds = 60, size_t max_file_size = std::numeric_limits::max()); + // // Create and register stdout/stderr loggers // diff --git a/tests/file_log.cpp b/tests/file_log.cpp index e20071a3..afcac255 100644 --- a/tests/file_log.cpp +++ b/tests/file_log.cpp @@ -179,6 +179,71 @@ TEST_CASE("daily_logger with custom calculator", "[daily_logger_custom]]") REQUIRE(count_lines(filename) == 10); } +TEST_CASE("step_logger", "[step_logger]]") +{ + prepare_logdir(); + // calculate filename (time based) + std::string basename = "logs/step_log"; + std::tm tm = spdlog::details::os::localtime(); + fmt::MemoryWriter w; + w.write("{}_{:04d}-{:02d}-{:02d}_{:02d}-{:02d}-{:02d}", basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); + + auto logger = spdlog::step_logger_mt("logger", basename, 60); + logger->flush_on(spdlog::level::info); + for (int i = 0; i < 10; ++i) + { +#if !defined(SPDLOG_FMT_PRINTF) + logger->info("Test message {}", i); +#else + logger->info("Test message %d", i); +#endif + } + + auto filename = w.str(); + REQUIRE(count_lines(filename) == 10); +} + +struct custom_step_file_name_calculator +{ + static std::tuple calc_filename(const spdlog::filename_t &filename) + { + std::tm tm = spdlog::details::os::localtime(); + spdlog::filename_t basename, ext; + std::tie(basename, ext) = spdlog::details::file_helper::split_by_extenstion(filename); + std::conditional::value, fmt::MemoryWriter, fmt::WMemoryWriter>::type w; + w.write(SPDLOG_FILENAME_T("{}.{:04d}:{:02d}:{:02d}.{:02d}:{:02d}:{:02d}"), basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec); + return std::make_tuple(w.str(), ext); + } +}; + +TEST_CASE("step_logger with custom calculator", "[step_logger_custom]]") +{ + using sink_type = spdlog::sinks::step_file_sink; + + prepare_logdir(); + + std::string basename = "logs/step_log_custom"; + std::tm tm = spdlog::details::os::localtime(); + fmt::MemoryWriter w; + w.write("{}.{:04d}:{:02d}:{:02d}.{:02d}:{:02d}:{:02d}", basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec); + + auto logger = spdlog::create("logger", basename, 60, std::numeric_limits::max()); + for (int i = 0; i < 10; ++i) + { +#if !defined(SPDLOG_FMT_PRINTF) + logger->info("Test message {}", i); +#else + logger->info("Test message %d", i); +#endif + } + + logger->flush(); + auto filename = w.str(); + REQUIRE(count_lines(filename) == 10); +} + /* * File name calculations */ From 6f12242a55238c19e12399d2a41f67ea6924f9c7 Mon Sep 17 00:00:00 2001 From: Puasonych Date: Wed, 11 Apr 2018 11:41:48 +0300 Subject: [PATCH 56/62] Update .gitignore --- .gitignore | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index be48891f..2b432ca5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ # Auto generated files -build/* +build/* *.slo *.lo *.o @@ -65,5 +65,7 @@ install_manifest.txt /tests/logs/* # idea -.idea/ +.idea/ + +# vscode .vscode/ \ No newline at end of file From 06580c8333f81f0cd700bf95de1e7c41ede782c4 Mon Sep 17 00:00:00 2001 From: Erik Date: Wed, 11 Apr 2018 22:15:50 +0500 Subject: [PATCH 57/62] Update file_sinks.h --- include/spdlog/sinks/file_sinks.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/include/spdlog/sinks/file_sinks.h b/include/spdlog/sinks/file_sinks.h index 407c5b83..13282789 100644 --- a/include/spdlog/sinks/file_sinks.h +++ b/include/spdlog/sinks/file_sinks.h @@ -286,6 +286,11 @@ public: _file_helper.open(_current_filename); _current_size = _file_helper.size(); // expensive. called only once } + + ~step_file_sink() + { + close_current_file(); + } protected: void _sink_it(const details::log_msg &msg) override @@ -306,7 +311,6 @@ protected: void _flush() override { _file_helper.flush(); - close_current_file(); } private: From be685337b12ece5533df65d78a5bb8a6926c5745 Mon Sep 17 00:00:00 2001 From: Erik Date: Thu, 12 Apr 2018 10:01:02 +0500 Subject: [PATCH 58/62] Update file_sinks.h Removed possible throw of an exception from the destructor --- include/spdlog/sinks/file_sinks.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/include/spdlog/sinks/file_sinks.h b/include/spdlog/sinks/file_sinks.h index 13282789..73724d23 100644 --- a/include/spdlog/sinks/file_sinks.h +++ b/include/spdlog/sinks/file_sinks.h @@ -289,7 +289,12 @@ public: ~step_file_sink() { - close_current_file(); + using details::os::filename_to_str; + + filename_t src =_current_filename; + filename_t target = _current_filename + _ext; + + details::os::rename(src, target); } protected: From bce3b75c53f80c8b3c9fd33ee2b2542bed11a61b Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Fri, 13 Apr 2018 12:44:43 +0300 Subject: [PATCH 59/62] Created contrib directory --- include/spdlog/contrib/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 include/spdlog/contrib/README.md diff --git a/include/spdlog/contrib/README.md b/include/spdlog/contrib/README.md new file mode 100644 index 00000000..e3abc34d --- /dev/null +++ b/include/spdlog/contrib/README.md @@ -0,0 +1 @@ +Please put here your contribs. Popular contribs will be moved to main tree after stablization From 5e08950ed2d983f0f640c4aa85fb96e5fe23592b Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Fri, 13 Apr 2018 12:45:33 +0300 Subject: [PATCH 60/62] Created contrib/sinks directory --- include/spdlog/contrib/sinks/.gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 include/spdlog/contrib/sinks/.gitignore diff --git a/include/spdlog/contrib/sinks/.gitignore b/include/spdlog/contrib/sinks/.gitignore new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/include/spdlog/contrib/sinks/.gitignore @@ -0,0 +1 @@ + From 1b2f6815bf784ac67defb72966511316b0d6458b Mon Sep 17 00:00:00 2001 From: Jan Niklas Hasse Date: Mon, 16 Apr 2018 10:58:50 +0200 Subject: [PATCH 61/62] Silence warning "value stored to rv is never read" --- tests/utils.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/utils.cpp b/tests/utils.cpp index 2c50ce36..5afdb4cf 100644 --- a/tests/utils.cpp +++ b/tests/utils.cpp @@ -8,6 +8,7 @@ void prepare_logdir() system("del /F /Q logs\\*"); #else auto rv = system("mkdir -p logs"); + (void)rv; rv = system("rm -f logs/*"); (void)rv; #endif From 093edc2dc2385a6488cccd1ad8fa422353ed7991 Mon Sep 17 00:00:00 2001 From: Puasonych Date: Mon, 16 Apr 2018 12:56:45 +0300 Subject: [PATCH 62/62] Update step_logger Test release of a logger step_logger --- include/spdlog/contrib/sinks/step_file_sink.h | 161 ++++++++++++++++++ include/spdlog/details/spdlog_impl.h | 13 -- include/spdlog/sinks/file_sinks.h | 101 ----------- include/spdlog/spdlog.h | 6 - tests/file_log.cpp | 65 ------- 5 files changed, 161 insertions(+), 185 deletions(-) create mode 100644 include/spdlog/contrib/sinks/step_file_sink.h diff --git a/include/spdlog/contrib/sinks/step_file_sink.h b/include/spdlog/contrib/sinks/step_file_sink.h new file mode 100644 index 00000000..6be4d8ef --- /dev/null +++ b/include/spdlog/contrib/sinks/step_file_sink.h @@ -0,0 +1,161 @@ +#pragma once + +#include "../../details/file_helper.h" +#include "../../details/null_mutex.h" +#include "../../fmt/fmt.h" +#include "../../sinks/base_sink.h" + +#include +#include +#include +#include +#include +#include +#include + +// Example for spdlog.h +// +// Create a file logger which creates new files with a specified time step and fixed file size: +// +// std::shared_ptr step_logger_mt(const std::string &logger_name, const filename_t &filename, unsigned seconds = 60, const filename_t &tmp_ext = ".tmp", unsigned max_file_size = std::numeric_limits::max()); +// std::shared_ptr step_logger_st(const std::string &logger_name, const filename_t &filename, unsigned seconds = 60, const filename_t &tmp_ext = ".tmp", unsigned max_file_size = std::numeric_limits::max();; + +// Example for spdlog_impl.h +// Create a file logger that creates new files with a specified increment +// inline std::shared_ptr spdlog::step_logger_mt( +// const std::string &logger_name, const filename_t &filename_fmt, unsigned seconds, const filename_t &tmp_ext, unsigned max_file_size) +// { +// return create(logger_name, filename_fmt, seconds, tmp_ext, max_file_size); +// } + +// inline std::shared_ptr spdlog::step_logger_st( +// const std::string &logger_name, const filename_t &filename_fmt, unsigned seconds, const filename_t &tmp_ext, unsigned max_file_size) +// { +// return create(logger_name, filename_fmt, seconds, tmp_ext, max_file_size); +// } + +namespace spdlog { +namespace sinks { + +/* + * Default generator of step log file names. + */ +struct default_step_file_name_calculator +{ + // Create filename for the form filename_YYYY-MM-DD_hh-mm-ss.ext + static std::tuple calc_filename(const filename_t &filename, const filename_t &tmp_ext) + { + std::tm tm = spdlog::details::os::localtime(); + filename_t basename, ext; + std::tie(basename, ext) = details::file_helper::split_by_extenstion(filename); + std::conditional::value, fmt::MemoryWriter, fmt::WMemoryWriter>::type w; + w.write(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}-{:02d}-{:02d}{}"), basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec, tmp_ext); + return std::make_tuple(w.str(), ext); + } +}; + +/* + * Rotating file sink based on size and a specified time step + */ +template +class step_file_sink SPDLOG_FINAL : public base_sink +{ +public: + step_file_sink(filename_t base_filename, unsigned step_seconds, filename_t tmp_ext, unsigned max_size) + : _base_filename(std::move(base_filename)) + , _tmp_ext(std::move(tmp_ext)) + , _step_seconds(step_seconds) + , _max_size(max_size) + { + if (step_seconds == 0) + { + throw spdlog_ex("step_file_sink: Invalid time step in ctor"); + } + if (max_size == 0) + { + throw spdlog_ex("step_file_sink: Invalid max log size in ctor"); + } + + _tp = _next_tp(); + std::tie(_current_filename, _ext) = FileNameCalc::calc_filename(_base_filename, _tmp_ext); + + if (_tmp_ext == _ext) + { + throw spdlog_ex("step_file_sink: The temporary extension matches the specified in ctor"); + } + + _file_helper.open(_current_filename); + _current_size = _file_helper.size(); // expensive. called only once + } + + ~step_file_sink() + { + using details::os::filename_to_str; + + filename_t src =_current_filename, target; + std::tie(target, std::ignore) = details::file_helper::split_by_extenstion(src); + target += _ext; + + details::os::rename(src, target); + } + +protected: + void _sink_it(const details::log_msg &msg) override + { + _current_size += msg.formatted.size(); + if (std::chrono::system_clock::now() >= _tp || _current_size > _max_size) + { + close_current_file(); + + std::tie(_current_filename, std::ignore) = FileNameCalc::calc_filename(_base_filename, _tmp_ext); + _file_helper.open(_current_filename); + _tp = _next_tp(); + _current_size = msg.formatted.size(); + } + _file_helper.write(msg); + } + + void _flush() override + { + _file_helper.flush(); + } + +private: + std::chrono::system_clock::time_point _next_tp() + { + return std::chrono::system_clock::now() + _step_seconds; + } + + void close_current_file() + { + using details::os::filename_to_str; + + filename_t src =_current_filename, target; + std::tie(target, std::ignore) = details::file_helper::split_by_extenstion(src); + target += _ext; + + if (details::file_helper::file_exists(src) && details::os::rename(src, target) != 0) + { + throw spdlog_ex("step_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno); + } + } + + const filename_t _base_filename; + const filename_t _tmp_ext; + const std::chrono::seconds _step_seconds; + const unsigned _max_size; + + std::chrono::system_clock::time_point _tp; + filename_t _current_filename; + filename_t _ext; + unsigned _current_size; + + details::file_helper _file_helper; +}; + +using step_file_sink_mt = step_file_sink; +using step_file_sink_st = step_file_sink; + +} // namespace sinks +} // namespace spdlog diff --git a/include/spdlog/details/spdlog_impl.h b/include/spdlog/details/spdlog_impl.h index 7d9195bc..4c363834 100644 --- a/include/spdlog/details/spdlog_impl.h +++ b/include/spdlog/details/spdlog_impl.h @@ -83,19 +83,6 @@ inline std::shared_ptr spdlog::daily_logger_st( return create(logger_name, filename, hour, minute); } -// Create a file logger that creates new files with a specified increment -inline std::shared_ptr spdlog::step_logger_mt( - const std::string &logger_name, const filename_t &filename_fmt, unsigned seconds, size_t max_file_size) -{ - return create(logger_name, filename_fmt, seconds, max_file_size); -} - -inline std::shared_ptr spdlog::step_logger_st( - const std::string &logger_name, const filename_t &filename_fmt, unsigned seconds, size_t max_file_size) -{ - return create(logger_name, filename_fmt, seconds, max_file_size); -} - // // stdout/stderr loggers // diff --git a/include/spdlog/sinks/file_sinks.h b/include/spdlog/sinks/file_sinks.h index 73724d23..109c493a 100644 --- a/include/spdlog/sinks/file_sinks.h +++ b/include/spdlog/sinks/file_sinks.h @@ -251,106 +251,5 @@ private: using daily_file_sink_mt = daily_file_sink; using daily_file_sink_st = daily_file_sink; -/* - * Default generator of step log file names. - */ -struct default_step_file_name_calculator -{ - // Create filename for the form filename_YYYY-MM-DD_hh-mm-ss.ext - static std::tuple calc_filename(const filename_t &filename) - { - std::tm tm = spdlog::details::os::localtime(); - filename_t basename, ext; - std::tie(basename, ext) = details::file_helper::split_by_extenstion(filename); - std::conditional::value, fmt::MemoryWriter, fmt::WMemoryWriter>::type w; - w.write(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}-{:02d}-{:02d}"), basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, - tm.tm_hour, tm.tm_min, tm.tm_sec); - return std::make_tuple(w.str(), ext); - } -}; - -/* - * Rotating file sink based on size and a specified time step - */ -template -class step_file_sink SPDLOG_FINAL : public base_sink -{ -public: - step_file_sink(filename_t base_filename, unsigned step_seconds, std::size_t max_size) - : _base_filename(std::move(base_filename)) - , _step_seconds(step_seconds) - , _max_size(max_size) - { - _tp = _next_tp(); - std::tie(_current_filename, _ext) = FileNameCalc::calc_filename(_base_filename); - _file_helper.open(_current_filename); - _current_size = _file_helper.size(); // expensive. called only once - } - - ~step_file_sink() - { - using details::os::filename_to_str; - - filename_t src =_current_filename; - filename_t target = _current_filename + _ext; - - details::os::rename(src, target); - } - -protected: - void _sink_it(const details::log_msg &msg) override - { - _current_size += msg.formatted.size(); - if (std::chrono::system_clock::now() >= _tp || _current_size > _max_size) - { - close_current_file(); - - std::tie(_current_filename, std::ignore) = FileNameCalc::calc_filename(_base_filename); - _file_helper.open(_current_filename); - _tp = _next_tp(); - _current_size = msg.formatted.size(); - } - _file_helper.write(msg); - } - - void _flush() override - { - _file_helper.flush(); - } - -private: - std::chrono::system_clock::time_point _next_tp() - { - return std::chrono::system_clock::now() + _step_seconds; - } - - void close_current_file() - { - using details::os::filename_to_str; - - filename_t src =_current_filename; - filename_t target = _current_filename + _ext; - - if (details::file_helper::file_exists(src) && details::os::rename(src, target) != 0) - { - throw spdlog_ex("step_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno); - } - } - - filename_t _base_filename; - std::chrono::seconds _step_seconds; - std::size_t _max_size; - - std::chrono::system_clock::time_point _tp; - filename_t _current_filename; - filename_t _ext; - std::size_t _current_size; - - details::file_helper _file_helper; -}; - -using step_file_sink_mt = step_file_sink; -using step_file_sink_st = step_file_sink; - } // namespace sinks } // namespace spdlog diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index f65fe57e..21f5951b 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -91,12 +91,6 @@ std::shared_ptr rotating_logger_st( std::shared_ptr daily_logger_mt(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0); std::shared_ptr daily_logger_st(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0); -// -// Create a file logger which creates new files with a specified time step and fixed file size: -// -std::shared_ptr step_logger_mt(const std::string &logger_name, const filename_t &filename, unsigned seconds = 60, size_t max_file_size = std::numeric_limits::max()); -std::shared_ptr step_logger_st(const std::string &logger_name, const filename_t &filename, unsigned seconds = 60, size_t max_file_size = std::numeric_limits::max()); - // // Create and register stdout/stderr loggers // diff --git a/tests/file_log.cpp b/tests/file_log.cpp index afcac255..e20071a3 100644 --- a/tests/file_log.cpp +++ b/tests/file_log.cpp @@ -179,71 +179,6 @@ TEST_CASE("daily_logger with custom calculator", "[daily_logger_custom]]") REQUIRE(count_lines(filename) == 10); } -TEST_CASE("step_logger", "[step_logger]]") -{ - prepare_logdir(); - // calculate filename (time based) - std::string basename = "logs/step_log"; - std::tm tm = spdlog::details::os::localtime(); - fmt::MemoryWriter w; - w.write("{}_{:04d}-{:02d}-{:02d}_{:02d}-{:02d}-{:02d}", basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); - - auto logger = spdlog::step_logger_mt("logger", basename, 60); - logger->flush_on(spdlog::level::info); - for (int i = 0; i < 10; ++i) - { -#if !defined(SPDLOG_FMT_PRINTF) - logger->info("Test message {}", i); -#else - logger->info("Test message %d", i); -#endif - } - - auto filename = w.str(); - REQUIRE(count_lines(filename) == 10); -} - -struct custom_step_file_name_calculator -{ - static std::tuple calc_filename(const spdlog::filename_t &filename) - { - std::tm tm = spdlog::details::os::localtime(); - spdlog::filename_t basename, ext; - std::tie(basename, ext) = spdlog::details::file_helper::split_by_extenstion(filename); - std::conditional::value, fmt::MemoryWriter, fmt::WMemoryWriter>::type w; - w.write(SPDLOG_FILENAME_T("{}.{:04d}:{:02d}:{:02d}.{:02d}:{:02d}:{:02d}"), basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, - tm.tm_hour, tm.tm_min, tm.tm_sec); - return std::make_tuple(w.str(), ext); - } -}; - -TEST_CASE("step_logger with custom calculator", "[step_logger_custom]]") -{ - using sink_type = spdlog::sinks::step_file_sink; - - prepare_logdir(); - - std::string basename = "logs/step_log_custom"; - std::tm tm = spdlog::details::os::localtime(); - fmt::MemoryWriter w; - w.write("{}.{:04d}:{:02d}:{:02d}.{:02d}:{:02d}:{:02d}", basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, - tm.tm_hour, tm.tm_min, tm.tm_sec); - - auto logger = spdlog::create("logger", basename, 60, std::numeric_limits::max()); - for (int i = 0; i < 10; ++i) - { -#if !defined(SPDLOG_FMT_PRINTF) - logger->info("Test message {}", i); -#else - logger->info("Test message %d", i); -#endif - } - - logger->flush(); - auto filename = w.str(); - REQUIRE(count_lines(filename) == 10); -} - /* * File name calculations */