nicelogger update

This commit is contained in:
lilydjwg 2014-01-31 17:26:12 +08:00
parent dcdfaa7d25
commit e71d56b671
1 changed files with 34 additions and 19 deletions

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 time
import logging
@ -9,7 +15,7 @@ class TornadoLogFormatter(logging.Formatter):
if color:
import curses
curses.setupterm()
if sys.hexversion < 50463728:
if sys.hexversion < 0x30203f0:
fg_color = str(curses.tigetstr("setaf") or
curses.tigetstr("setf") or "", "ascii")
else:
@ -23,6 +29,8 @@ class TornadoLogFormatter(logging.Formatter):
"ascii"),
logging.ERROR: str(curses.tparm(fg_color, 1), # Red
"ascii"),
logging.CRITICAL: str(curses.tparm(fg_color, 9), # Bright Red
"ascii"),
}
self._normal = str(curses.tigetstr("sgr0"), "ascii")
@ -47,23 +55,30 @@ class TornadoLogFormatter(logging.Formatter):
formatted = formatted.rstrip() + "\n" + record.exc_text
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()
h = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s:%(levelname)-7s:%(name)-12s:%(message)s')
try:
import curses
if handler is None:
h = logging.StreamHandler()
else:
h = handler
if color is None:
color = False
curses.setupterm()
if curses.tigetnum("colors") > 0:
color = True
formatter = TornadoLogFormatter(color=color)
except:
import traceback
traceback.print_exc()
finally:
h.setLevel(level)
h.setFormatter(formatter)
logger.setLevel(level)
logger.addHandler(h)
if handler is None and sys.stderr.isatty():
try:
import curses
curses.setupterm()
if curses.tigetnum("colors") > 0:
color = True
except:
import traceback
traceback.print_exc()
formatter = TornadoLogFormatter(color=color)
h.setLevel(level)
h.setFormatter(formatter)
logger.setLevel(level)
logger.addHandler(h)