Created
May 19, 2013 21:48
-
-
Save rcarmo/5609167 to your computer and use it in GitHub Desktop.
A Python logging handler with ANSI coloring support
This file contains hidden or 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
from pygments import highlight | |
from pygments.lexers import get_lexer_by_name, guess_lexer | |
from pygments.formatters import TerminalFormatter, Terminal256Formatter, NullFormatter | |
class PygmentsHandler(logging.StreamHandler): | |
"""Console logging handler with syntax highlighting""" | |
def __init__(self, stream=None, syntax="guess", encoding='utf-8'): | |
# run the regular Handler __init__ | |
logging.StreamHandler.__init__(self,stream) | |
self.pformatter = (Terminal256Formatter(encoding=encoding) | |
if '256color' in os.environ.get('TERM', '') | |
else TerminalFormatter(encoding=encoding)) | |
if not stream.isatty(): | |
self.pformatter = NullFormatter | |
if syntax == "guess": | |
self.lexer = guess_lexer | |
else: | |
self.lexer = get_lexer_by_name(syntax) | |
def emit(self, record): | |
if self.pformatter == NullFormatter: | |
return | |
msg = self.format(record) | |
# Note that the guessing also applies to any log formatting | |
if self.lexer == guess_lexer: | |
lexer = guess_lexer(msg) | |
self.stream.write(highlight(msg,lexer,self.pformatter)) | |
return | |
self.stream.write(highlight(msg,self.lexer,self.pformatter)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment