Subclassing logging.Formatter Changes the default behavior for logging.Formatter

I added two handlers with different formats to my registrar. The first requires a subclass of logging.Formatter for custom formatting. The default formatting format will be sufficient for the second handler.

Say the first formatter simply removes newlines from the message. The following script illustrates what seems like strange behavior:

import logging

logger = logging.getLogger(__name__)

class CustomFormatter(logging.Formatter):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    def format(self, record):
        record.msg = record.msg.strip().replace('\n', ' ')
        return super().format(record)

h1 = logging.StreamHandler()
formatter1 = CustomFormatter(fmt=None, datefmt=None)
h1.setFormatter(formatter1)
logger.addHandler(h1)

h2 = logging.StreamHandler()
formatter2 = logging.Formatter(fmt=None, datefmt=None)
h2.setFormatter(formatter2)
logger.addHandler(h2)

logger.warning('string with\nmultiple lines')

Outputs the following:

string with multiple lines
string with multiple lines

I was expecting this instead:

string with multiple lines
string with 
multiple lines

The second formatter should not implement the behavior of CustomFormatter, but it does. When I cancel the order in which handlers are added to the registrar, this does not happen.

, . , , logging.Formatter.

​​ , - ?

+4
1

:

record.msg = record.msg.strip().replace('\n', ' ')

, /, . , :

import logging
from copy import copy

logger = logging.getLogger(__name__)

class CustomFormatter(logging.Formatter):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    def format(self, record):
        record = copy(record)
        record.msg = record.msg.strip().replace('\n', ' ')
        return super().format(record)

h1 = logging.StreamHandler()
formatter1 = CustomFormatter(fmt=None, datefmt=None)
h1.setFormatter(formatter1)
logger.addHandler(h1)

h2 = logging.StreamHandler()
formatter2 = logging.Formatter(fmt=None, datefmt=None)
h2.setFormatter(formatter2)
logger.addHandler(h2)

logger.warning('string with\nmultiple lines')

string with multiple lines
string with
multiple lines
+2

All Articles