Skip to content

Commit 5e9b233

Browse files
committed
Prevent errors if no formatter is provided
This mimics CPython logging functionality. Fixes #2
1 parent b3e70ba commit 5e9b233

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

mqlog/__init__.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import asyncio
44
import logging
55

6+
_default_formatter = logging.Formatter(logging._default_fmt)
7+
68

79
class MqttHandler(logging.Handler):
810
"""
@@ -59,6 +61,11 @@ def emit(self, record):
5961
if self._should_flush(record):
6062
self.will_flush.set()
6163

64+
# Override Handler.format to prevent errors if there's no formatter set
65+
def format(self, record):
66+
fmt = self.formatter or _default_formatter
67+
return fmt.format(record)
68+
6269
# Named with an underscore to avoid conflict with logging.Handler.flush
6370
async def _flush(self):
6471
if self.buffer:

tests/test_handler.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ def setUp(self):
2626
self.logger.addHandler(self.handler)
2727
self.logger.setLevel(logging.INFO)
2828

29+
def test_default_formatter(self):
30+
"""Handler should use default formatter if none is set"""
31+
self.handler.setFormatter(None)
32+
self.logger.info("Test message") # Would error if no formatter
33+
2934
def test_no_flush(self):
3035
"""Buffer should not be flushed until capacity/level reached"""
3136
self.handler.flush_level = logging.WARNING

0 commit comments

Comments
 (0)