From 6f8cb2b481a8be37926a189402320a165f7bd4a9 Mon Sep 17 00:00:00 2001 From: ithewei Date: Thu, 6 Aug 2026 12:06:44 +0800 Subject: [PATCH] feat(hlog): add %p (pid) and %t (tid) log format specifiers Adds %p/%t to the log format. hlog is meant to be usable standalone (depending only on hexport.h), so instead of pulling in hthread.h this inlines the pid/tid platform primitives using the headers hlog.c already includes (windows.h / pthread.h + sys/syscall.h on Linux, pthread_ threadid_np on macOS). Verified: hlog.c still compiles standalone (only -I. -Ibase, no hthread.h/hplatform.h) and %p/%t print the correct process/thread id. Supersedes #742 (same feature; reworked to keep hlog dependency-free). --- base/hlog.c | 31 +++++++++++++++++++++++++++++++ base/hlog.h | 2 ++ 2 files changed, 33 insertions(+) diff --git a/base/hlog.c b/base/hlog.c index 092fe6ae0..cb149d11c 100644 --- a/base/hlog.c +++ b/base/hlog.c @@ -5,6 +5,7 @@ #include #include #include +#include #include //#include "hmutex.h" @@ -26,6 +27,30 @@ #define hmutex_unlock pthread_mutex_unlock #endif +// Self-contained pid/tid for the %p/%t format specifiers. hlog is meant to be +// usable standalone (only depending on hexport.h), so we don't pull in +// hthread.h/hplatform.h here; instead inline the platform primitives, using +// the headers already included above (windows.h / pthread.h). +#ifdef _WIN32 +#define hlog_getpid() (long)GetCurrentProcessId() +#define hlog_gettid() (long)GetCurrentThreadId() +#else +#include // for getpid +#define hlog_getpid() (long)getpid() +#if defined(__linux__) +#include // for SYS_gettid +static inline long hlog_gettid() { return (long)syscall(SYS_gettid); } +#elif defined(__APPLE__) +static inline long hlog_gettid() { + uint64_t tid = 0; + pthread_threadid_np(NULL, &tid); + return (long)tid; +} +#else +#define hlog_gettid() (long)pthread_self() +#endif +#endif + //#include "htime.h" #define SECONDS_PER_HOUR 3600 #define SECONDS_PER_DAY 86400 // 24*3600 @@ -478,6 +503,12 @@ int logger_print(logger_t* logger, int level, const char* fmt, ...) { buf[len++] = plevel[i]; } break; + case 'p': + len += snprintf(buf + len, bufsize - len, "%ld", hlog_getpid()); + break; + case 't': + len += snprintf(buf + len, bufsize - len, "%ld", hlog_gettid()); + break; case 's': { va_list ap; diff --git a/base/hlog.h b/base/hlog.h index 4ebf7fff1..ed420dc20 100644 --- a/base/hlog.h +++ b/base/hlog.h @@ -100,6 +100,8 @@ HV_EXPORT void logger_set_level_by_str(logger_t* logger, const char* level); * %Z us * %l First character of level * %L All characters of level + * %p pid (process id) + * %t tid (thread id) * %s message * %% % */