Skip to content

Commit

Permalink
Add thread info to the logger (#1798)
Browse files Browse the repository at this point in the history
* Add the current thread to the logger.

* Add thread to logger as well
  • Loading branch information
jonathangreen authored Apr 18, 2024
1 parent d9face1 commit b40913b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
4 changes: 4 additions & 0 deletions core/service/logging/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
18 changes: 18 additions & 0 deletions tests/core/service/logging/test_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit b40913b

Please sign in to comment.