From 437a654b90e4143ff9f6c31736567b587897f71b Mon Sep 17 00:00:00 2001 From: Lion Kortlepel Date: Sun, 8 Nov 2020 02:28:40 +0100 Subject: [PATCH] Added thread names to logs --- include/Logger.h | 4 ++-- src/logger.cpp | 40 ++++++++++++++++++++++++++++++++++------ 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/include/Logger.h b/include/Logger.h index c4890b8..f1037af 100644 --- a/include/Logger.h +++ b/include/Logger.h @@ -6,8 +6,8 @@ #include #include void InitLog(); -#define DebugPrintTID() DebugPrintTIDInternal(__func__) -void DebugPrintTIDInternal(const std::string& func); // prints the current thread id in debug mode, to make tracing of crashes and asserts easier +#define DebugPrintTID() DebugPrintTIDInternal(__func__, false) +void DebugPrintTIDInternal(const std::string& func, bool overwrite = true); // prints the current thread id in debug mode, to make tracing of crashes and asserts easier void ConsoleOut(const std::string& msg); void QueueAbort(); void except(const std::string& toPrint); diff --git a/src/logger.cpp b/src/logger.cpp index 0b989fd..a37f765 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -9,7 +9,37 @@ #include #include #include +#include +#include +using RWMutex = std::shared_mutex; +using ReadLock = std::shared_lock; +using WriteLock = std::unique_lock; + +static RWMutex ThreadNameMapMutex; +static std::unordered_map ThreadNameMap; + +std::string ThreadName() { + ReadLock lock(ThreadNameMapMutex); + std::string Name; + if (ThreadNameMap.find(std::this_thread::get_id()) != ThreadNameMap.end()) { + Name = ThreadNameMap.at(std::this_thread::get_id()); + } else { + std::stringstream ss; + ss << std::this_thread::get_id(); + Name = ss.str(); + } + lock.unlock(); + return Name; +} + +void SetThreadName(const std::string& Name, bool overwrite) { + WriteLock lock(ThreadNameMapMutex); + if (overwrite || ThreadNameMap.find(std::this_thread::get_id()) == ThreadNameMap.end()) { + ThreadNameMap[std::this_thread::get_id()] = Name; + } + lock.unlock(); +} std::string getDate() { typedef std::chrono::duration>::type> days; @@ -46,14 +76,11 @@ std::string getDate() { << Min << ":" << Secs << "] " -#ifdef DEBUG - << std::this_thread::get_id() + << ThreadName() << " "; -#else - ; -#endif return date.str(); } + void InitLog() { std::ofstream LFS; LFS.open(Sec("Server.log")); @@ -64,9 +91,10 @@ void InitLog() { } std::mutex LogLock; -void DebugPrintTIDInternal(const std::string& func) { +void DebugPrintTIDInternal(const std::string& func, bool overwrite) { // we need to print to cout here as we might crash before all console output is handled, // due to segfaults or asserts. + SetThreadName(func, overwrite); #ifdef DEBUG LogLock.lock(); std::stringstream Print;