Skip to content

Commit

Permalink
Support providing a logging context (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
meln1k authored Nov 3, 2023
1 parent 158b557 commit 58ea9b9
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 4 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: Optional[Callable[[], Dict[str, str]]] = None,
) -> None:
super().__init__()
self.fmt_dict = fmt_dict
self.time_format = time_format
self.static_values = static_values or {}
self.get_logging_context = 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 get_context := self.get_logging_context:
message_dict.update(get_context())
if record.exc_info:
if not record.exc_text:
record.exc_text = self.formatException(record.exc_info)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "fixcloudutils"
version = "1.8.0"
version = "1.9.0"
authors = [{ name = "Some Engineering Inc." }]
description = "Utilities for fixcloud."
license = { file = "LICENSE" }
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 58ea9b9

Please sign in to comment.