Home > Net >  python logger limit string size
python logger limit string size

Time:01-10

Python logger library -

Hey, is there a way to limit the string size and return another string if it exceeds the max limit? I have a log file max size set, but it doesn't fit the needs, since the logger sometimes receives a base64 for log, which makes all the logging in the terminal useless.

example:

export = '<Base64 Long String>'
logger.info(f'result: {export}')

Since the code is a part of a big project, I cannot change it in the function itself, is there a way to set it on the logger level?

CodePudding user response:

Use a custom logging.Formatter

import logging

class NotTooLongStringFormatter(logging.Formatter):

    def __init__(self, max_length=10):
        super(NotTooLongStringFormatter, self).__init__()
        self.max_length = max_length

    def format(self, record):
        if len(record.msg) > self.max_length:
            record.msg = record.msg[:self.max_length]   "..."
        return super().format(record)
LOG = logging.getLogger("mylogger")

h = logging.StreamHandler()
h.setFormatter(NotTooLongStringFormatter(20))
LOG.addHandler(h)

LOG.error("a" * 10)  # aaaaaaaaaa
LOG.info("a" * 100)  # aaaaaaaaaaaaaaaaaaaa...

To keep a detailled log, with a specific format, just pass it to super.__init__

def __init__(self, max_length=10):
    fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    super(NotTooLongStringFormatter, self).__init__(fmt)
    self.max_length = max_length


2022-01-09 12:29:44,862 - mylogger - WARNING - aaaaaaaaaa
2022-01-09 12:29:44,863 - mylogger - WARNING - aaaaaaaaaaaaaaaaaaaa...
  •  Tags:  
  • Related