Skip to content

Commit

Permalink
Support providing a logging context
Browse files Browse the repository at this point in the history
  • Loading branch information
meln1k committed Nov 3, 2023
1 parent 158b557 commit ef77a75
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
6 changes: 5 additions & 1 deletion fixcloudutils/logging/json_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
from logging import Formatter, LogRecord
from typing import Mapping, Optional, Dict
from typing import Mapping, Optional, Dict, Callable


class JsonFormatter(Formatter):
Expand All @@ -34,11 +34,13 @@ def __init__(
fmt_dict: Mapping[str, str],
time_format: str = "%Y-%m-%dT%H:%M:%S",
static_values: Optional[Dict[str, str]] = None,
get_logging_context: Callable[[], Dict[str, str]] = lambda: {},
) -> None:
super().__init__()
self.fmt_dict = fmt_dict
self.time_format = time_format
self.static_values = static_values or {}
self.get_context_values = get_logging_context
self.__uses_time = "asctime" in self.fmt_dict.values()

def usesTime(self) -> bool: # noqa: N802
Expand All @@ -55,6 +57,8 @@ def prop(name: str) -> str:

message_dict = {fmt_key: prop(fmt_val) for fmt_key, fmt_val in self.fmt_dict.items()}
message_dict.update(self.static_values)
if context := self.get_context_values():
message_dict.update(context)
if record.exc_info:
if not record.exc_text:
record.exc_text = self.formatException(record.exc_info)
Expand Down
8 changes: 6 additions & 2 deletions tests/logging_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,18 @@
import logging

import prometheus_client
from typing import Dict

from fixcloudutils.logging import JsonFormatter, PrometheusLoggingCounter


def test_json_logging() -> None:
format = JsonFormatter({"level": "levelname", "message": "message"})
def logging_context() -> Dict[str, str]:
return {"foo": "bar"}

format = JsonFormatter({"level": "levelname", "message": "message"}, get_logging_context=logging_context)
record = logging.getLogger().makeRecord("test", logging.INFO, "test", 1, "test message", (), None)
assert format.format(record) == '{"level": "INFO", "message": "test message"}'
assert format.format(record) == '{"level": "INFO", "message": "test message", "foo": "bar"}'


def test_prometheus_counter() -> None:
Expand Down

0 comments on commit ef77a75

Please sign in to comment.