Beispiel #1
0
def setupLogging(stream, level, color=True): # pragma: no cover
    "Setup logging according to the command line parameters"

    # Copied from six source
    if sys.version_info[0] == 3:
        string_types = str,
    else:
        string_types = basestring,

    if isinstance(stream, string_types):
        class Stream(object):
            """
            File subclass that allows RainbowLoggingHandler to write
            with colors
            """
            _lock = Lock()
            _color = color

            def __init__(self, *args, **kwargs):
                self._fd = open(*args, **kwargs)

            def isatty(self):
                """
                Tells if this stream accepts control chars
                """
                return self._color

            def write(self, text):
                """
                Writes to the stream
                """
                with self._lock:
                    try:
                        self._fd.write(toBytes(text))
                    except:
                        _logger.exception("Something went wrong!")

        _stream = Stream(stream, 'ab', buffering=0)
    else:
        _stream = stream

    try:
        from rainbow_logging_handler import RainbowLoggingHandler
        handler = RainbowLoggingHandler(
            _stream,
            #  Customizing each column's color
            # pylint: disable=bad-whitespace
            color_asctime          = ('dim white',  'black'),
            color_name             = ('dim white',  'black'),
            color_funcName         = ('green',      'black'),
            color_lineno           = ('dim white',  'black'),
            color_pathname         = ('black',      'red'),
            color_module           = ('yellow',     None),
            color_message_debug    = ('color_59',   None),
            color_message_info     = (None,         None),
            color_message_warning  = ('color_226',  None),
            color_message_error    = ('red',        None),
            color_message_critical = ('bold white', 'red'))
            # pylint: enable=bad-whitespace
    except ImportError: # pragma: no cover
        handler = logging.StreamHandler(_stream)  # pylint: disable=redefined-variable-type
        log_format = "%(levelname)-8s || %(name)-30s || %(message)s"
        handler.formatter = logging.Formatter(log_format)

    logging.root.addHandler(handler)
    logging.root.setLevel(level)