From d786f6961b37ff045c1d416d0dd111c61b8a21c2 Mon Sep 17 00:00:00 2001 From: chenBright Date: Sat, 27 Jun 2026 17:56:41 +0800 Subject: [PATCH] Use thread local process id and thread id for logging --- src/bthread/mutex.cpp | 4 ++-- src/butil/logging.cc | 18 +++++++++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/bthread/mutex.cpp b/src/bthread/mutex.cpp index fb06470336..dff2da3ff4 100644 --- a/src/bthread/mutex.cpp +++ b/src/bthread/mutex.cpp @@ -515,7 +515,7 @@ int first_sys_pthread_mutex_unlock(pthread_mutex_t* mutex) { pthread_once(&init_sys_mutex_lock_once, init_sys_mutex_lock); return sys_pthread_mutex_unlock(mutex); } -#endif +#endif // NO_PTHREAD_MUTEX_HOOK template inline uint64_t hash_mutex_ptr(const Mutex* m) { @@ -988,7 +988,7 @@ BUTIL_FORCE_INLINE int pthread_mutex_timedlock_impl(pthread_mutex_t* mutex, BUTIL_FORCE_INLINE int pthread_mutex_unlock_impl(pthread_mutex_t* mutex) { return internal::pthread_mutex_unlock_impl(mutex); } -#endif +#endif // NO_PTHREAD_MUTEX_HOOK // Implement bthread_mutex_t related functions struct MutexInternal { diff --git a/src/butil/logging.cc b/src/butil/logging.cc index e4964d0ecf..69ecf182a2 100644 --- a/src/butil/logging.cc +++ b/src/butil/logging.cc @@ -195,6 +195,9 @@ bool show_error_dialogs = false; // the debug message dialog and process termination. LogAssertHandler log_assert_handler = NULL; +BAIDU_VOLATILE_THREAD_LOCAL(int32_t, tls_log_pid, 0); +BAIDU_VOLATILE_THREAD_LOCAL(butil::PlatformThreadId, tls_log_tid, 0); + // Helper functions to wrap platform differences. int32_t CurrentProcessId() { @@ -865,10 +868,19 @@ void PrintLogPrefix(std::ostream& os, int severity, os << '.' << std::setw(6) << tv.tv_usec; #endif if (FLAGS_log_pid) { - os << ' ' << std::setfill(' ') << std::setw(5) << CurrentProcessId(); + int32_t pid = BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_log_pid); + if (pid == 0) { + pid = CurrentProcessId(); + BAIDU_SET_VOLATILE_THREAD_LOCAL(tls_log_pid, pid); + } + os << ' ' << std::setfill(' ') << std::setw(5) << pid; + } + butil::PlatformThreadId tid = BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_log_tid); + if (tid == 0) { + tid = butil::PlatformThread::CurrentId(); + BAIDU_SET_VOLATILE_THREAD_LOCAL(tls_log_tid, tid); } - os << ' ' << std::setfill(' ') << std::setw(5) - << butil::PlatformThread::CurrentId() << std::setfill('0'); + os << ' ' << std::setfill(' ') << std::setw(5) << tid << std::setfill('0'); if (FLAGS_log_bid && bthread_self) { os << ' ' << std::setfill(' ') << std::setw(5) << bthread_self(); }