Created
May 17, 2017 10:22
-
-
Save epinna/31bada8ad664c242c7723fca07ef1adc to your computer and use it in GitHub Desktop.
Python message format based on message logging level in Python 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Tested with Python 3.5.2 | |
from config import LOGLEVEL | |
import logging | |
class SrvLogFormat(logging.Formatter): | |
err_fmt = "[E] %(msg)s" | |
warn_fmt = "[!] %(msg)s" | |
dbg_fmt = "[D] %(module)s: %(lineno)d: %(msg)s" | |
info_fmt = "%(msg)s" | |
def format(self, record): | |
original_style = self._style | |
if record.levelno == logging.DEBUG: | |
self._style = logging.PercentStyle(self.dbg_fmt) | |
if record.levelno == logging.INFO: | |
self._style = logging.PercentStyle(self.info_fmt) | |
if record.levelno == logging.WARNING: | |
self._style = logging.PercentStyle(self.warn_fmt) | |
if record.levelno == logging.ERROR: | |
self._style = logging.PercentStyle(self.err_fmt) | |
result = logging.Formatter.format(self, record) | |
self._style = original_style | |
return result | |
numeric_level = getattr(logging, LOGLEVEL.upper(), None) | |
if not isinstance(numeric_level, int): | |
raise ValueError('Invalid log level: %s' % loglevel) | |
hdlr = logging.StreamHandler() | |
hdlr.setFormatter(SrvLogFormat()) | |
logging.root.addHandler(hdlr) | |
logging.root.setLevel(numeric_level) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment