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 * %% % */