Skip to content
This repository was archived by the owner on Dec 21, 2024. It is now read-only.

Commit b0dbe22

Browse files
committed
Fix too strict regex for pecentage style logging
Regression introduced in 0055dc5. Only fields followed by an 's' were correctly extracted. As there are other possible cases like '8s', 'd', or no 's' at all the regex is loosened. In this funky case "[%(levelname)8s][PID %(process)d][%(threadName)s]" the extracted field was "levelname)8s][PID %(process)d][%(threadName".
1 parent 5fb15d5 commit b0dbe22

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/pythonjsonlogger/jsonlogger.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,15 +146,15 @@ def parse(self) -> List[str]:
146146
147147
This method is responsible for returning a list of fields (as strings)
148148
to include in all log messages.
149-
"""
149+
"""
150150
if isinstance(self._style, logging.StringTemplateStyle):
151151
formatter_style_pattern = re.compile(r'\$\{(.+?)\}', re.IGNORECASE)
152152
elif isinstance(self._style, logging.StrFormatStyle):
153153
formatter_style_pattern = re.compile(r'\{(.+?)\}', re.IGNORECASE)
154154
# PercentStyle is parent class of StringTemplateStyle and StrFormatStyle so
155155
# it needs to be checked last.
156156
elif isinstance(self._style, logging.PercentStyle):
157-
formatter_style_pattern = re.compile(r'%\((.+?)\)s', re.IGNORECASE)
157+
formatter_style_pattern = re.compile(r'%\((.+?)\)', re.IGNORECASE)
158158
else:
159159
raise ValueError('Invalid format: %s' % self._fmt)
160160

tests/tests.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,20 @@ def testDefaultFormat(self):
4242

4343
self.assertEqual(logJson["message"], msg)
4444

45+
def testPercentageFormat(self):
46+
fr = jsonlogger.JsonFormatter(
47+
# All kind of different styles to check the regex
48+
'[%(levelname)8s] %(message)s %(filename)s:%(lineno)d %(asctime)'
49+
)
50+
self.logHandler.setFormatter(fr)
51+
52+
msg = "testing logging format"
53+
self.logger.info(msg)
54+
logJson = json.loads(self.buffer.getvalue())
55+
56+
self.assertEqual(logJson["message"], msg)
57+
self.assertEqual(logJson.keys(), {'levelname', 'message', 'filename', 'lineno', 'asctime'})
58+
4559
def testRenameBaseField(self):
4660
fr = jsonlogger.JsonFormatter(rename_fields={'message': '@message'})
4761
self.logHandler.setFormatter(fr)

0 commit comments

Comments
 (0)