From 67b8367dc202b76a88fb67e4e97a2dd2ce3582ff Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Mon, 20 Nov 2023 21:20:06 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=97=A5=E5=BF=97=E4=B8=8A?= =?UTF-8?q?=E4=B8=8B=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Network/Socket.cpp | 12 ++++++++++-- src/Network/Socket.h | 4 +--- src/Network/TcpClient.cpp | 6 ++++++ src/Network/TcpServer.cpp | 3 +++ src/Network/UdpServer.cpp | 3 +++ src/Util/logger.cpp | 21 ++++++++++++++++----- src/Util/logger.h | 31 +++++++++++++++++++++---------- 7 files changed, 60 insertions(+), 20 deletions(-) diff --git a/src/Network/Socket.cpp b/src/Network/Socket.cpp index cb47b2492..bccec32ea 100644 --- a/src/Network/Socket.cpp +++ b/src/Network/Socket.cpp @@ -1002,11 +1002,19 @@ bool SocketHelper::isSocketBusy() const { } Task::Ptr SocketHelper::async(TaskIn task, bool may_sync) { - return _poller->async(std::move(task), may_sync); + std::weak_ptr weak_this = shared_from_this(); + return _poller->async([task, weak_this]() mutable{ + Logger::setThreadContext(std::move(weak_this)); + task(); + }, may_sync); } Task::Ptr SocketHelper::async_first(TaskIn task, bool may_sync) { - return _poller->async_first(std::move(task), may_sync); + std::weak_ptr weak_this = shared_from_this(); + return _poller->async_first([task, weak_this]() mutable { + Logger::setThreadContext(std::move(weak_this)); + task(); + }, may_sync); } void SocketHelper::setSendFlushFlag(bool try_flush) { diff --git a/src/Network/Socket.h b/src/Network/Socket.h index c071730b9..4e7c7363b 100644 --- a/src/Network/Socket.h +++ b/src/Network/Socket.h @@ -253,7 +253,7 @@ class MutexWrapper { Mtx _mtx; }; -class SockInfo { +class SockInfo : public LogThreadContext { public: SockInfo() = default; virtual ~SockInfo() = default; @@ -266,8 +266,6 @@ class SockInfo { virtual std::string get_peer_ip() = 0; //获取对方端口号 virtual uint16_t get_peer_port() = 0; - //获取标识符 - virtual std::string getIdentifier() const { return ""; } }; #define TraceP(ptr) TraceL << ptr->getIdentifier() << "(" << ptr->get_peer_ip() << ":" << ptr->get_peer_port() << ") " diff --git a/src/Network/TcpClient.cpp b/src/Network/TcpClient.cpp index b2d292fca..c176ebd47 100644 --- a/src/Network/TcpClient.cpp +++ b/src/Network/TcpClient.cpp @@ -50,11 +50,13 @@ void TcpClient::setNetAdapter(const string &local_ip) { void TcpClient::startConnect(const string &url, uint16_t port, float timeout_sec, uint16_t local_port) { weak_ptr weak_self = static_pointer_cast(shared_from_this()); + Logger::setThreadContext(weak_self); _timer = std::make_shared(2.0f, [weak_self]() { auto strong_self = weak_self.lock(); if (!strong_self) { return false; } + Logger::setThreadContext(strong_self); strong_self->onManager(); return true; }, getPoller()); @@ -73,6 +75,7 @@ void TcpClient::startConnect(const string &url, uint16_t port, float timeout_sec } strong_self->_timer.reset(); TraceL << strong_self->getIdentifier() << " on err: " << ex; + Logger::setThreadContext(strong_self); strong_self->onError(ex); }); @@ -80,6 +83,7 @@ void TcpClient::startConnect(const string &url, uint16_t port, float timeout_sec sock_ptr->connect(url, port, [weak_self](const SockException &err) { auto strong_self = weak_self.lock(); if (strong_self) { + Logger::setThreadContext(strong_self); strong_self->onSockConnect(err); } }, timeout_sec, _net_adapter, local_port); @@ -105,6 +109,7 @@ void TcpClient::onSockConnect(const SockException &ex) { //已经重连socket,上传socket的事件忽略掉 return false; } + Logger::setThreadContext(strong_self); strong_self->onFlush(); return true; }); @@ -119,6 +124,7 @@ void TcpClient::onSockConnect(const SockException &ex) { return; } try { + Logger::setThreadContext(strong_self); strong_self->onRecv(pBuf); } catch (std::exception &ex) { strong_self->shutdown(SockException(Err_other, ex.what())); diff --git a/src/Network/TcpServer.cpp b/src/Network/TcpServer.cpp index 1b0f0d1c7..e1a7c6514 100644 --- a/src/Network/TcpServer.cpp +++ b/src/Network/TcpServer.cpp @@ -129,6 +129,7 @@ Session::Ptr TcpServer::onAcceptConnection(const Socket::Ptr &sock) { return; } try { + Logger::setThreadContext(strong_session); strong_session->onRecv(buf); } catch (SockException &ex) { strong_session->shutdown(ex); @@ -171,6 +172,7 @@ Session::Ptr TcpServer::onAcceptConnection(const Socket::Ptr &sock) { if (strong_session) { //触发onError事件回调 TraceP(strong_session) << cls << " on err: " << err; + Logger::setThreadContext(strong_session); strong_session->onError(err); } }); @@ -230,6 +232,7 @@ void TcpServer::onManagerSession() { for (auto &pr : _session_map) { //遍历时,可能触发onErr事件(也会操作_session_map) try { + Logger::setThreadContext(pr.second->session()); pr.second->session()->onManager(); } catch (exception &ex) { WarnL << ex.what(); diff --git a/src/Network/UdpServer.cpp b/src/Network/UdpServer.cpp index 2a027d1e4..96991f1c6 100644 --- a/src/Network/UdpServer.cpp +++ b/src/Network/UdpServer.cpp @@ -144,6 +144,7 @@ void UdpServer::onRead(const Buffer::Ptr &buf, sockaddr *addr, int addr_len) { static void emitSessionRecv(const Session::Ptr &session, const Buffer::Ptr &buf) { try { + Logger::setThreadContext(session); session->onRecv(buf); } catch (SockException &ex) { session->shutdown(ex); @@ -197,6 +198,7 @@ void UdpServer::onManagerSession() { continue; } try { + Logger::setThreadContext(session); // UDP 会话需要处理超时 session->onManager(); } catch (exception &ex) { @@ -292,6 +294,7 @@ Session::Ptr UdpServer::createSession(const PeerIdType &id, const Buffer::Ptr &b if (auto strong_session = weak_session.lock()) { // 触发 onError 事件回调 TraceP(strong_session) << cls << " on err: " << err; + Logger::setThreadContext(strong_session); strong_session->onError(err); } }); diff --git a/src/Util/logger.cpp b/src/Util/logger.cpp index 2ae000036..08f0de371 100644 --- a/src/Util/logger.cpp +++ b/src/Util/logger.cpp @@ -71,6 +71,17 @@ void setLogger(Logger *logger) { g_defaultLogger = logger; } +static thread_local std::weak_ptr g_log_context; + +void Logger::setThreadContext(std::weak_ptr ctx) { + g_log_context = std::move(ctx); +} + +std::string Logger::getThreadContext() { + auto ref = g_log_context.lock(); + return ref ? ref->getIdentifier() : ""; +} + ///////////////////Logger/////////////////// INSTANCE_IMP(Logger, exeName()) @@ -175,9 +186,9 @@ static inline const char *getFunctionName(const char *func) { #endif } -LogContext::LogContext(LogLevel level, const char *file, const char *function, int line, const char *module_name, const char *flag) +LogContext::LogContext(LogLevel level, const char *file, const char *function, int line, std::string module_name, std::string flag) : _level(level), _line(line), _file(getFileName(file)), _function(getFunctionName(function)), - _module_name(module_name), _flag(flag) { + _module_name(std::move(module_name)), _flag(std::move(flag)) { gettimeofday(&_tv, nullptr); _thread_name = getThreadName(); } @@ -195,8 +206,8 @@ const string &LogContext::str() { static string s_module_name = exeName(false); -LogContextCapture::LogContextCapture(Logger &logger, LogLevel level, const char *file, const char *function, int line, const char *flag) : - _ctx(new LogContext(level, file, function, line, s_module_name.c_str(), flag)), _logger(logger) { +LogContextCapture::LogContextCapture(Logger &logger, LogLevel level, const char *file, const char *function, int line, std::string flag) : + _ctx(new LogContext(level, file, function, line, s_module_name.c_str(), std::move(flag))), _logger(logger) { } LogContextCapture::LogContextCapture(const LogContextCapture &that) : _ctx(that._ctx), _logger(that._logger) { @@ -620,7 +631,7 @@ void FileChannel::setFileMaxCount(size_t max_count) { ////////////////////////////////////////////////////////////////////////////////////////////////// void LoggerWrapper::printLogV(Logger &logger, int level, const char *file, const char *function, int line, const char *fmt, va_list ap) { - LogContextCapture info(logger, (LogLevel) level, file, function, line); + LogContextCapture info(logger, (LogLevel) level, file, function, line, Logger::getThreadContext()); char *str = nullptr; if (vasprintf(&str, fmt, ap) > 0 && str) { info << str; diff --git a/src/Util/logger.h b/src/Util/logger.h index 178c8f728..b9dc2e1e1 100644 --- a/src/Util/logger.h +++ b/src/Util/logger.h @@ -38,6 +38,12 @@ typedef enum { Logger &getLogger(); void setLogger(Logger *logger); +class LogThreadContext { +public: + virtual ~LogThreadContext() = default; + virtual std::string getIdentifier() const { return ""; } +}; + /** * 日志类 */ @@ -98,6 +104,12 @@ class Logger : public std::enable_shared_from_this, public noncopyable { */ void write(const LogContextPtr &ctx); + /** + * 设置线程日志上下文 + */ + static void setThreadContext(std::weak_ptr ctx); + static std::string getThreadContext(); + private: /** * 写日志到各channel,仅供AsyncLogWriter调用 @@ -122,7 +134,7 @@ class LogContext : public std::ostringstream { //_file,_function改成string保存,目的是有些情况下,指针可能会失效 //比如说动态库中打印了一条日志,然后动态库卸载了,那么指向静态数据区的指针就会失效 LogContext() = default; - LogContext(LogLevel level, const char *file, const char *function, int line, const char *module_name, const char *flag); + LogContext(LogLevel level, const char *file, const char *function, int line, std::string module_name, std::string flag); ~LogContext() = default; LogLevel _level; @@ -149,7 +161,7 @@ class LogContextCapture { public: using Ptr = std::shared_ptr; - LogContextCapture(Logger &logger, LogLevel level, const char *file, const char *function, int line, const char *flag = ""); + LogContextCapture(Logger &logger, LogLevel level, const char *file, const char *function, int line, std::string flag = ""); LogContextCapture(const LogContextCapture &that); ~LogContextCapture(); @@ -365,12 +377,11 @@ class SysLogChannel : public LogChannel { class BaseLogFlagInterface { protected: - virtual ~BaseLogFlagInterface() {} + virtual ~BaseLogFlagInterface() =default; // 获得日志标记Flag - const char* getLogFlag(){ - return _log_flag; - } + const char *getLogFlag() { return _log_flag; } void setLogFlag(const char *flag) { _log_flag = flag; } + private: const char *_log_flag = ""; }; @@ -379,13 +390,13 @@ class LoggerWrapper { public: template static inline void printLogArray(Logger &logger, LogLevel level, const char *file, const char *function, int line, First &&first, ARGS &&...args) { - LogContextCapture log(logger, level, file, function, line); + LogContextCapture log(logger, level, file, function, line, Logger::getThreadContext()); log << std::forward(first); appendLog(log, std::forward(args)...); } static inline void printLogArray(Logger &logger, LogLevel level, const char *file, const char *function, int line) { - LogContextCapture log(logger, level, file, function, line); + LogContextCapture log(logger, level, file, function, line, Logger::getThreadContext()); } template @@ -402,11 +413,11 @@ class LoggerWrapper { static void printLogV(Logger &logger, int level, const char *file, const char *function, int line, const char *fmt, va_list ap); }; -//可重置默认值 +// 可重置默认值 extern Logger *g_defaultLogger; //用法: DebugL << 1 << "+" << 2 << '=' << 3; -#define WriteL(level) ::toolkit::LogContextCapture(::toolkit::getLogger(), level, __FILE__, __FUNCTION__, __LINE__) +#define WriteL(level) ::toolkit::LogContextCapture(::toolkit::getLogger(), level, __FILE__, __FUNCTION__, __LINE__, toolkit::Logger::getThreadContext()) #define TraceL WriteL(::toolkit::LTrace) #define DebugL WriteL(::toolkit::LDebug) #define InfoL WriteL(::toolkit::LInfo)