Skip to content

Commit a6dcf85

Browse files
fix: deal with 3rd party libs passing non-str objects to Logger.info etc.
- emit warning to tell 'I silently tried to cast which might fail' - try to cast to avoid most errors which would in last instance cause the regex match to fail
1 parent 7843ad2 commit a6dcf85

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

python_logging_filters/__init__.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
22
import re
3+
import warnings
34

45

56
class DjangoHttp404LogFilter(logging.Filter):
@@ -33,13 +34,28 @@ class DjangoHttp404LogFilter(logging.Filter):
3334
PATTERN = re.compile("^Not Found:")
3435

3536
def filter(self, record: logging.LogRecord) -> bool:
36-
try:
37-
message = record.msg % record.args
38-
except TypeError:
39-
message = record.msg
37+
message = self._format_message(record)
4038
is_not_found_record = (
4139
self.PATTERN.match(message) is not None
4240
and record.levelno == logging.WARNING
4341
and record.name.startswith("django")
4442
)
4543
return not is_not_found_record
44+
45+
def _format_message(self, record: logging.LogRecord) -> str:
46+
if not isinstance(record.msg, str):
47+
warnings.warn(self._format_type_warning(record.msg))
48+
49+
# NOTE: 'record.msg' is typed as 'str' but casted explicitly as some
50+
# immature third-party rant passes 'anything' causing the regex pattern
51+
# matching in .filter() to fail -.-
52+
try:
53+
return str(record.msg) % record.args
54+
except TypeError:
55+
return str(record.msg)
56+
57+
def _format_type_warning(self, value: object):
58+
return (
59+
"[DjangoHttp404LogFilter] received non-str object. "
60+
f"trying to cast {value.__class__} into str"
61+
)

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
setup(
44
name="python-logging-filters",
5-
version="0.1.7",
5+
version="0.1.8",
66
description="standard python logging filters",
77
long_description=open("README.md").read(),
88
long_description_content_type="text/markdown",

0 commit comments

Comments
 (0)