Skip to content

Commit

Permalink
支持日志上下文
Browse files Browse the repository at this point in the history
  • Loading branch information
xia-chu committed Nov 20, 2023
1 parent ad44a16 commit f60de31
Show file tree
Hide file tree
Showing 8 changed files with 62 additions and 22 deletions.
4 changes: 2 additions & 2 deletions src/Network/Session.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ Session::Session(const Socket::Ptr &sock) : SocketHelper(sock) {

string Session::getIdentifier() const {
if (_id.empty()) {
static atomic<uint64_t> s_session_index{0};
_id = to_string(++s_session_index) + '-' + to_string(getSock()->rawFD());
static atomic<uint64_t> s_session_index { 0 };
_id = toolkit::demangle(typeid(*this).name()) + "-" + to_string(++s_session_index) + '-' + to_string(getSock()->rawFD());
}
return _id;
}
Expand Down
12 changes: 10 additions & 2 deletions src/Network/Socket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<SocketHelper> 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<SocketHelper> 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) {
Expand Down
4 changes: 1 addition & 3 deletions src/Network/Socket.h
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ class MutexWrapper {
Mtx _mtx;
};

class SockInfo {
class SockInfo : public LogThreadContext {
public:
SockInfo() = default;
virtual ~SockInfo() = default;
Expand All @@ -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() << ") "
Expand Down
6 changes: 6 additions & 0 deletions src/Network/TcpClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<TcpClient> weak_self = static_pointer_cast<TcpClient>(shared_from_this());
Logger::setThreadContext(weak_self);
_timer = std::make_shared<Timer>(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());
Expand All @@ -73,13 +75,15 @@ 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);
});

TraceL << getIdentifier() << " start connect " << url << ":" << port;
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);
Expand All @@ -105,6 +109,7 @@ void TcpClient::onSockConnect(const SockException &ex) {
//已经重连socket,上传socket的事件忽略掉
return false;
}
Logger::setThreadContext(strong_self);
strong_self->onFlush();
return true;
});
Expand All @@ -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()));
Expand Down
3 changes: 3 additions & 0 deletions src/Network/TcpServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
});
Expand Down Expand Up @@ -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();
Expand Down
3 changes: 3 additions & 0 deletions src/Network/UdpServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -197,6 +198,7 @@ void UdpServer::onManagerSession() {
continue;
}
try {
Logger::setThreadContext(session);
// UDP 会话需要处理超时
session->onManager();
} catch (exception &ex) {
Expand Down Expand Up @@ -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);
}
});
Expand Down
21 changes: 16 additions & 5 deletions src/Util/logger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,17 @@ void setLogger(Logger *logger) {
g_defaultLogger = logger;
}

static thread_local std::weak_ptr<LogThreadContext> g_log_context;

void Logger::setThreadContext(std::weak_ptr<LogThreadContext> 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())
Expand Down Expand Up @@ -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();
}
Expand All @@ -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) {
Expand Down Expand Up @@ -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;
Expand Down
31 changes: 21 additions & 10 deletions src/Util/logger.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ typedef enum {
Logger &getLogger();
void setLogger(Logger *logger);

class LogThreadContext {
public:
virtual ~LogThreadContext() = default;
virtual std::string getIdentifier() const { return ""; }
};

/**
* 日志类
*/
Expand Down Expand Up @@ -98,6 +104,12 @@ class Logger : public std::enable_shared_from_this<Logger>, public noncopyable {
*/
void write(const LogContextPtr &ctx);

/**
* 设置线程日志上下文
*/
static void setThreadContext(std::weak_ptr<LogThreadContext> ctx);
static std::string getThreadContext();

private:
/**
* 写日志到各channel,仅供AsyncLogWriter调用
Expand All @@ -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;
Expand All @@ -149,7 +161,7 @@ class LogContextCapture {
public:
using Ptr = std::shared_ptr<LogContextCapture>;

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();

Expand Down Expand Up @@ -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 = "";
};
Expand All @@ -379,13 +390,13 @@ class LoggerWrapper {
public:
template<typename First, typename ...ARGS>
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>(first);
appendLog(log, std::forward<ARGS>(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<typename Log, typename First, typename ...ARGS>
Expand All @@ -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)
Expand Down

0 comments on commit f60de31

Please sign in to comment.