From d63c68af78ca6505b012638bf1bdbb5c2e60664a Mon Sep 17 00:00:00 2001 From: Benau Date: Fri, 28 Feb 2020 09:35:11 +0800 Subject: [PATCH] Add thread safe log prefix assignment --- src/utils/log.cpp | 18 +++++++++++++++--- src/utils/log.hpp | 10 ++++------ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/utils/log.cpp b/src/utils/log.cpp index bfd0a485c..f6f130c97 100644 --- a/src/utils/log.cpp +++ b/src/utils/log.cpp @@ -21,6 +21,7 @@ #include "config/user_config.hpp" #include "network/network_config.hpp" #include "utils/file_utils.hpp" +#include "utils/tls.hpp" #include #include @@ -42,10 +43,21 @@ Log::LogLevel Log::m_min_log_level = Log::LL_VERBOSE; bool Log::m_no_colors = false; FILE* Log::m_file_stdout = NULL; -std::string Log::m_prefix = ""; size_t Log::m_buffer_size = 1; bool Log::m_console_log = true; Synchronised > Log::m_line_buffer; +thread_local char g_prefix[11] = {}; + +// ---------------------------------------------------------------------------- +void Log::setPrefix(const char* prefix) +{ + size_t len = strlen(prefix); + if (len > 10) + len = 10; + if (len != 0) + memcpy(g_prefix, prefix, len); + g_prefix[len] = 0; +} // setPrefix // ---------------------------------------------------------------------------- /** Selects background/foreground colors for the message depending on @@ -155,9 +167,9 @@ void Log::printMessage(int level, const char *component, const char *format, int index = 0; int remaining = MAX_LENGTH; - if (!m_prefix.empty()) + if (strlen(g_prefix) != 0) { - index += snprintf(line+index, remaining, "%s ", m_prefix.c_str()); + index += snprintf(line+index, remaining, "%s ", g_prefix); remaining = MAX_LENGTH - index > 0 ? MAX_LENGTH - index : 0; } diff --git a/src/utils/log.hpp b/src/utils/log.hpp index a3a15f9c5..cac3e070a 100644 --- a/src/utils/log.hpp +++ b/src/utils/log.hpp @@ -73,14 +73,11 @@ private: int m_level; }; static Synchronised > m_line_buffer; - + /** <0 if no buffered logging is to be used, otherwise this is ** the maximum number of lines the buffer should hold. */ static size_t m_buffer_size; - /** An optional prefix to be printed. */ - static std::string m_prefix; - static void setTerminalColor(LogLevel level); static void resetTerminalColor(); static void writeLine(const char *line, int level); @@ -152,7 +149,8 @@ public: } // disableColor // ------------------------------------------------------------------------ /** Sets a prefix to be printed before each line. To disable the prefix, - * set it to "". */ - static void setPrefix(const std::string &prefix) { m_prefix = prefix; } + * set it to "", max length of prefix is 10, if larger than that the + * remaining characters are ignored. */ + static void setPrefix(const char* prefix); }; // Log #endif