nicelogger update

This commit is contained in:
lilydjwg 2014-01-31 17:26:12 +08:00
parent dcdfaa7d25
commit e71d56b671

View File

@ -1,3 +1,9 @@
'''
A Tornado-inspired logging formatter, with displayed time with millisecond accuracy
FYI: pyftpdlib also has a Tornado-style logger.
'''
import sys import sys
import time import time
import logging import logging
@ -9,7 +15,7 @@ class TornadoLogFormatter(logging.Formatter):
if color: if color:
import curses import curses
curses.setupterm() curses.setupterm()
if sys.hexversion < 50463728: if sys.hexversion < 0x30203f0:
fg_color = str(curses.tigetstr("setaf") or fg_color = str(curses.tigetstr("setaf") or
curses.tigetstr("setf") or "", "ascii") curses.tigetstr("setf") or "", "ascii")
else: else:
@ -23,6 +29,8 @@ class TornadoLogFormatter(logging.Formatter):
"ascii"), "ascii"),
logging.ERROR: str(curses.tparm(fg_color, 1), # Red logging.ERROR: str(curses.tparm(fg_color, 1), # Red
"ascii"), "ascii"),
logging.CRITICAL: str(curses.tparm(fg_color, 9), # Bright Red
"ascii"),
} }
self._normal = str(curses.tigetstr("sgr0"), "ascii") self._normal = str(curses.tigetstr("sgr0"), "ascii")
@ -47,23 +55,30 @@ class TornadoLogFormatter(logging.Formatter):
formatted = formatted.rstrip() + "\n" + record.exc_text formatted = formatted.rstrip() + "\n" + record.exc_text
return formatted.replace("\n", "\n ") return formatted.replace("\n", "\n ")
def enable_pretty_logging(level=logging.DEBUG): def enable_pretty_logging(level=logging.DEBUG, handler=None, color=None):
'''
handler: specify a handler instead of default StreamHandler
color: boolean, force color to be on / off. Default to be on only when
``handler`` isn't specified and the term supports color
'''
logger = logging.getLogger() logger = logging.getLogger()
h = logging.StreamHandler() if handler is None:
formatter = logging.Formatter('%(asctime)s:%(levelname)-7s:%(name)-12s:%(message)s') h = logging.StreamHandler()
try: else:
import curses h = handler
if color is None:
color = False color = False
curses.setupterm() if handler is None and sys.stderr.isatty():
if curses.tigetnum("colors") > 0: try:
color = True import curses
formatter = TornadoLogFormatter(color=color) curses.setupterm()
except: if curses.tigetnum("colors") > 0:
import traceback color = True
traceback.print_exc() except:
finally: import traceback
h.setLevel(level) traceback.print_exc()
h.setFormatter(formatter) formatter = TornadoLogFormatter(color=color)
logger.setLevel(level) h.setLevel(level)
logger.addHandler(h) h.setFormatter(formatter)
logger.setLevel(level)
logger.addHandler(h)