python-colorlog-4.1.0/0000755000232200023220000000000013603360546015227 5ustar debalancedebalancepython-colorlog-4.1.0/doc/0000755000232200023220000000000013603360546015774 5ustar debalancedebalancepython-colorlog-4.1.0/doc/example.py0000644000232200023220000000202113603360546017774 0ustar debalancedebalance#!/usr/bin/env python """python-colorlog example.""" import logging from colorlog import ColoredFormatter def setup_logger(): """Return a logger with a default ColoredFormatter.""" formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', } ) logger = logging.getLogger('example') handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) return logger def main(): """Create and use a logger.""" logger = setup_logger() logger.debug('a debug message') logger.info('an info message') logger.warning('a warning message') logger.error('an error message') logger.critical('a critical message') if __name__ == '__main__': main() python-colorlog-4.1.0/doc/custom_level.py0000644000232200023220000000073113603360546021050 0ustar debalancedebalanceimport logging from colorlog import ColoredFormatter logging.addLevelName(5, 'TRACE') def main(): """Create and use a logger.""" formatter = ColoredFormatter(log_colors={'TRACE': 'yellow'}) handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger('example') logger.addHandler(handler) logger.setLevel('TRACE') logger.log(5, 'a message using a custom level') if __name__ == '__main__': main() python-colorlog-4.1.0/doc/example.png0000644000232200023220000002465713603360546020153 0ustar debalancedebalancePNG  IHDR|VCźy iCCPICC ProfileH wTSF z/Х$PBL*6TWpEeEA\"kA,XQ`_EEY 6T~/=~s|ޝ;w̛9 %f DAĤd1 :bOTT⍔VX9\1( N9Cj[( \I )grfČOls<e@zi $ ¶_aO6AXeNN6MG0&bexv/LdaXZ>lr%y}%DHODά6+7TƂ9;$qs!g9;cIVDcα(7Z_!39Ls1st~ s x sϏcqV,.DrN#Ff.}<^lc N0WG=sgf @"QɨtUDգZP]^Mj ES4CKЫћFt;&z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ئyӚ/8:DZN8Ci7oqC ֺ1{5Bg]2g.~dP"gUZu*BNkʮ ܙI l(*?> 7&VRR4 +Lt}a!&@A; K:/W_log_color`: Return another color based on the records level if the formatter has secondary colors configured (see `secondary_log_colors` below). Multiple escape codes can be used at once by joining them with commas when configuring the color for a log level (but can't be used directly in the format string). For example, `black,bg_white` would use the escape codes for black text on a white background. The following escape codes are made available for use in the format string: - `{color}`, `fg_{color}`, `bg_{color}`: Foreground and background colors. - `bold`, `bold_{color}`, `fg_bold_{color}`, `bg_bold_{color}`: Bold/bright colors. - `thin`, `thin_{color}`, `fg_thin_{color}`: Thin colors (terminal dependent). - `reset`: Clear all formatting (both foreground and background colors). The available color names are `black`, `red`, `green`, `yellow`, `blue`, `purple`, `cyan` and `white`. Examples -------- ![Example output](doc/example.png) The following code creates a `ColoredFormatter` for use in a logging setup, using the default values for each argument. ```python from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%' ) ``` Using `secondary_log_colors` ------------------------------ Secondary log colors are a way to have more than one color that is selected based on the log level. Each key in `secondary_log_colors` adds an attribute that can be used in format strings (`message` becomes `message_log_color`), and has a corresponding value that is identical in format to the `log_colors` argument. The following example highlights the level name using the default log colors, and highlights the message in red for `error` and `critical` level log messages. ```python from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s", secondary_log_colors={ 'message': { 'ERROR': 'red', 'CRITICAL': 'red' } } ) ``` With [`dictConfig`][dictConfig] ------------------------------- ```python logging.config.dictConfig({ 'formatters': { 'colored': { '()': 'colorlog.ColoredFormatter', 'format': "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s" } } }) ``` A full example dictionary can be found in `tests/test_colorlog.py`. With [`fileConfig`][fileConfig] ------------------------------- ```ini ... [formatters] keys=color [formatter_color] class=colorlog.ColoredFormatter format=%(log_color)s%(levelname)-8s%(reset)s %(bg_blue)s[%(name)s]%(reset)s %(message)s from fileConfig datefmt=%m-%d %H:%M:%S ``` An instance of ColoredFormatter created with those arguments will then be used by any handlers that are configured to use the `color` formatter. A full example configuration can be found in `tests/test_config.ini`. With custom log levels ---------------------- ColoredFormatter will work with custom log levels added with [`logging.addLevelName`][addLevelName]: ```python import logging, colorlog TRACE = 5 logging.addLevelName(TRACE, 'TRACE') formatter = colorlog.ColoredFormatter(log_colors={'TRACE': 'yellow'}) handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger('example') logger.addHandler(handler) logger.setLevel('TRACE') logger.log(TRACE, 'a message using a custom level') ``` Compatibility ============= colorlog works on Python 2.6 and above, including Python 3. On Windows, [colorama] is required for `colorlog` to work properly. It will automatically be included when installing `colorlog` on windows. Tests ===== Tests similar to the above examples are found in `tests/test_colorlog.py`. [`tox`][tox] will run the tests under all compatible python versions. Projects using colorlog ----------------------- - [Counterparty] - [Errbot] - [Pythran] - [zenlog] Licence ------- Copyright (c) 2012 Sam Clements Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [dictConfig]: http://docs.python.org/3/library/logging.config.html#logging.config.dictConfig [fileConfig]: http://docs.python.org/3/library/logging.config.html#logging.config.fileConfig [addLevelName]: https://docs.python.org/3/library/logging.html#logging.addLevelNam[addLevelN]e [Formatter]: http://docs.python.org/3/library/logging.html#logging.Formatter [tox]: http://tox.readthedocs.org/ [Arch AUR]: https://aur.archlinux.org/packages/python-colorlog/ [BSD ports]: https://www.freshports.org/devel/py-colorlog/ [colorama]: https://pypi.python.org/pypi/colorama [Conda]: https://anaconda.org/auto/colorlog [Counterparty]: https://counterparty.io/ [Debian]: https://packages.debian.org/jessie/python-colorlog [Errbot]: http://errbot.io/ [Fedora packaging scripts]: https://github.com/bartv/python-colorlog [Gentoo]: https://packages.gentoo.org/packages/dev-python/colorlog [OpenSuse]: http://rpm.pbone.net/index.php3?stat=3&search=python-colorlog&srodzaj=3 [Pythran]: http://pythonhosted.org/pythran/DEVGUIDE.html [Ubuntu]: https://launchpad.net/python-colorlog [zenlog]: https://github.com/ManufacturaInd/python-zenlog python-colorlog-4.1.0/LICENSE0000644000232200023220000000211613603360546016234 0ustar debalancedebalanceThe MIT License (MIT) Copyright (c) 2018 Sam Clements Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-colorlog-4.1.0/MANIFEST.in0000644000232200023220000000012313603360546016761 0ustar debalancedebalanceinclude README.md include LICENSE include colorlog/tests/test_config.ini graft doc python-colorlog-4.1.0/colorlog/0000755000232200023220000000000013603360546017047 5ustar debalancedebalancepython-colorlog-4.1.0/colorlog/__init__.py0000644000232200023220000000117313603360546021162 0ustar debalancedebalance"""A logging formatter for colored output.""" from __future__ import absolute_import from colorlog.colorlog import ( escape_codes, default_log_colors, ColoredFormatter, LevelFormatter, TTYColoredFormatter) from colorlog.logging import ( basicConfig, root, getLogger, log, debug, info, warning, error, exception, critical, StreamHandler) __all__ = ('ColoredFormatter', 'default_log_colors', 'escape_codes', 'basicConfig', 'root', 'getLogger', 'debug', 'info', 'warning', 'error', 'exception', 'critical', 'log', 'exception', 'StreamHandler', 'LevelFormatter', 'TTYColoredFormatter') python-colorlog-4.1.0/colorlog/escape_codes.py0000644000232200023220000000233513603360546022041 0ustar debalancedebalance""" Generates a dictionary of ANSI escape codes. http://en.wikipedia.org/wiki/ANSI_escape_code Uses colorama as an optional dependency to support color on Windows """ try: import colorama except ImportError: pass else: colorama.init() __all__ = ('escape_codes', 'parse_colors') # Returns escape codes from format codes def esc(*x): return '\033[' + ';'.join(x) + 'm' # The initial list of escape codes escape_codes = { 'reset': esc('0'), 'bold': esc('01'), 'thin': esc('02') } # The color names COLORS = [ 'black', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white' ] PREFIXES = [ # Foreground without prefix ('3', ''), ('01;3', 'bold_'), ('02;3', 'thin_'), # Foreground with fg_ prefix ('3', 'fg_'), ('01;3', 'fg_bold_'), ('02;3', 'fg_thin_'), # Background with bg_ prefix - bold/light works differently ('4', 'bg_'), ('10', 'bg_bold_'), ] for prefix, prefix_name in PREFIXES: for code, name in enumerate(COLORS): escape_codes[prefix_name + name] = esc(prefix + str(code)) def parse_colors(sequence): """Return escape codes from a color sequence.""" return ''.join(escape_codes[n] for n in sequence.split(',') if n) python-colorlog-4.1.0/colorlog/logging.py0000644000232200023220000000251613603360546021053 0ustar debalancedebalance"""Wrappers around the logging module.""" from __future__ import absolute_import import functools import logging from colorlog.colorlog import ColoredFormatter BASIC_FORMAT = "%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s" def basicConfig(**kwargs): """Call ``logging.basicConfig`` and override the formatter it creates.""" logging.basicConfig(**kwargs) logging._acquireLock() try: stream = logging.root.handlers[0] stream.setFormatter( ColoredFormatter( fmt=kwargs.get('format', BASIC_FORMAT), datefmt=kwargs.get('datefmt', None))) finally: logging._releaseLock() def ensure_configured(func): """Modify a function to call ``basicConfig`` first if no handlers exist.""" @functools.wraps(func) def wrapper(*args, **kwargs): if len(logging.root.handlers) == 0: basicConfig() return func(*args, **kwargs) return wrapper root = logging.root getLogger = logging.getLogger debug = ensure_configured(logging.debug) info = ensure_configured(logging.info) warning = ensure_configured(logging.warning) error = ensure_configured(logging.error) critical = ensure_configured(logging.critical) log = ensure_configured(logging.log) exception = ensure_configured(logging.exception) StreamHandler = logging.StreamHandler python-colorlog-4.1.0/colorlog/colorlog.py0000644000232200023220000001745613603360546021256 0ustar debalancedebalance"""The ColoredFormatter class.""" from __future__ import absolute_import import logging import sys from colorlog.escape_codes import escape_codes, parse_colors __all__ = ('escape_codes', 'default_log_colors', 'ColoredFormatter', 'LevelFormatter', 'TTYColoredFormatter') # The default colors to use for the debug levels default_log_colors = { 'DEBUG': 'white', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } # The default format to use for each style default_formats = { '%': '%(log_color)s%(levelname)s:%(name)s:%(message)s', '{': '{log_color}{levelname}:{name}:{message}', '$': '${log_color}${levelname}:${name}:${message}' } class ColoredRecord(object): """ Wraps a LogRecord, adding named escape codes to the internal dict. The internal dict is used when formatting the message (by the PercentStyle, StrFormatStyle, and StringTemplateStyle classes). """ def __init__(self, record): """Add attributes from the escape_codes dict and the record.""" self.__dict__.update(escape_codes) self.__dict__.update(record.__dict__) # Keep a reference to the original record so ``__getattr__`` can # access functions that are not in ``__dict__`` self.__record = record def __getattr__(self, name): return getattr(self.__record, name) class ColoredFormatter(logging.Formatter): """ A formatter that allows colors to be placed in the format string. Intended to help in creating more readable logging output. """ def __init__(self, fmt=None, datefmt=None, style='%', log_colors=None, reset=True, secondary_log_colors=None): """ Set the format and colors the ColoredFormatter will use. The ``fmt``, ``datefmt`` and ``style`` args are passed on to the ``logging.Formatter`` constructor. The ``secondary_log_colors`` argument can be used to create additional ``log_color`` attributes. Each key in the dictionary will set ``{key}_log_color``, using the value to select from a different ``log_colors`` set. :Parameters: - fmt (str): The format string to use - datefmt (str): A format string for the date - log_colors (dict): A mapping of log level names to color names - reset (bool): Implicitly append a color reset to all records unless False - style ('%' or '{' or '$'): The format style to use. (*No meaning prior to Python 3.2.*) - secondary_log_colors (dict): Map secondary ``log_color`` attributes. (*New in version 2.6.*) """ if fmt is None: if sys.version_info > (3, 2): fmt = default_formats[style] else: fmt = default_formats['%'] if sys.version_info > (3, 8) and isinstance(self, LevelFormatter) \ and isinstance(fmt, dict): super(ColoredFormatter, self).__init__( fmt, datefmt, style, validate=False) elif sys.version_info > (3, 2): super(ColoredFormatter, self).__init__(fmt, datefmt, style) elif sys.version_info > (2, 7): super(ColoredFormatter, self).__init__(fmt, datefmt) else: logging.Formatter.__init__(self, fmt, datefmt) self.log_colors = ( log_colors if log_colors is not None else default_log_colors) self.secondary_log_colors = secondary_log_colors self.reset = reset def color(self, log_colors, level_name): """Return escape codes from a ``log_colors`` dict.""" return parse_colors(log_colors.get(level_name, "")) def format(self, record): """Format a message from a record object.""" record = ColoredRecord(record) record.log_color = self.color(self.log_colors, record.levelname) # Set secondary log colors if self.secondary_log_colors: for name, log_colors in self.secondary_log_colors.items(): color = self.color(log_colors, record.levelname) setattr(record, name + '_log_color', color) # Format the message if sys.version_info > (2, 7): message = super(ColoredFormatter, self).format(record) else: message = logging.Formatter.format(self, record) # Add a reset code to the end of the message # (if it wasn't explicitly added in format str) if self.reset and not message.endswith(escape_codes['reset']): message += escape_codes['reset'] return message class LevelFormatter(ColoredFormatter): """An extension of ColoredFormatter that uses per-level format strings.""" def __init__(self, fmt=None, datefmt=None, style='%', log_colors=None, reset=True, secondary_log_colors=None): """ Set the per-loglevel format that will be used. Supports fmt as a dict. All other args are passed on to the ``colorlog.ColoredFormatter`` constructor. :Parameters: - fmt (dict): A mapping of log levels (represented as strings, e.g. 'WARNING') to different formatters. (*New in version 2.7.0) (All other parameters are the same as in colorlog.ColoredFormatter) Example: formatter = colorlog.LevelFormatter(fmt={ 'DEBUG':'%(log_color)s%(msg)s (%(module)s:%(lineno)d)', 'INFO': '%(log_color)s%(msg)s', 'WARNING': '%(log_color)sWARN: %(msg)s (%(module)s:%(lineno)d)', 'ERROR': '%(log_color)sERROR: %(msg)s (%(module)s:%(lineno)d)', 'CRITICAL': '%(log_color)sCRIT: %(msg)s (%(module)s:%(lineno)d)', }) """ if sys.version_info > (2, 7): super(LevelFormatter, self).__init__( fmt=fmt, datefmt=datefmt, style=style, log_colors=log_colors, reset=reset, secondary_log_colors=secondary_log_colors) else: ColoredFormatter.__init__( self, fmt=fmt, datefmt=datefmt, style=style, log_colors=log_colors, reset=reset, secondary_log_colors=secondary_log_colors) self.style = style self.fmt = fmt def format(self, record): """Customize the message format based on the log level.""" if isinstance(self.fmt, dict): self._fmt = self.fmt[record.levelname] if sys.version_info > (3, 2): # Update self._style because we've changed self._fmt # (code based on stdlib's logging.Formatter.__init__()) if self.style not in logging._STYLES: raise ValueError('Style must be one of: %s' % ','.join( logging._STYLES.keys())) self._style = logging._STYLES[self.style][0](self._fmt) if sys.version_info > (2, 7): message = super(LevelFormatter, self).format(record) else: message = ColoredFormatter.format(self, record) return message class TTYColoredFormatter(ColoredFormatter): """ Blanks all color codes if not running under a TTY. This is useful when you want to be able to pipe colorlog output to a file. """ def __init__(self, *args, **kwargs): """Overwrite the `reset` argument to False if stream is not a TTY.""" self.stream = kwargs.pop('stream') # Both `reset` and `isatty` must be true to insert reset codes. kwargs['reset'] = kwargs.get('reset', True) and self.stream.isatty() ColoredFormatter.__init__(self, *args, **kwargs) def color(self, log_colors, level_name): """Only returns colors if STDOUT is a TTY.""" if not self.stream.isatty(): log_colors = {} return ColoredFormatter.color(self, log_colors, level_name) python-colorlog-4.1.0/colorlog/tests/0000755000232200023220000000000013603360546020211 5ustar debalancedebalancepython-colorlog-4.1.0/colorlog/tests/test_config.ini0000644000232200023220000000047113603360546023220 0ustar debalancedebalance[loggers] keys=root [logger_root] handlers=stream level=DEBUG [formatters] keys=color [formatter_color] class=colorlog.ColoredFormatter format=%(log_color)s%(levelname)s:%(name)s:%(message)s:test_config.ini datefmt=%H:%M:%S [handlers] keys=stream [handler_stream] class=StreamHandler formatter=color args=() python-colorlog-4.1.0/colorlog/tests/test_colorlog.py0000644000232200023220000000620113603360546023441 0ustar debalancedebalance"""Test the colorlog.colorlog module.""" import sys import pytest import colorlog def test_colored_formatter(create_and_test_logger): create_and_test_logger() def test_custom_colors(create_and_test_logger): """Disable all colors and check no escape codes are output.""" create_and_test_logger( log_colors={}, reset=False, validator=lambda line: '\x1b[' not in line) def test_reset(create_and_test_logger): create_and_test_logger( reset=True, validator=lambda l: l.endswith('\x1b[0m')) def test_no_reset(create_and_test_logger): create_and_test_logger( fmt="%(reset)s%(log_color)s%(levelname)s:%(name)s:%(message)s", reset=False, # Check that each line does not end with an escape code validator=lambda line: not line.endswith('\x1b[0m')) def test_secondary_colors(create_and_test_logger): expected = ':\x1b[31mtest_secondary_colors:\x1b[34m' create_and_test_logger( fmt=( "%(log_color)s%(levelname)s:" "%(name_log_color)s%(name)s:" "%(message_log_color)s%(message)s" ), secondary_log_colors={ 'name': { 'DEBUG': 'red', 'INFO': 'red', 'WARNING': 'red', 'ERROR': 'red', 'CRITICAL': 'red', }, 'message': { 'DEBUG': 'blue', 'INFO': 'blue', 'WARNING': 'blue', 'ERROR': 'blue', 'CRITICAL': 'blue', } }, validator=lambda line: expected in line) def test_some_secondary_colors(create_and_test_logger): lines = create_and_test_logger( fmt="%(message_log_color)s%(message)s", secondary_log_colors={ 'message': { 'ERROR': 'red', 'CRITICAL': 'red' } }) # Check that only two lines are colored assert len([l for l in lines if '\x1b[31m' in l]) == 2 def test_percent_style(create_and_test_logger): create_and_test_logger( fmt='%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s', style='%') @pytest.mark.skipif(sys.version_info < (3, 2), reason="requires python3.2") def test_braces_style(create_and_test_logger): create_and_test_logger( fmt='{log_color}{levelname}{reset}:{name}:{message}', style='{') @pytest.mark.skipif(sys.version_info < (3, 2), reason="requires python3.2") def test_template_style(create_and_test_logger): create_and_test_logger( fmt='${log_color}${levelname}${reset}:${name}:${message}', style='$') def test_ttycolorlog(create_and_test_logger, monkeypatch): monkeypatch.setattr(sys.stderr, 'isatty', lambda: True) create_and_test_logger( formatter_class=colorlog.TTYColoredFormatter, validator=lambda line: '\x1b[' in line, stream=sys.stderr) def test_ttycolorlog_notty(create_and_test_logger, monkeypatch): monkeypatch.setattr(sys.stderr, 'isatty', lambda: False) create_and_test_logger( formatter_class=colorlog.TTYColoredFormatter, validator=lambda line: '\x1b[' not in line, stream=sys.stderr) python-colorlog-4.1.0/colorlog/tests/test_exports.py0000644000232200023220000000053313603360546023327 0ustar debalancedebalance"""Test that `from colorlog import *` works correctly.""" from colorlog import * # noqa def test_exports(): assert { 'ColoredFormatter', 'default_log_colors', 'escape_codes', 'basicConfig', 'root', 'getLogger', 'debug', 'info', 'warning', 'error', 'exception', 'critical', 'log', 'exception' } < set(globals()) python-colorlog-4.1.0/colorlog/tests/test_logging.py0000644000232200023220000000047413603360546023255 0ustar debalancedebalance"""Test the colorlog.logging module.""" import logging import colorlog def test_logging_module(test_logger): test_logger(logging) def test_colorlog_module(test_logger): test_logger(colorlog) def test_colorlog_basicConfig(test_logger): colorlog.basicConfig() test_logger(colorlog.getLogger()) python-colorlog-4.1.0/colorlog/tests/test_config.py0000644000232200023220000000236613603360546023076 0ustar debalancedebalance"""Test using colorlog with logging.config""" import logging import logging.config import os.path import sys import pytest def path(filename): """Return an absolute path to a file in the current directory.""" return os.path.join(os.path.dirname(os.path.realpath(__file__)), filename) def test_build_from_file(test_logger): logging.config.fileConfig(path("test_config.ini")) test_logger(logging.getLogger(), lambda l: ':test_config.ini' in l) @pytest.mark.skipif(sys.version_info < (2, 7), reason="requires python2.7") def test_build_from_dictionary(test_logger): logging.config.dictConfig({ 'version': 1, 'formatters': { 'colored': { '()': 'colorlog.ColoredFormatter', 'format': "%(log_color)s%(levelname)s:%(name)s:%(message)s:dict", } }, 'handlers': { 'stream': { 'class': 'logging.StreamHandler', 'formatter': 'colored', 'level': 'DEBUG' }, }, 'loggers': { '': { 'handlers': ['stream'], 'level': 'DEBUG', }, }, }) test_logger(logging.getLogger(), lambda l: ':dict' in l) python-colorlog-4.1.0/colorlog/tests/conftest.py0000644000232200023220000000436313603360546022416 0ustar debalancedebalance"""Fixtures that can be used in other tests.""" from __future__ import print_function import inspect import logging import sys import pytest import colorlog class TestingStreamHandler(logging.StreamHandler): """Raise errors to be caught by py.test instead of printing to stdout.""" def handleError(self, record): _type, value, _traceback = sys.exc_info() raise value def assert_log_message(log_function, message, capsys): """Call a log function and check the message has been output.""" log_function(message) out, err = capsys.readouterr() # Print the output so that py.test shows it when a test fails print(err, end='', file=sys.stderr) # Assert the message send to the logger was output assert message in err, 'Log message not output to STDERR' return err @pytest.fixture() def reset_loggers(): logging.root.handlers = list() logging.root.setLevel(logging.DEBUG) @pytest.fixture() def test_logger(reset_loggers, capsys): def function(logger, validator=None): lines = [ assert_log_message(logger.debug, 'a debug message', capsys), assert_log_message(logger.info, 'an info message', capsys), assert_log_message(logger.warning, 'a warning message', capsys), assert_log_message(logger.error, 'an error message', capsys), assert_log_message(logger.critical, 'a critical message', capsys) ] if validator is not None: for line in lines: valid = validator(line.strip()) assert valid, "{!r} did not validate".format(line.strip()) return lines return function @pytest.fixture() def create_and_test_logger(test_logger): def function(*args, **kwargs): validator = kwargs.pop('validator', None) formatter_cls = kwargs.pop('formatter_class', colorlog.ColoredFormatter) formatter = formatter_cls(*args, **kwargs) stream = TestingStreamHandler(stream=sys.stderr) stream.setLevel(logging.DEBUG) stream.setFormatter(formatter) logger = logging.getLogger(inspect.stack()[1][3]) logger.setLevel(logging.DEBUG) logger.addHandler(stream) return test_logger(logger, validator) return function python-colorlog-4.1.0/colorlog/tests/test_example.py0000644000232200023220000000047413603360546023262 0ustar debalancedebalancedef test_example(): """Tests the usage example from the README""" import colorlog handler = colorlog.StreamHandler() handler.setFormatter(colorlog.ColoredFormatter( '%(log_color)s%(levelname)s:%(name)s:%(message)s')) logger = colorlog.getLogger('example') logger.addHandler(handler) python-colorlog-4.1.0/colorlog/tests/test_escape_codes.py0000644000232200023220000000257513603360546024250 0ustar debalancedebalance"""Test the colorlog.escape_codes module.""" from colorlog.escape_codes import escape_codes, esc, parse_colors import pytest def test_esc(): assert esc('1', '2', '3') == '\033[1;2;3m' def test_reset(): assert escape_codes['reset'] == '\033[0m' def test_bold_color(): assert escape_codes['bold_red'] == '\033[01;31m' def test_fg_color(): assert escape_codes['fg_bold_yellow'] == '\033[01;33m' def test_bg_color(): assert escape_codes['bg_bold_blue'] == '\033[104m' def test_rainbow(create_and_test_logger): """Test *all* escape codes, useful to ensure backwards compatibility.""" create_and_test_logger( "%(log_color)s%(levelname)s%(reset)s:%(bold_black)s%(name)s:" "%(message)s%(reset)s:" "%(bold_red)sr%(red)sa%(yellow)si%(green)sn%(bold_blue)sb" "%(blue)so%(purple)sw%(reset)s " "%(fg_bold_red)sr%(fg_red)sa%(fg_yellow)si%(fg_green)sn" "%(fg_bold_blue)sb%(fg_blue)so%(fg_purple)sw%(reset)s " "%(bg_red)sr%(bg_bold_red)sa%(bg_yellow)si%(bg_green)sn" "%(bg_bold_blue)sb%(bg_blue)so%(bg_purple)sw%(reset)s " ) def test_parse_colors(): assert parse_colors('reset') == '\033[0m' def test_parse_multiple_colors(): assert parse_colors('bold_red,bg_bold_blue') == '\033[01;31m\033[104m' def test_parse_invalid_colors(): with pytest.raises(KeyError): parse_colors('false') python-colorlog-4.1.0/setup.py0000644000232200023220000000236413603360546016746 0ustar debalancedebalancefrom setuptools import setup setup( name='colorlog', version='4.1.0', description='Log formatting with colors!', long_description=open('README.md').read(), long_description_content_type='text/markdown', author='Sam Clements', author_email='sam@borntyping.co.uk', url='https://github.com/borntyping/python-colorlog', license='MIT License', packages=['colorlog', 'colorlog.tests'], extras_require={ ':sys_platform=="win32"': [ 'colorama' ] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Terminals', 'Topic :: Utilities', ], ) python-colorlog-4.1.0/tox.ini0000644000232200023220000000066213603360546016546 0ustar debalancedebalance[tox] minversion=1.8.0 envlist=py26-{test,test-colorama},py{27,35,36,37,38,py,py3}-{test,test-colorama,lint} skip_missing_interpreters=true [testenv] commands= lint: flake8 colorlog test: py.test -v {posargs} colorlog deps= colorama: colorama lint: flake8_docstrings test: pytest [testenv:release] commands= python setup.py sdist bdist_wheel twine upload dist/* skip_sdist=true deps= wheel twine