Skip to content

Commit 5f4fc97

Browse files
committed
emit thread id on linux / macOS
1 parent 141cedc commit 5f4fc97

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

lib/picotls.c

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7104,12 +7104,36 @@ int ptls_log_add_fd(int fd, float sample_ratio, const char *_points, const char
71047104

71057105
void ptls_log__do_write_start(struct st_ptls_log_point_t *point, ptls_buffer_t *buf, void *smallbuf, size_t smallbufsize)
71067106
{
7107+
#if defined(__linux__) || defined(__APPLE__)
7108+
static PTLS_THREADLOCAL char tid[sizeof(",\"tid\":-9223372036854775808")];
7109+
static PTLS_THREADLOCAL int tid_ready;
7110+
if (!tid_ready) {
7111+
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
7112+
pthread_mutex_lock(&mutex);
7113+
if (!tid_ready) {
7114+
#if defined(__linux__)
7115+
sprintf(tid, ",\"tid\":%" PRId64, (int64_t)syscall(SYS_gettid));
7116+
#elif defined(__APPLE__)
7117+
uint64_t t = 0;
7118+
(void)pthread_threadid_np(NULL, &t);
7119+
sprintf(tid, ",\"tid\":%" PRIu64, t);
7120+
#else
7121+
#error "unexpected platform"
7122+
#endif
7123+
__sync_synchronize();
7124+
tid_ready = 1;
7125+
}
7126+
pthread_mutex_unlock(&mutex);
7127+
}
7128+
#else
7129+
const char *tid = "";
7130+
#endif
71077131
const char *colon_at = strchr(point->name, ':');
71087132

71097133
ptls_buffer_init(buf, smallbuf, smallbufsize);
71107134

7111-
int written = snprintf((char *)buf->base, buf->capacity, "{\"module\":\"%.*s\",\"type\":\"%s\"", (int)(colon_at - point->name),
7112-
point->name, colon_at + 1);
7135+
int written = snprintf((char *)buf->base, buf->capacity, "{\"module\":\"%.*s\",\"type\":\"%s\"%s",
7136+
(int)(colon_at - point->name), point->name, colon_at + 1, tid);
71137137
assert(written > 0 && written < buf->capacity && "caller MUST provide smallbuf suffient to emit the prefix");
71147138
buf->off = (size_t)written;
71157139
}

0 commit comments

Comments
 (0)