python - How to format the name of the logging level -
when start ipython, see logs this:
[i 17:03:59.993 notebookapp] using mathjax cdn: https://cdn.mathjax.org/mathjax/latest/mathjax.js [w 17:04:00.292 notebookapp] terminals not available (error no module named terminado) [i 17:04:00.293 notebookapp] serving notebooks local directory: /home/oleg [i 17:04:00.293 notebookapp] 0 active kernels [i 17:04:00.293 notebookapp] ipython notebook running at: http://localhost:8888/ [i 17:04:00.293 notebookapp] use control-c stop server , shut down kernels (twice skip confirmation).
here levels of messages formatted, is, see i
instead of info
, w
instead of warning
etc. in addition, brackets colored. find cool , write logs way too. however, ipython uses tornado logging system.
i use colorlog module color messages. in order formatting, subclassed streamhandler
class, described here: how level of logging record in custom logging.handler in python?
class formatlevelhandler(logging.streamhandler): def emit(self, record): record.levelname = record.levelname[0] logging.streamhandler.emit(self, record)
but when this, coloring not work anymore.
is there way have both logging level name formatting , coloring? here full code:
import logging colorlog import coloredformatter formatter = coloredformatter( "%(log_color)s[%(levelname)1s %(asctime)s] %(reset)s %(blue)s%(message)s", datefmt=none, reset=true, log_colors={ 'debug': 'cyan', 'info': 'green', 'warning': 'yellow', 'error': 'red', 'critical': 'red,bg_white', }, secondary_log_colors={}, style='%' ) logger = logging.getlogger(__name__) class formatlevelhandler(logging.streamhandler): def emit(self, record): record.levelname = record.levelname[0] logging.streamhandler.emit(self, record) ch = formatlevelhandler() ch.setformatter(formatter) logger.addhandler(ch) logger.setlevel(logging.debug) logger.info('hello') logger.debug('hi')
do not change level in handler.emit()
. instead, truncate level in format string using %(levelname)1.1s
(not %(levelname)1s
in example).
or can use tornado logging system whether use rest of tornado or not: call tornado.log.enable_pretty_logging()
@ start of program.
Comments
Post a Comment