Skip to content

Commit c8ecf6e

Browse files
committed
refactor: remove unused JsonFormatter class
No production consumer — all JSON formatting goes through map_event_to_json_record via structlog's ProcessorFormatter. JsonRecord TypedDict stays as the schema definition.
1 parent 1b9f1d7 commit c8ecf6e

File tree

2 files changed

+3
-79
lines changed

2 files changed

+3
-79
lines changed

src/common/core/logging.py

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from typing_extensions import TypedDict
1616

1717
from common.core.constants import LOGGING_DEFAULT_ROOT_LOG_LEVEL
18+
from common.core.sentry import sentry_processor
1819

1920
logger = logging.getLogger(__name__)
2021

@@ -29,27 +30,6 @@ class JsonRecord(TypedDict, extra_items=Any, total=False): # type: ignore[call-
2930
exc_info: str
3031

3132

32-
class JsonFormatter(logging.Formatter):
33-
"""Custom formatter for json logs."""
34-
35-
def get_json_record(self, record: logging.LogRecord) -> JsonRecord:
36-
formatted_message = record.getMessage()
37-
json_record: JsonRecord = {
38-
"levelname": record.levelname,
39-
"message": formatted_message,
40-
"timestamp": self.formatTime(record, self.datefmt),
41-
"logger_name": record.name,
42-
"pid": record.process,
43-
"thread_name": record.threadName,
44-
}
45-
if record.exc_info:
46-
json_record["exc_info"] = self.formatException(record.exc_info)
47-
return json_record
48-
49-
def format(self, record: logging.LogRecord) -> str:
50-
return json.dumps(self.get_json_record(record))
51-
52-
5333
def setup_logging(
5434
log_level: str = "INFO",
5535
log_format: str = "generic",
@@ -120,7 +100,7 @@ def map_event_to_json_record(
120100
method_name: str,
121101
event_dict: EventDict,
122102
) -> EventDict:
123-
"""Map structlog fields to match :class:`JsonFormatter` output schema."""
103+
"""Map structlog fields to match :class:`JsonRecord` output schema."""
124104
event_dict.pop("positional_args", None)
125105
record: JsonRecord = {
126106
"message": event_dict.pop("event", ""),
@@ -148,7 +128,6 @@ def setup_structlog(
148128
record, leaving the original ``msg``, ``args``, and ``exc_info``
149129
intact for Sentry's ``LoggingIntegration`` hook.
150130
"""
151-
from common.core.sentry import sentry_processor
152131

153132
if log_format == "json":
154133
renderer_processors: list[Processor] = [

tests/unit/common/core/test_logging.py

Lines changed: 1 addition & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from sentry_sdk.envelope import Envelope
1212
from sentry_sdk.transport import Transport
1313

14-
from common.core.logging import JsonFormatter, setup_logging
14+
from common.core.logging import setup_logging
1515

1616
if TYPE_CHECKING:
1717
from sentry_sdk._types import Event
@@ -49,61 +49,6 @@ def sentry_transport_mock() -> Generator[MockSentryTransport, None, None]:
4949
sentry_sdk.init(transport=None)
5050

5151

52-
@pytest.mark.freeze_time("2023-12-08T06:05:47+00:00")
53-
def test_json_formatter__format_log__outputs_expected(
54-
caplog: pytest.LogCaptureFixture,
55-
request: pytest.FixtureRequest,
56-
) -> None:
57-
# Given
58-
json_formatter = JsonFormatter()
59-
60-
caplog.handler.setFormatter(json_formatter)
61-
logger = logging.getLogger("test_json_formatter__outputs_expected")
62-
logger.setLevel(logging.INFO)
63-
64-
expected_pid = os.getpid()
65-
expected_module_path = os.path.abspath(request.path)
66-
67-
def _log_traceback() -> None:
68-
try:
69-
raise Exception()
70-
except Exception as exc:
71-
logger.error("this is an error", exc_info=exc)
72-
73-
expected_lineno = _log_traceback.__code__.co_firstlineno + 2
74-
expected_tb_string = (
75-
"Traceback (most recent call last):\n"
76-
f' File "{expected_module_path}",'
77-
f" line {expected_lineno}, in _log_traceback\n"
78-
" raise Exception()\nException"
79-
)
80-
81-
# When
82-
logger.info("hello %s, %d", "arg1", 22.22)
83-
_log_traceback()
84-
85-
# Then
86-
assert [json.loads(message) for message in caplog.text.split("\n") if message] == [
87-
{
88-
"levelname": "INFO",
89-
"message": "hello arg1, 22",
90-
"timestamp": "2023-12-08 06:05:47,000",
91-
"logger_name": "test_json_formatter__outputs_expected",
92-
"pid": expected_pid,
93-
"thread_name": "MainThread",
94-
},
95-
{
96-
"levelname": "ERROR",
97-
"message": "this is an error",
98-
"timestamp": "2023-12-08 06:05:47,000",
99-
"logger_name": "test_json_formatter__outputs_expected",
100-
"pid": expected_pid,
101-
"thread_name": "MainThread",
102-
"exc_info": expected_tb_string,
103-
},
104-
]
105-
106-
10752
def test_setup_logging__generic_format__configures_stdlib(
10853
capsys: pytest.CaptureFixture[str],
10954
test_app_loggers: list[str],

0 commit comments

Comments
 (0)