Skip to content

Commit

Permalink
Merge pull request #239 from ayalash/force_colorize
Browse files Browse the repository at this point in the history
ColorizingStreamHandlerMixin: Allow force/forbid colors
  • Loading branch information
vmalloc committed Jul 11, 2017
2 parents 55262a9 + 029d7db commit 89c8640
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
13 changes: 13 additions & 0 deletions logbook/more.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,17 @@ class ColorizingStreamHandlerMixin(object):
.. _`colorama`: https://pypi.python.org/pypi/colorama
"""
_use_color = None

def force_color(self):
"""Force colorizing the stream (`should_colorize` will return True)
"""
self._use_color = True

def forbid_color(self):
"""Forbid colorizing the stream (`should_colorize` will return False)
"""
self._use_color = False

def should_colorize(self, record):
"""Returns `True` if colorizing should be applied to this
Expand All @@ -341,6 +352,8 @@ def should_colorize(self, record):
import colorama
except ImportError:
return False
if self._use_color is not None:
return self._use_color
isatty = getattr(self.stream, 'isatty', None)
return isatty and isatty()

Expand Down
20 changes: 17 additions & 3 deletions tests/test_more.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,16 @@ def test_colorizing_support(logger):
from logbook.more import ColorizedStderrHandler

class TestColorizingHandler(ColorizedStderrHandler):
def __init__(self, *args, **kwargs):
super(TestColorizingHandler, self).__init__(*args, **kwargs)
self._obj_stream = StringIO()

@property
def stream(self):
return self._obj_stream

def should_colorize(self, record):
return True
stream = StringIO()
with TestColorizingHandler(format_string='{record.message}') as handler:
handler.force_color()
logger.error('An error')
logger.warn('A warning')
logger.debug('A debug message')
Expand All @@ -45,6 +50,15 @@ def should_colorize(self, record):
'\x1b[33;01mA warning\x1b[39;49;00m',
'\x1b[37mA debug message\x1b[39;49;00m']

with TestColorizingHandler(format_string='{record.message}') as handler:
handler.forbid_color()
logger.error('An error')
logger.warn('A warning')
logger.debug('A debug message')
lines = handler.stream.getvalue().rstrip('\n').splitlines()
assert lines == ['An error', 'A warning', 'A debug message']



def test_tagged(default_handler):
from logbook.more import TaggingLogger, TaggingHandler
Expand Down

0 comments on commit 89c8640

Please sign in to comment.