Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

structured logging #93

Merged
merged 19 commits into from
Oct 25, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
adding custom logging filters and formatters
ericbuckley committed Oct 22, 2024
commit 9627cdf4079e92b93274702f434f19905c24820a
44 changes: 44 additions & 0 deletions src/recordlinker/logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import logging
import typing

import pythonjsonlogger.jsonlogger

RESERVED_ATTRS = pythonjsonlogger.jsonlogger.RESERVED_ATTRS + ("taskName",)


# Custom filter to transform log arguments into JSON fields
class DictArgFilter(logging.Filter):
def filter(self, record):
"""
Filter the log record to extract the dictionary arguments as fields.
"""
# if the args are a dictionary, set the key-value pairs as attributes
if isinstance(record.args, dict):
for key, value in record.args.items():
setattr(record, key, value)
return True


class KeyValueFilter(logging.Filter):
def filter(self, record):
"""
Filter the log record to extract the key-value pairs from the log message.
"""
for key, value in record.__dict__.items():
if key not in RESERVED_ATTRS:
record.msg = f"{record.msg} {key}={value}"
return True


class JSONFormatter(pythonjsonlogger.jsonlogger.JsonFormatter):
"""
A custom JSON formatter that excldues the taskName field by default.
"""

def __init__(
self,
*args: typing.Any,
reserved_attrs: tuple[str, ...] = RESERVED_ATTRS,
**kwargs: typing.Any,
):
super().__init__(*args, reserved_attrs=reserved_attrs, **kwargs)