Last active
May 19, 2016 03:44
-
-
Save hotpxl/45af6f86762c95229d7615e1d67868a8 to your computer and use it in GitHub Desktop.
Logging utilities
This file contains 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
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
"""Logging utilities.""" | |
import logging | |
CRITICAL = logging.CRITICAL | |
ERROR = logging.ERROR | |
WARNING = logging.WARNING | |
INFO = logging.INFO | |
DEBUG = logging.DEBUG | |
NOTSET = logging.NOTSET | |
class _Formatter(logging.Formatter): | |
"""Customized log formatter.""" | |
def __init__(self): | |
datefmt = '%m%d %H:%M:%S' | |
super().__init__(datefmt=datefmt, style='{') | |
def _get_color(self, level): | |
if WARNING <= level: | |
return '\x1b[31m' | |
elif INFO <= level: | |
return '\x1b[32m' | |
else: | |
return '\x1b[34m' | |
def _get_label(self, level): | |
if level == CRITICAL: | |
return 'C' | |
elif level == ERROR: | |
return 'E' | |
elif level == WARNING: | |
return 'W' | |
elif level == INFO: | |
return 'I' | |
elif level == DEBUG: | |
return 'D' | |
else: | |
return 'U' | |
def format(self, record): | |
fmt = self._get_color(record.levelno) | |
fmt += self._get_label(record.levelno) | |
fmt += '{asctime} {process:5d} {name}:{funcName}:{lineno}' | |
fmt += ']\x1b[0m' | |
fmt += ' {message}' | |
self._style._fmt = fmt | |
return super().format(record) | |
_handler = logging.StreamHandler() | |
_handler.setFormatter(_Formatter()) | |
def get_logger(name=None, level=DEBUG): | |
"""Get customized logger. | |
:param str name: Name of the logger. | |
:param level: Level to log. | |
:return: A logger. | |
""" | |
logger = logging.getLogger(name) | |
if getattr(logger, '_init_done', None) is None: | |
logger._init_done = True | |
logger.addHandler(_handler) | |
logger.setLevel(level) | |
return logger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment