[logger] Add thread name and thread id to log messages

This commit is contained in:
Christian Meffert 2025-02-15 19:55:29 +00:00 committed by ejurgensen
parent 7cde752f20
commit 5fec4bbe34
4 changed files with 60 additions and 2 deletions

View File

@ -85,7 +85,15 @@ AC_SEARCH_LIBS([pthread_setname_np], [pthread],
[AC_MSG_RESULT([[no]])])],
[AC_SEARCH_LIBS([pthread_set_name_np], [pthread],
[AC_CHECK_FUNCS([pthread_set_name_np])])])
AC_SEARCH_LIBS([pthread_getname_np], [pthread],
[AC_DEFINE([HAVE_PTHREAD_GETNAME_NP], 1,
[Define to 1 if you have pthread_getname_np])]
[AC_SEARCH_LIBS([pthread_get_name_np], [pthread],
[AC_DEFINE([HAVE_PTHREAD_GETNAME_NP], 1,
[Define to 1 if you have pthread_get_name_np])])])
AC_SEARCH_LIBS([pthread_getthreadid_np], [pthread],
[AC_DEFINE([HAVE_PTHREAD_GETTHREADID_NP], 1,
[Define to 1 if you have pthread_getthreadid_np])])
AC_SEARCH_LIBS([uuid_generate_random], [uuid],
[AC_DEFINE([HAVE_UUID], 1,
[Define to 1 if you have uuid_generate_random function])])

View File

@ -136,16 +136,19 @@ static void
logger_write_with_label(int severity, int domain, const char *content)
{
char stamp[32];
char thread_nametid[32];
time_t t;
struct tm timebuf;
int ret;
thread_getnametid(thread_nametid, sizeof(thread_nametid));
t = time(NULL);
ret = strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime_r(&t, &timebuf));
if (ret == 0)
stamp[0] = '\0';
logger_write("[%s] [%5s] %8s: %s", stamp, severities[severity], labels[domain], content);
logger_write("[%s] [%5s] [%-20s] %8s: %s", stamp, severities[severity], thread_nametid, labels[domain], content);
}
static void

View File

@ -1788,6 +1788,42 @@ mutex_init(pthread_mutex_t *mutex)
return err;
}
int
thread_gettid()
{
int tid = -1;
#if defined(HAVE_GETTID)
tid = (int)gettid();
#elif defined(HAVE_PTHREAD_GETTHREADID_NP)
tid = pthread_getthreadid_np();
#endif
return tid;
}
void
thread_getname(pthread_t thread, char *name, size_t len)
{
#if defined(HAVE_PTHREAD_GETNAME_NP)
pthread_getname_np(thread, name, len);
#elif defined(HAVE_PTHREAD_GET_NAME_NP)
pthread_get_name_np(thread, name, len);
#else
name[0] = '\0';
#endif
}
void
thread_getnametid(char *buf, size_t len)
{
int tid;
char thread_name[32];
pthread_t p = pthread_self();
thread_getname(p, thread_name, sizeof(thread_name));
tid = thread_gettid();
snprintf(buf, len, "%s (%d)", thread_name, tid);
}
void
thread_setname(pthread_t thread, const char *name)
{

View File

@ -316,6 +316,17 @@ buildopts_get(void);
int
mutex_init(pthread_mutex_t *mutex);
// wrapper for gettid/pthread_getthreadid_np
int
thread_gettid();
// wrapper for pthread_getname_np/pthread_get_name_np
void
thread_getname(pthread_t thread, char *name, size_t len);
void
thread_getnametid(char *buf, size_t len);
// wrapper for pthread_setname_np/pthread_set_name_np
void
thread_setname(pthread_t thread, const char *name);