From b40913bc8beadbc85a414b708328a5e1d9f26011 Mon Sep 17 00:00:00 2001 From: Jonathan Green Date: Thu, 18 Apr 2024 14:54:06 -0300 Subject: [PATCH] Add thread info to the logger (#1798) * Add the current thread to the logger. * Add thread to logger as well --- core/service/logging/log.py | 4 ++++ tests/core/service/logging/test_log.py | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/core/service/logging/log.py b/core/service/logging/log.py index 7622dee226..14bfbfcc7a 100644 --- a/core/service/logging/log.py +++ b/core/service/logging/log.py @@ -3,6 +3,7 @@ import json import logging import socket +import threading from collections.abc import Callable, Mapping, Sequence from logging import Handler from typing import TYPE_CHECKING, Any @@ -39,6 +40,7 @@ def __init__(self) -> None: if len(fqdn) > len(hostname): hostname = fqdn self.hostname = hostname + self.main_thread_id = threading.main_thread().ident def format(self, record: logging.LogRecord) -> str: def ensure_str(s: Any) -> Any: @@ -85,6 +87,8 @@ def ensure_str(s: Any) -> Any: data["traceback"] = self.formatException(record.exc_info) if record.process: data["process"] = record.process + if record.thread and record.thread != self.main_thread_id: + data["thread"] = record.thread # If we are running in a Flask context, we include the request data in the log if flask_request: diff --git a/tests/core/service/logging/test_log.py b/tests/core/service/logging/test_log.py index 29714df24d..009120f890 100644 --- a/tests/core/service/logging/test_log.py +++ b/tests/core/service/logging/test_log.py @@ -61,6 +61,24 @@ def test_format(self, log_record: LogRecordCallable): data = json.loads(formatter.format(record)) assert "process" not in data + def test_format_thread(self, log_record: LogRecordCallable) -> None: + formatter = JSONFormatter() + record = log_record() + + # Since we are in the main thread, the thread field is not included in the log. + data = json.loads(formatter.format(record)) + assert "thread" not in data + + # If the thread is None we also don't include it in the log. + record.thread = None + data = json.loads(formatter.format(record)) + assert "thread" not in data + + # But if we are not in the main thread, the thread field is included in the log. + record.thread = 12 + data = json.loads(formatter.format(record)) + assert data["thread"] == 12 + def test_format_exception(self, log_record: LogRecordCallable) -> None: formatter = JSONFormatter()