Skip to content

Instantly share code, notes, and snippets.

@epinna
Created May 17, 2017 10:22
Show Gist options
  • Save epinna/31bada8ad664c242c7723fca07ef1adc to your computer and use it in GitHub Desktop.
Save epinna/31bada8ad664c242c7723fca07ef1adc to your computer and use it in GitHub Desktop.
Python message format based on message logging level in Python 3
# 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