python-colorlog-6.6.0/0000755000232200023220000000000014142253140015224 5ustar debalancedebalancepython-colorlog-6.6.0/doc/0000755000232200023220000000000014142253140015771 5ustar debalancedebalancepython-colorlog-6.6.0/doc/example.py0000644000232200023220000000200714142253140017775 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-6.6.0/doc/yaml_example.yaml0000644000232200023220000000150514142253140021333 0ustar debalancedebalanceversion: 1 formatters: logging: format: '%(asctime)s - %(name)-11s - %(levelname)-8s - %(message)-60s - formatter=logging.Formatter' colorlog: (): 'colorlog.ColoredFormatter' format: '%(log_color)s%(asctime)s - %(name)-11s - %(levelname)-8s - %(message)-60s - formatter=colorlog.ColoredFormatter' handlers: console: class: logging.StreamHandler level: DEBUG formatter: logging stream: ext://sys.stdout file: class: logging.FileHandler level: WARNING formatter: logging filename: doc/example_yaml.log colour: class: logging.StreamHandler level: DEBUG formatter: colorlog loggers: '': level: DEBUG handlers: [console] example: level: INFO handlers: [file] propagate: yes application: level: INFO handlers: [colour, file] propagate: no python-colorlog-6.6.0/doc/custom_level.py0000644000232200023220000000073114142253140021045 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-6.6.0/doc/yaml_example.py0000644000232200023220000000351614142253140021025 0ustar debalancedebalance""" Based on an example provided by Ricardo Reis. https://github.com/ricardo-reis-1970/colorlog-YAML This configures the `logging` module from a YAML file, and provides specific configuration for the loggers named 'application' and 'example'. """ import logging.config import pathlib import yaml def config(): """ Configure `logging` from a YAML file. You might adjust this function to provide the configuration path as an argument. """ path = pathlib.Path(__file__).with_suffix(".yaml") logging.config.dictConfig(yaml.safe_load(path.read_text())) if __name__ == "__main__": config() root = logging.getLogger() root.debug("Root logs debug example") root.info("Root logs written to console without colours") root.warning("Root logs warning") root.error("Root logs error") root.critical("Root logs critical") unknown = logging.getLogger("unknown") unknown.debug("Unknown logs debug example") unknown.info("Unknown logs propagated to root logger") unknown.warning("Unknown logs warning") unknown.error("Unknown logs error") unknown.critical("Unknown logs critical") application = logging.getLogger("application") application.debug("Application logs debug filtered by log level") application.info("Application logs written to console and file") application.warning("Application logs not propagated to the root logger") application.error("Application logs error example") application.critical("Application logs critical example") example = logging.getLogger("example") example.debug("Example logs debug filtered by log level") example.info("Example logs configured to write to file") example.warning("Example logs propagated to the root logger") example.error("Example logs error example") example.critical("Example logs critical example") python-colorlog-6.6.0/doc/colors.py0000644000232200023220000000041314142253140017642 0ustar debalancedebalance""" Print every color code supported by colorlog in it's own color. """ import colorlog.escape_codes if __name__ == "__main__": for key, value in colorlog.escape_codes.escape_codes.items(): print(value, key, colorlog.escape_codes.escape_codes["reset"]) python-colorlog-6.6.0/doc/example.png0000644000232200023220000002465714142253140020150 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;$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7Ekda8BWKyGKE|LEaHF+85O&˦ш9O(ILs{&'F'<#u&e8e7. Q*V3ᾕBwlyczfx 8OxD}']L|b)ECf[|v{Öv+Vئ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') ``` Tests ----- Tests similar to the above examples are found in `tests/test_colorlog.py`. Status ------ colorlog is in maintenance mode. I try and ensure bugfixes are published, but compatibility with Python 2.6+ and Python 3+ makes this a difficult codebase to add features to. Any changes that might break backwards compatibility for existing users will not be considered. Alternatives ------------ There are some more modern libraries for improving Python logging you may find useful. - [structlog] - [jsonlog] Projects using colorlog ----------------------- GitHub provides [a list of projects that depend on colorlog][dependents]. Some early adopters included [Errbot], [Pythran], and [zenlog]. Licence ------- Copyright (c) 2012-2021 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.addLevelName [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/conda-forge/colorlog [Debian]: https://packages.debian.org/buster/python3-colorlog [Errbot]: http://errbot.io/ [Fedora]: https://src.fedoraproject.org/rpms/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]: https://github.com/serge-sans-paille/pythran [Ubuntu]: https://launchpad.net/python-colorlog [zenlog]: https://github.com/ManufacturaInd/python-zenlog [structlog]: https://www.structlog.org/en/stable/ [jsonlog]: https://github.com/borntyping/jsonlog [dependents]: https://github.com/borntyping/python-colorlog/network/dependents?package_id=UGFja2FnZS01MDk3NDcyMQ%3D%3D python-colorlog-6.6.0/LICENSE0000644000232200023220000000212314142253140016227 0ustar debalancedebalanceThe MIT License (MIT) Copyright (c) 2012-2021 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-6.6.0/MANIFEST.in0000644000232200023220000000021114142253140016754 0ustar debalancedebalanceglobal-exclude *.py[co] recursive-include colorlog/tests/ *.py *.ini recursive-include doc/ *.py *.png include LICENSE include README.md python-colorlog-6.6.0/colorlog/0000755000232200023220000000000014142253140017044 5ustar debalancedebalancepython-colorlog-6.6.0/colorlog/py.typed0000644000232200023220000000000014142253140020531 0ustar debalancedebalancepython-colorlog-6.6.0/colorlog/__init__.py0000644000232200023220000000223414142253140021156 0ustar debalancedebalance"""A logging formatter for colored output.""" import sys import warnings from colorlog.formatter import ( ColoredFormatter, LevelFormatter, TTYColoredFormatter, default_log_colors, ) from colorlog.wrappers import ( CRITICAL, DEBUG, ERROR, FATAL, INFO, NOTSET, StreamHandler, WARN, WARNING, basicConfig, critical, debug, error, exception, getLogger, info, log, root, warning, ) __all__ = ( "CRITICAL", "DEBUG", "ERROR", "FATAL", "INFO", "NOTSET", "WARN", "WARNING", "ColoredFormatter", "LevelFormatter", "StreamHandler", "TTYColoredFormatter", "basicConfig", "critical", "debug", "default_log_colors", "error", "exception", "exception", "getLogger", "info", "log", "root", "warning", ) if sys.version_info < (3, 6): warnings.warn( "Colorlog requires Python 3.6 or above. Pin 'colorlog<5' to your dependencies " "if you require compatibility with older versions of Python. See " "https://github.com/borntyping/python-colorlog#status for more information." ) python-colorlog-6.6.0/colorlog/escape_codes.py0000644000232200023220000000460514142253140022040 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 """ import sys try: import colorama except ImportError: pass else: if sys.platform == "win32": colorama.init(strip=False) __all__ = ("escape_codes", "parse_colors") # Returns escape codes from format codes def esc(*codes: int) -> str: return "\033[" + ";".join(str(code) for code in codes) + "m" escape_codes = { "reset": esc(0), "bold": esc(1), "thin": esc(2), } escape_codes_foreground = { "black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "purple": 35, "cyan": 36, "white": 37, "light_black": 90, "light_red": 91, "light_green": 92, "light_yellow": 93, "light_blue": 94, "light_purple": 95, "light_cyan": 96, "light_white": 97, } escape_codes_background = { "black": 40, "red": 41, "green": 42, "yellow": 43, "blue": 44, "purple": 45, "cyan": 46, "white": 47, "light_black": 100, "light_red": 101, "light_green": 102, "light_yellow": 103, "light_blue": 104, "light_purple": 105, "light_cyan": 106, "light_white": 107, # Bold background colors don't exist, # but we used to provide these names. "bold_black": 100, "bold_red": 101, "bold_green": 102, "bold_yellow": 103, "bold_blue": 104, "bold_purple": 105, "bold_cyan": 106, "bold_white": 107, } # Foreground without prefix for name, code in escape_codes_foreground.items(): escape_codes["%s" % name] = esc(code) escape_codes["bold_%s" % name] = esc(1, code) escape_codes["thin_%s" % name] = esc(2, code) # Foreground with fg_ prefix for name, code in escape_codes_foreground.items(): escape_codes["fg_%s" % name] = esc(code) escape_codes["fg_bold_%s" % name] = esc(1, code) escape_codes["fg_thin_%s" % name] = esc(2, code) # Background with bg_ prefix for name, code in escape_codes_background.items(): escape_codes["bg_%s" % name] = esc(code) # 256 colour support for code in range(256): escape_codes["fg_%d" % code] = esc(38, 5, code) escape_codes["bg_%d" % code] = esc(48, 5, code) def parse_colors(string: str) -> str: """Return escape codes from a color sequence string.""" return "".join(escape_codes[n] for n in string.split(",") if n) python-colorlog-6.6.0/colorlog/wrappers.py0000644000232200023220000000417614142253140021271 0ustar debalancedebalance"""Wrappers around the logging module.""" import functools import logging import typing from logging import ( CRITICAL, DEBUG, ERROR, FATAL, INFO, NOTSET, StreamHandler, WARN, WARNING, getLogger, root, ) import colorlog.formatter __all__ = ( "CRITICAL", "DEBUG", "ERROR", "FATAL", "INFO", "NOTSET", "WARN", "WARNING", "StreamHandler", "basicConfig", "critical", "debug", "error", "exception", "getLogger", "info", "log", "root", "warning", ) def basicConfig( style: str = "%", log_colors: typing.Optional[colorlog.formatter.LogColors] = None, reset: bool = True, secondary_log_colors: typing.Optional[colorlog.formatter.SecondaryLogColors] = None, format: str = "%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s", datefmt: typing.Optional[str] = None, **kwargs ) -> None: """Call ``logging.basicConfig`` and override the formatter it creates.""" logging.basicConfig(**kwargs) logging._acquireLock() # type: ignore try: handler = logging.root.handlers[0] handler.setFormatter( colorlog.formatter.ColoredFormatter( fmt=format, datefmt=datefmt, style=style, log_colors=log_colors, reset=reset, secondary_log_colors=secondary_log_colors, stream=kwargs.get("stream", None), ) ) finally: logging._releaseLock() # type: ignore def ensure_configured(func): """Modify a function to call our 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 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) python-colorlog-6.6.0/colorlog/formatter.py0000644000232200023220000001643114142253140021426 0ustar debalancedebalance"""The ColoredFormatter class.""" import logging import os import sys import typing import colorlog.escape_codes __all__ = ( "default_log_colors", "ColoredFormatter", "LevelFormatter", "TTYColoredFormatter", ) # Type aliases used in function signatures. EscapeCodes = typing.Mapping[str, str] LogColors = typing.Mapping[str, str] SecondaryLogColors = typing.Mapping[str, LogColors] # 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: """ Wraps a LogRecord, adding 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: logging.LogRecord, escapes: EscapeCodes) -> None: self.__dict__.update(record.__dict__) self.__dict__.update(escapes) 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: typing.Optional[str] = None, datefmt: typing.Optional[str] = None, style: str = "%", log_colors: typing.Optional[LogColors] = None, reset: bool = True, secondary_log_colors: typing.Optional[SecondaryLogColors] = None, validate: bool = True, stream: typing.Optional[typing.IO] = None, no_color: bool = False, force_color: bool = False, ) -> 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.*) - validate (bool) Validate the format string. - stream (typing.IO) The stream formatted messages will be printed to. Used to toggle colour on non-TTY outputs. Optional. - no_color (bool): Disable color output. - force_color (bool): Enable color output. Takes precedence over `no_color`. """ # Select a default format if `fmt` is not provided. fmt = default_formats[style] if fmt is None else fmt if sys.version_info >= (3, 8): super().__init__(fmt, datefmt, style, validate) else: super().__init__(fmt, datefmt, style) self.log_colors = log_colors if log_colors is not None else default_log_colors self.secondary_log_colors = ( secondary_log_colors if secondary_log_colors is not None else {} ) self.reset = reset self.stream = stream self.no_color = no_color self.force_color = force_color def formatMessage(self, record: logging.LogRecord) -> str: """Format a message from a record object.""" escapes = self._escape_code_map(record.levelname) wrapper = ColoredRecord(record, escapes) message = super().formatMessage(wrapper) # type: ignore message = self._append_reset(message, escapes) return message def _escape_code_map(self, item: str) -> EscapeCodes: """ Build a map of keys to escape codes for use in message formatting. If _blank_escape_codes() returns True, all values will be an empty string. """ codes = {**colorlog.escape_codes.escape_codes} codes.setdefault("log_color", self._get_escape_code(self.log_colors, item)) for name, colors in self.secondary_log_colors.items(): codes.setdefault("%s_log_color" % name, self._get_escape_code(colors, item)) if self._blank_escape_codes(): codes = {key: "" for key in codes.keys()} return codes def _blank_escape_codes(self): """Return True if we should be prevented from printing escape codes.""" if self.force_color or "FORCE_COLOR" in os.environ: return False if self.no_color or "NO_COLOR" in os.environ: return True if self.stream is not None and not self.stream.isatty(): return True return False @staticmethod def _get_escape_code(log_colors: LogColors, item: str) -> str: """Extract a color sequence from a mapping, and return escape codes.""" return colorlog.escape_codes.parse_colors(log_colors.get(item, "")) def _append_reset(self, message: str, escapes: EscapeCodes) -> str: """Add a reset code to the end of the message, if it's not already there.""" reset_escape_code = escapes["reset"] if self.reset and not message.endswith(reset_escape_code): message += reset_escape_code return message class LevelFormatter: """An extension of ColoredFormatter that uses per-level format strings.""" def __init__(self, fmt: typing.Mapping[str, str], **kwargs: typing.Any) -> None: """ Configure a ColoredFormatter with its own format string for each log level. 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 format strings. (*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%(message)s (%(module)s:%(lineno)d)", "INFO": "%(log_color)s%(message)s", "WARNING": "%(log_color)sWRN: %(message)s (%(module)s:%(lineno)d)", "ERROR": "%(log_color)sERR: %(message)s (%(module)s:%(lineno)d)", "CRITICAL": "%(log_color)sCRT: %(message)s (%(module)s:%(lineno)d)", } ) """ self.formatters = { level: ColoredFormatter(fmt=f, **kwargs) for level, f in fmt.items() } def format(self, record: logging.LogRecord) -> str: return self.formatters[record.levelname].format(record) # Provided for backwards compatibility. The features provided by this subclass are now # included directly in the `ColoredFormatter` class. TTYColoredFormatter = ColoredFormatter python-colorlog-6.6.0/colorlog/tests/0000755000232200023220000000000014142253140020206 5ustar debalancedebalancepython-colorlog-6.6.0/colorlog/tests/test_config.ini0000644000232200023220000000047114142253140023215 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-6.6.0/colorlog/tests/test_colorlog.py0000644000232200023220000000653114142253140023444 0ustar debalancedebalance"""Test the colorlog.colorlog module.""" import sys 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="%" ) def test_braces_style(create_and_test_logger): create_and_test_logger( fmt="{log_color}{levelname}{reset}:{name}:{message}", style="{" ) def test_template_style(create_and_test_logger): create_and_test_logger( fmt="${log_color}${levelname}${reset}:${name}:${message}", style="$" ) class TestLevelFormatter: def test_level_formatter(self, create_and_test_logger): create_and_test_logger( formatter_class=colorlog.LevelFormatter, fmt={ "DEBUG": "%(message)s", "INFO": "%(message)s", "WARNING": "%(message)s", "ERROR": "%(message)s", "CRITICAL": "%(message)s", }, ) 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-6.6.0/colorlog/tests/test_exports.py0000644000232200023220000000063414142253140023326 0ustar debalancedebalance"""Test that `from colorlog import *` works correctly.""" from colorlog import * # noqa def test_exports(): assert { "ColoredFormatter", "default_log_colors", "basicConfig", "root", "getLogger", "debug", "info", "warning", "error", "exception", "critical", "log", "exception", } < set(globals()) python-colorlog-6.6.0/colorlog/tests/test_config.py0000644000232200023220000000233714142253140023071 0ustar debalancedebalance"""Test using colorlog with logging.config""" import logging import logging.config import os.path 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) 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-6.6.0/colorlog/tests/conftest.py0000644000232200023220000000437014142253140022411 0ustar debalancedebalance"""Fixtures that can be used in other tests.""" 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(capsys, log_function, message, *args): """Call a log function and check the message has been output.""" log_function(message, *args) 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 % args 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(capsys, logger.debug, "a debug message %s", 1), assert_log_message(capsys, logger.info, "an info message %s", 2), assert_log_message(capsys, logger.warning, "a warning message %s", 3), assert_log_message(capsys, logger.error, "an error message %s", 4), assert_log_message(capsys, logger.critical, "a critical message %s", 5), ] if validator is not None: for line in lines: valid = validator(line.strip()) assert valid, f"{line.strip()!r} did not validate" 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-6.6.0/colorlog/tests/test_example.py0000644000232200023220000000050114142253140023246 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-6.6.0/colorlog/tests/test_escape_codes.py0000644000232200023220000000304314142253140024234 0ustar debalancedebalance"""Test the colorlog.escape_codes module.""" import pytest from colorlog.escape_codes import esc, escape_codes, parse_colors 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[1;31m" def test_fg_color(): assert escape_codes["fg_bold_yellow"] == "\033[1;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[1;31m\033[104m" def test_parse_invalid_colors(): with pytest.raises(KeyError): parse_colors("false") def test_256_colors(): for i in range(256): assert parse_colors("fg_%d" % i) == "\033[38;5;%dm" % i assert parse_colors("bg_%d" % i) == "\033[48;5;%dm" % i python-colorlog-6.6.0/colorlog/tests/test_wrappers.py0000644000232200023220000000227114142253140023464 0ustar debalancedebalance"""Test the colorlog.wrappers 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()) def test_reexports(): assert colorlog.root is logging.root assert colorlog.getLogger is logging.getLogger assert colorlog.StreamHandler is logging.StreamHandler assert colorlog.CRITICAL is logging.CRITICAL assert colorlog.FATAL is logging.FATAL assert colorlog.ERROR is logging.ERROR assert colorlog.WARNING is logging.WARNING assert colorlog.WARN is logging.WARN assert colorlog.INFO is logging.INFO assert colorlog.DEBUG is logging.DEBUG assert colorlog.NOTSET is logging.NOTSET def test_wrappers(): assert colorlog.debug is not logging.debug assert colorlog.info is not logging.info assert colorlog.warning is not logging.warning assert colorlog.error is not logging.error assert colorlog.critical is not logging.critical assert colorlog.log is not logging.log assert colorlog.exception is not logging.exception python-colorlog-6.6.0/setup.py0000644000232200023220000000251014142253140016734 0ustar debalancedebalancefrom setuptools import setup setup( name="colorlog", version="6.6.0", description="Add colours to the output of Python's logging module.", 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"], package_data={"colorlog": ["py.typed"]}, setup_requires=["setuptools>=38.6.0"], extras_require={ ':sys_platform=="win32"': ["colorama"], "development": ["black", "flake8", "mypy", "pytest", "types-colorama"], }, python_requires=">=3.6", 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 :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Topic :: Terminals", "Topic :: Utilities", ], ) python-colorlog-6.6.0/sample.py0000644000232200023220000000032014142253140017052 0ustar debalancedebalanceimport logging import colorlog fmt = "{log_color}{levelname} {name}: {message}" colorlog.basicConfig(level=logging.DEBUG, style="{", format=fmt, stream=None) log = logging.getLogger() log.warning("hello") python-colorlog-6.6.0/tox.ini0000644000232200023220000000013014142253140016531 0ustar debalancedebalance[tox] envlist = py36,py37,py38,py39,py310 [testenv] deps = pytest commands = pytest -v