├── .github └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── colorlog ├── __init__.py ├── escape_codes.py ├── formatter.py ├── py.typed ├── tests │ ├── conftest.py │ ├── test_colorlog.py │ ├── test_config.ini │ ├── test_config.py │ ├── test_escape_codes.py │ ├── test_example.py │ ├── test_exports.py │ └── test_wrappers.py └── wrappers.py ├── docs ├── CONTRIBUTING.md ├── colors.py ├── custom_level.py ├── example.png ├── example.py ├── yaml_example.py └── yaml_example.yaml ├── sample.py ├── setup.cfg ├── setup.py └── tox.ini /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: "CI" 2 | on: ["push", "pull_request"] 3 | jobs: 4 | lint: 5 | name: "🐍 Lint Python modules" 6 | runs-on: "ubuntu-latest" 7 | strategy: 8 | matrix: 9 | python-version: 10 | - "3.12" 11 | steps: 12 | - uses: "actions/checkout@master" 13 | - name: "🐍 Set up Python ${{ matrix.python-version }}" 14 | uses: "actions/setup-python@v2" 15 | with: 16 | python-version: "${{ matrix.python-version }}" 17 | - name: "🐍 Display Python version" 18 | run: "python --version" 19 | - name: "🐍 Install dependencies" 20 | run: "python -m pip install --user --pre black flake8 mypy types-PyYAML" 21 | - name: "🐍 Run mypy" 22 | run: "python -m mypy ." 23 | - name: "🐍 Run flake8" 24 | run: "python -m flake8" 25 | - name: "🐍 Run black" 26 | run: "python -m black --check ." 27 | test: 28 | name: "🐍 Test Python modules" 29 | runs-on: "ubuntu-latest" 30 | strategy: 31 | matrix: 32 | python-version: 33 | - "3.8" 34 | - "3.9" 35 | - "3.10" 36 | - "3.11" 37 | - "3.12" 38 | - "3.13" 39 | dependencies: 40 | - "" 41 | - "colorama" 42 | steps: 43 | - uses: "actions/checkout@master" 44 | - name: "🐍 Set up Python ${{ matrix.python-version }}" 45 | uses: "actions/setup-python@v2" 46 | with: 47 | python-version: "${{ matrix.python-version }}" 48 | allow-prereleases: true 49 | - name: "🐍 Display Python version" 50 | run: "python --version" 51 | - name: "🐍 Install dependencies" 52 | run: "python -m pip install --user pytest ${{ matrix.dependencies }}" 53 | - name: "🐍 Run pytest" 54 | run: "python -m pytest" 55 | publish: 56 | name: "📦 Publish Python distributions" 57 | if: "startsWith(github.ref, 'refs/tags')" 58 | runs-on: "ubuntu-latest" 59 | environment: "publish" 60 | permissions: 61 | id-token: write 62 | strategy: 63 | matrix: 64 | python-version: 65 | - "3.10" 66 | steps: 67 | - uses: "actions/checkout@master" 68 | - name: "🐍 Set up Python ${{ matrix.python-version }}" 69 | uses: "actions/setup-python@v2" 70 | with: 71 | python-version: "${{ matrix.python-version }}" 72 | - name: "🐍 Display Python version" 73 | run: "python --version" 74 | - name: "🐍 Install wheel" 75 | run: "python -m pip install wheel --user" 76 | - name: "🐍 Build a binary wheel and a source tarball" 77 | run: "python setup.py sdist bdist_wheel" 78 | - name: "📦 Publish package distributions to PyPI" 79 | uses: "pypa/gh-action-pypi-publish@release/v1" 80 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.egg-info/* 2 | *.pyc 3 | .cache 4 | .idea/ 5 | .tox 6 | build/* 7 | dist/* 8 | doc/*.log 9 | MANIFEST 10 | venv/ 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2012-2021 Sam Clements 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | global-exclude *.py[co] 2 | recursive-include colorlog/tests/ *.py *.ini 3 | recursive-include doc/ *.py *.png 4 | include LICENSE 5 | include README.md 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Log formatting with colors! 2 | 3 | [![](https://img.shields.io/pypi/v/colorlog.svg)](https://pypi.org/project/colorlog/) 4 | [![](https://img.shields.io/pypi/l/colorlog.svg)](https://pypi.org/project/colorlog/) 5 | 6 | Add colours to the output of Python's `logging` module. 7 | 8 | * [Source on GitHub](https://github.com/borntyping/python-colorlog) 9 | * [Packages on PyPI](https://pypi.org/pypi/colorlog/) 10 | 11 | ## Status 12 | 13 | colorlog currently requires Python 3.6 or higher. Older versions (below 5.x.x) 14 | support Python 2.6 and above. 15 | 16 | * colorlog 6.x requires Python 3.6 or higher. 17 | * colorlog 5.x is an interim version that will warn Python 2 users to downgrade. 18 | * colorlog 4.x is the final version supporting Python 2. 19 | 20 | [colorama] is included as a required dependency and initialised when using 21 | colorlog on Windows. 22 | 23 | This library is over a decade old and supported a wide set of Python versions 24 | for most of its life, which has made it a difficult library to add new features 25 | to. colorlog 6 may break backwards compatibility so that newer features 26 | can be added more easily, but may still not accept all changes or feature 27 | requests. colorlog 4 might accept essential bugfixes but should not be 28 | considered actively maintained and will not accept any major changes or new 29 | features. 30 | 31 | ## Installation 32 | 33 | Install from PyPI with: 34 | 35 | ```bash 36 | pip install colorlog 37 | ``` 38 | 39 | Several Linux distributions provide official packages ([Debian], [Arch], [Fedora], 40 | [Gentoo], [OpenSuse] and [Ubuntu]), and others have user provided packages 41 | ([BSD ports], [Conda]). 42 | 43 | ## Usage 44 | 45 | ```python 46 | import colorlog 47 | 48 | handler = colorlog.StreamHandler() 49 | handler.setFormatter(colorlog.ColoredFormatter( 50 | '%(log_color)s%(levelname)s:%(name)s:%(message)s')) 51 | 52 | logger = colorlog.getLogger('example') 53 | logger.addHandler(handler) 54 | ``` 55 | 56 | The `ColoredFormatter` class takes several arguments: 57 | 58 | - `format`: The format string used to output the message (required). 59 | - `datefmt`: An optional date format passed to the base class. See [`logging.Formatter`][Formatter]. 60 | - `reset`: Implicitly adds a color reset code to the message output, unless the output already ends with one. Defaults to `True`. 61 | - `log_colors`: A mapping of record level names to color names. The defaults can be found in `colorlog.default_log_colors`, or the below example. 62 | - `secondary_log_colors`: A mapping of names to `log_colors` style mappings, defining additional colors that can be used in format strings. See below for an example. 63 | - `style`: Available on Python 3.2 and above. See [`logging.Formatter`][Formatter]. 64 | 65 | Color escape codes can be selected based on the log records level, by adding 66 | parameters to the format string: 67 | 68 | - `log_color`: Return the color associated with the records level. 69 | - `_log_color`: Return another color based on the records level if the formatter has secondary colors configured (see `secondary_log_colors` below). 70 | 71 | Multiple escape codes can be used at once by joining them with commas when 72 | configuring the color for a log level (but can't be used directly in the format 73 | string). For example, `black,bg_white` would use the escape codes for black 74 | text on a white background. 75 | 76 | The following escape codes are made available for use in the format string: 77 | 78 | - `{color}`, `fg_{color}`, `bg_{color}`: Foreground and background colors. 79 | - `bold`, `bold_{color}`, `fg_bold_{color}`, `bg_bold_{color}`: Bold/bright colors. 80 | - `thin`, `thin_{color}`, `fg_thin_{color}`: Thin colors (terminal dependent). 81 | - `reset`: Clear all formatting (both foreground and background colors). 82 | 83 | The available color names are: 84 | 85 | - `black` 86 | - `red` 87 | - `green` 88 | - `yellow` 89 | - `blue`, 90 | - `purple` 91 | - `cyan` 92 | - `white` 93 | 94 | You can also use "bright" colors. These aren't standard ANSI codes, and 95 | support for these varies wildly across different terminals. 96 | 97 | - `light_black` 98 | - `light_red` 99 | - `light_green` 100 | - `light_yellow` 101 | - `light_blue` 102 | - `light_purple` 103 | - `light_cyan` 104 | - `light_white` 105 | 106 | ## Examples 107 | 108 | ![Example output](docs/example.png) 109 | 110 | The following code creates a `ColoredFormatter` for use in a logging setup, 111 | using the default values for each argument. 112 | 113 | ```python 114 | from colorlog import ColoredFormatter 115 | 116 | formatter = ColoredFormatter( 117 | "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", 118 | datefmt=None, 119 | reset=True, 120 | log_colors={ 121 | 'DEBUG': 'cyan', 122 | 'INFO': 'green', 123 | 'WARNING': 'yellow', 124 | 'ERROR': 'red', 125 | 'CRITICAL': 'red,bg_white', 126 | }, 127 | secondary_log_colors={}, 128 | style='%' 129 | ) 130 | ``` 131 | 132 | ### Using `secondary_log_colors` 133 | 134 | Secondary log colors are a way to have more than one color that is selected 135 | based on the log level. Each key in `secondary_log_colors` adds an attribute 136 | that can be used in format strings (`message` becomes `message_log_color`), and 137 | has a corresponding value that is identical in format to the `log_colors` 138 | argument. 139 | 140 | The following example highlights the level name using the default log colors, 141 | and highlights the message in red for `error` and `critical` level log messages. 142 | 143 | ```python 144 | from colorlog import ColoredFormatter 145 | 146 | formatter = ColoredFormatter( 147 | "%(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s", 148 | secondary_log_colors={ 149 | 'message': { 150 | 'ERROR': 'red', 151 | 'CRITICAL': 'red' 152 | } 153 | } 154 | ) 155 | ``` 156 | 157 | ### With [`dictConfig`][dictConfig] 158 | 159 | ```python 160 | logging.config.dictConfig({ 161 | 'formatters': { 162 | 'colored': { 163 | '()': 'colorlog.ColoredFormatter', 164 | 'format': "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s" 165 | } 166 | } 167 | }) 168 | ``` 169 | 170 | A full example dictionary can be found in `tests/test_colorlog.py`. 171 | 172 | ### With [`fileConfig`][fileConfig] 173 | 174 | ```ini 175 | ... 176 | 177 | [formatters] 178 | keys=color 179 | 180 | [formatter_color] 181 | class=colorlog.ColoredFormatter 182 | format=%(log_color)s%(levelname)-8s%(reset)s %(bg_blue)s[%(name)s]%(reset)s %(message)s from fileConfig 183 | datefmt=%m-%d %H:%M:%S 184 | ``` 185 | 186 | An instance of ColoredFormatter created with those arguments will then be used 187 | by any handlers that are configured to use the `color` formatter. 188 | 189 | A full example configuration can be found in `tests/test_config.ini`. 190 | 191 | ### With custom log levels 192 | 193 | ColoredFormatter will work with custom log levels added with 194 | [`logging.addLevelName`][addLevelName]: 195 | 196 | ```python 197 | import logging, colorlog 198 | TRACE = 5 199 | logging.addLevelName(TRACE, 'TRACE') 200 | formatter = colorlog.ColoredFormatter(log_colors={'TRACE': 'yellow'}) 201 | handler = logging.StreamHandler() 202 | handler.setFormatter(formatter) 203 | logger = logging.getLogger('example') 204 | logger.addHandler(handler) 205 | logger.setLevel('TRACE') 206 | logger.log(TRACE, 'a message using a custom level') 207 | ``` 208 | 209 | ## Tests 210 | 211 | Tests similar to the above examples are found in `tests/test_colorlog.py`. 212 | 213 | ## Status 214 | 215 | colorlog is in maintenance mode. I try and ensure bugfixes are published, 216 | but compatibility with Python 2.6+ and Python 3+ makes this a difficult 217 | codebase to add features to. Any changes that might break backwards 218 | compatibility for existing users will not be considered. 219 | 220 | ## Alternatives 221 | 222 | There are some more modern libraries for improving Python logging you may 223 | find useful. 224 | 225 | - [structlog] 226 | - [jsonlog] 227 | 228 | ## Projects using colorlog 229 | 230 | GitHub provides [a list of projects that depend on colorlog][dependents]. 231 | 232 | Some early adopters included [Errbot], [Pythran], and [zenlog]. 233 | 234 | ## Licence 235 | 236 | Copyright (c) 2012-2021 Sam Clements 237 | 238 | Permission is hereby granted, free of charge, to any person obtaining a copy of 239 | this software and associated documentation files (the "Software"), to deal in 240 | the Software without restriction, including without limitation the rights to 241 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 242 | the Software, and to permit persons to whom the Software is furnished to do so, 243 | subject to the following conditions: 244 | 245 | The above copyright notice and this permission notice shall be included in all 246 | copies or substantial portions of the Software. 247 | 248 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 249 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 250 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 251 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 252 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 253 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 254 | 255 | [dictConfig]: http://docs.python.org/3/library/logging.config.html#logging.config.dictConfig 256 | [fileConfig]: http://docs.python.org/3/library/logging.config.html#logging.config.fileConfig 257 | [addLevelName]: https://docs.python.org/3/library/logging.html#logging.addLevelName 258 | [Formatter]: http://docs.python.org/3/library/logging.html#logging.Formatter 259 | [tox]: http://tox.readthedocs.org/ 260 | [Arch]: https://archlinux.org/packages/extra/any/python-colorlog/ 261 | [BSD ports]: https://www.freshports.org/devel/py-colorlog/ 262 | [colorama]: https://pypi.python.org/pypi/colorama 263 | [Conda]: https://anaconda.org/conda-forge/colorlog 264 | [Debian]: [https://packages.debian.org/buster/python3-colorlog](https://packages.debian.org/buster/python3-colorlog) 265 | [Errbot]: http://errbot.io/ 266 | [Fedora]: https://src.fedoraproject.org/rpms/python-colorlog 267 | [Gentoo]: https://packages.gentoo.org/packages/dev-python/colorlog 268 | [OpenSuse]: http://rpm.pbone.net/index.php3?stat=3&search=python-colorlog&srodzaj=3 269 | [Pythran]: https://github.com/serge-sans-paille/pythran 270 | [Ubuntu]: https://launchpad.net/python-colorlog 271 | [zenlog]: https://github.com/ManufacturaInd/python-zenlog 272 | [structlog]: https://www.structlog.org/en/stable/ 273 | [jsonlog]: https://github.com/borntyping/jsonlog 274 | [dependents]: https://github.com/borntyping/python-colorlog/network/dependents?package_id=UGFja2FnZS01MDk3NDcyMQ%3D%3D 275 | -------------------------------------------------------------------------------- /colorlog/__init__.py: -------------------------------------------------------------------------------- 1 | """A logging formatter for colored output.""" 2 | 3 | import sys 4 | import warnings 5 | 6 | from colorlog.formatter import ( 7 | ColoredFormatter, 8 | LevelFormatter, 9 | TTYColoredFormatter, 10 | default_log_colors, 11 | ) 12 | from colorlog.wrappers import ( 13 | CRITICAL, 14 | DEBUG, 15 | ERROR, 16 | FATAL, 17 | INFO, 18 | NOTSET, 19 | StreamHandler, 20 | WARN, 21 | WARNING, 22 | basicConfig, 23 | critical, 24 | debug, 25 | error, 26 | exception, 27 | getLogger, 28 | info, 29 | log, 30 | root, 31 | warning, 32 | ) 33 | 34 | __all__ = ( 35 | "CRITICAL", 36 | "DEBUG", 37 | "ERROR", 38 | "FATAL", 39 | "INFO", 40 | "NOTSET", 41 | "WARN", 42 | "WARNING", 43 | "ColoredFormatter", 44 | "LevelFormatter", 45 | "StreamHandler", 46 | "TTYColoredFormatter", 47 | "basicConfig", 48 | "critical", 49 | "debug", 50 | "default_log_colors", 51 | "error", 52 | "exception", 53 | "exception", 54 | "getLogger", 55 | "info", 56 | "log", 57 | "root", 58 | "warning", 59 | ) 60 | 61 | if sys.version_info < (3, 6): 62 | warnings.warn( 63 | "Colorlog requires Python 3.6 or above. Pin 'colorlog<5' to your dependencies " 64 | "if you require compatibility with older versions of Python. See " 65 | "https://github.com/borntyping/python-colorlog#status for more information." 66 | ) 67 | -------------------------------------------------------------------------------- /colorlog/escape_codes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Generates a dictionary of ANSI escape codes. 3 | 4 | http://en.wikipedia.org/wiki/ANSI_escape_code 5 | 6 | Uses colorama as an optional dependency to support color on Windows 7 | """ 8 | 9 | import sys 10 | 11 | try: 12 | import colorama 13 | except ImportError: 14 | pass 15 | else: 16 | if sys.platform == "win32": 17 | colorama.init(strip=False) 18 | 19 | __all__ = ("escape_codes", "parse_colors") 20 | 21 | 22 | # Returns escape codes from format codes 23 | def esc(*codes: int) -> str: 24 | return "\033[" + ";".join(str(code) for code in codes) + "m" 25 | 26 | 27 | escape_codes = { 28 | "reset": esc(0), 29 | "bold": esc(1), 30 | "thin": esc(2), 31 | } 32 | 33 | escape_codes_foreground = { 34 | "black": 30, 35 | "red": 31, 36 | "green": 32, 37 | "yellow": 33, 38 | "blue": 34, 39 | "purple": 35, 40 | "cyan": 36, 41 | "white": 37, 42 | "light_black": 90, 43 | "light_red": 91, 44 | "light_green": 92, 45 | "light_yellow": 93, 46 | "light_blue": 94, 47 | "light_purple": 95, 48 | "light_cyan": 96, 49 | "light_white": 97, 50 | } 51 | 52 | escape_codes_background = { 53 | "black": 40, 54 | "red": 41, 55 | "green": 42, 56 | "yellow": 43, 57 | "blue": 44, 58 | "purple": 45, 59 | "cyan": 46, 60 | "white": 47, 61 | "light_black": 100, 62 | "light_red": 101, 63 | "light_green": 102, 64 | "light_yellow": 103, 65 | "light_blue": 104, 66 | "light_purple": 105, 67 | "light_cyan": 106, 68 | "light_white": 107, 69 | # Bold background colors don't exist, 70 | # but we used to provide these names. 71 | "bold_black": 100, 72 | "bold_red": 101, 73 | "bold_green": 102, 74 | "bold_yellow": 103, 75 | "bold_blue": 104, 76 | "bold_purple": 105, 77 | "bold_cyan": 106, 78 | "bold_white": 107, 79 | } 80 | 81 | # Foreground without prefix 82 | for name, code in escape_codes_foreground.items(): 83 | escape_codes["%s" % name] = esc(code) 84 | escape_codes["bold_%s" % name] = esc(1, code) 85 | escape_codes["thin_%s" % name] = esc(2, code) 86 | 87 | # Foreground with fg_ prefix 88 | for name, code in escape_codes_foreground.items(): 89 | escape_codes["fg_%s" % name] = esc(code) 90 | escape_codes["fg_bold_%s" % name] = esc(1, code) 91 | escape_codes["fg_thin_%s" % name] = esc(2, code) 92 | 93 | # Background with bg_ prefix 94 | for name, code in escape_codes_background.items(): 95 | escape_codes["bg_%s" % name] = esc(code) 96 | 97 | # 256 colour support 98 | for code in range(256): 99 | escape_codes["fg_%d" % code] = esc(38, 5, code) 100 | escape_codes["bg_%d" % code] = esc(48, 5, code) 101 | 102 | 103 | def parse_colors(string: str) -> str: 104 | """Return escape codes from a color sequence string.""" 105 | return "".join(escape_codes[n] for n in string.split(",") if n) 106 | -------------------------------------------------------------------------------- /colorlog/formatter.py: -------------------------------------------------------------------------------- 1 | """The ColoredFormatter class.""" 2 | 3 | import logging 4 | import os 5 | import sys 6 | import typing 7 | 8 | import colorlog.escape_codes 9 | 10 | __all__ = ( 11 | "default_log_colors", 12 | "ColoredFormatter", 13 | "LevelFormatter", 14 | "TTYColoredFormatter", 15 | ) 16 | 17 | # Type aliases used in function signatures. 18 | EscapeCodes = typing.Mapping[str, str] 19 | LogColors = typing.Mapping[str, str] 20 | SecondaryLogColors = typing.Mapping[str, LogColors] 21 | if sys.version_info >= (3, 8): 22 | _FormatStyle = typing.Literal["%", "{", "$"] 23 | else: 24 | _FormatStyle = str 25 | 26 | # The default colors to use for the debug levels 27 | default_log_colors = { 28 | "DEBUG": "white", 29 | "INFO": "green", 30 | "WARNING": "yellow", 31 | "ERROR": "red", 32 | "CRITICAL": "bold_red", 33 | } 34 | 35 | # The default format to use for each style 36 | default_formats = { 37 | "%": "%(log_color)s%(levelname)s:%(name)s:%(message)s", 38 | "{": "{log_color}{levelname}:{name}:{message}", 39 | "$": "${log_color}${levelname}:${name}:${message}", 40 | } 41 | 42 | 43 | class ColoredRecord: 44 | """ 45 | Wraps a LogRecord, adding escape codes to the internal dict. 46 | 47 | The internal dict is used when formatting the message (by the PercentStyle, 48 | StrFormatStyle, and StringTemplateStyle classes). 49 | """ 50 | 51 | def __init__(self, record: logging.LogRecord, escapes: EscapeCodes) -> None: 52 | self.__dict__.update(record.__dict__) 53 | self.__dict__.update(escapes) 54 | 55 | 56 | class ColoredFormatter(logging.Formatter): 57 | """ 58 | A formatter that allows colors to be placed in the format string. 59 | 60 | Intended to help in creating more readable logging output. 61 | """ 62 | 63 | def __init__( 64 | self, 65 | fmt: typing.Optional[str] = None, 66 | datefmt: typing.Optional[str] = None, 67 | style: _FormatStyle = "%", 68 | log_colors: typing.Optional[LogColors] = None, 69 | reset: bool = True, 70 | secondary_log_colors: typing.Optional[SecondaryLogColors] = None, 71 | validate: bool = True, 72 | stream: typing.Optional[typing.IO] = None, 73 | no_color: bool = False, 74 | force_color: bool = False, 75 | defaults: typing.Optional[typing.Mapping[str, typing.Any]] = None, 76 | ) -> None: 77 | """ 78 | Set the format and colors the ColoredFormatter will use. 79 | 80 | The ``fmt``, ``datefmt``, ``style``, and ``default`` args are passed on to the 81 | ``logging.Formatter`` constructor. 82 | 83 | The ``secondary_log_colors`` argument can be used to create additional 84 | ``log_color`` attributes. Each key in the dictionary will set 85 | ``{key}_log_color``, using the value to select from a different 86 | ``log_colors`` set. 87 | 88 | :Parameters: 89 | - fmt (str): The format string to use. 90 | - datefmt (str): A format string for the date. 91 | - log_colors (dict): 92 | A mapping of log level names to color names. 93 | - reset (bool): 94 | Implicitly append a color reset to all records unless False. 95 | - style ('%' or '{' or '$'): 96 | The format style to use. 97 | - secondary_log_colors (dict): 98 | Map secondary ``log_color`` attributes. (*New in version 2.6.*) 99 | - validate (bool) 100 | Validate the format string. 101 | - stream (typing.IO) 102 | The stream formatted messages will be printed to. Used to toggle colour 103 | on non-TTY outputs. Optional. 104 | - no_color (bool): 105 | Disable color output. 106 | - force_color (bool): 107 | Enable color output. Takes precedence over `no_color`. 108 | """ 109 | 110 | # Select a default format if `fmt` is not provided. 111 | fmt = default_formats[style] if fmt is None else fmt 112 | 113 | if sys.version_info >= (3, 10): 114 | super().__init__(fmt, datefmt, style, validate, defaults=defaults) 115 | elif sys.version_info >= (3, 8): 116 | super().__init__(fmt, datefmt, style, validate) 117 | else: 118 | super().__init__(fmt, datefmt, style) 119 | 120 | self.log_colors = log_colors if log_colors is not None else default_log_colors 121 | self.secondary_log_colors = ( 122 | secondary_log_colors if secondary_log_colors is not None else {} 123 | ) 124 | self.reset = reset 125 | self.stream = stream 126 | self.no_color = no_color 127 | self.force_color = force_color 128 | 129 | def formatMessage(self, record: logging.LogRecord) -> str: 130 | """Format a message from a record object.""" 131 | escapes = self._escape_code_map(record.levelname) 132 | wrapper = ColoredRecord(record, escapes) 133 | message = super().formatMessage(wrapper) # type: ignore 134 | message = self._append_reset(message, escapes) 135 | return message 136 | 137 | def _escape_code_map(self, item: str) -> EscapeCodes: 138 | """ 139 | Build a map of keys to escape codes for use in message formatting. 140 | 141 | If _blank_escape_codes() returns True, all values will be an empty string. 142 | """ 143 | codes = {**colorlog.escape_codes.escape_codes} 144 | codes.setdefault("log_color", self._get_escape_code(self.log_colors, item)) 145 | for name, colors in self.secondary_log_colors.items(): 146 | codes.setdefault("%s_log_color" % name, self._get_escape_code(colors, item)) 147 | if self._blank_escape_codes(): 148 | codes = {key: "" for key in codes.keys()} 149 | return codes 150 | 151 | def _blank_escape_codes(self): 152 | """Return True if we should be prevented from printing escape codes.""" 153 | if self.force_color or "FORCE_COLOR" in os.environ: 154 | return False 155 | 156 | if self.no_color or "NO_COLOR" in os.environ: 157 | return True 158 | 159 | if self.stream is not None and not self.stream.isatty(): 160 | return True 161 | 162 | return False 163 | 164 | @staticmethod 165 | def _get_escape_code(log_colors: LogColors, item: str) -> str: 166 | """Extract a color sequence from a mapping, and return escape codes.""" 167 | return colorlog.escape_codes.parse_colors(log_colors.get(item, "")) 168 | 169 | def _append_reset(self, message: str, escapes: EscapeCodes) -> str: 170 | """Add a reset code to the end of the message, if it's not already there.""" 171 | reset_escape_code = escapes["reset"] 172 | 173 | if self.reset and not message.endswith(reset_escape_code): 174 | message += reset_escape_code 175 | 176 | return message 177 | 178 | 179 | class LevelFormatter: 180 | """An extension of ColoredFormatter that uses per-level format strings.""" 181 | 182 | def __init__(self, fmt: typing.Mapping[str, str], **kwargs: typing.Any) -> None: 183 | """ 184 | Configure a ColoredFormatter with its own format string for each log level. 185 | 186 | Supports fmt as a dict. All other args are passed on to the 187 | ``colorlog.ColoredFormatter`` constructor. 188 | 189 | :Parameters: 190 | - fmt (dict): 191 | A mapping of log levels (represented as strings, e.g. 'WARNING') to 192 | format strings. (*New in version 2.7.0) 193 | (All other parameters are the same as in colorlog.ColoredFormatter) 194 | 195 | Example: 196 | 197 | formatter = colorlog.LevelFormatter( 198 | fmt={ 199 | "DEBUG": "%(log_color)s%(message)s (%(module)s:%(lineno)d)", 200 | "INFO": "%(log_color)s%(message)s", 201 | "WARNING": "%(log_color)sWRN: %(message)s (%(module)s:%(lineno)d)", 202 | "ERROR": "%(log_color)sERR: %(message)s (%(module)s:%(lineno)d)", 203 | "CRITICAL": "%(log_color)sCRT: %(message)s (%(module)s:%(lineno)d)", 204 | } 205 | ) 206 | """ 207 | self.formatters = { 208 | level: ColoredFormatter(fmt=f, **kwargs) for level, f in fmt.items() 209 | } 210 | 211 | def format(self, record: logging.LogRecord) -> str: 212 | return self.formatters[record.levelname].format(record) 213 | 214 | 215 | # Provided for backwards compatibility. The features provided by this subclass are now 216 | # included directly in the `ColoredFormatter` class. 217 | TTYColoredFormatter = ColoredFormatter 218 | -------------------------------------------------------------------------------- /colorlog/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/borntyping/python-colorlog/dfa10f59186d3d716aec4165ee79e58f2265c0eb/colorlog/py.typed -------------------------------------------------------------------------------- /colorlog/tests/conftest.py: -------------------------------------------------------------------------------- 1 | """Fixtures that can be used in other tests.""" 2 | 3 | import inspect 4 | import logging 5 | import sys 6 | 7 | import pytest 8 | 9 | import colorlog 10 | 11 | 12 | class TestingStreamHandler(logging.StreamHandler): 13 | """Raise errors to be caught by py.test instead of printing to stdout.""" 14 | 15 | def handleError(self, record): 16 | _type, value, _traceback = sys.exc_info() 17 | raise value 18 | 19 | 20 | def assert_log_message(capsys, log_function, message, *args): 21 | """Call a log function and check the message has been output.""" 22 | log_function(message, *args) 23 | out, err = capsys.readouterr() 24 | # Print the output so that py.test shows it when a test fails 25 | print(err, end="", file=sys.stderr) 26 | # Assert the message send to the logger was output 27 | assert message % args in err, "Log message not output to STDERR" 28 | return err 29 | 30 | 31 | @pytest.fixture(autouse=True) 32 | def clean_env(monkeypatch): 33 | monkeypatch.delenv("FORCE_COLOR", raising=False) 34 | monkeypatch.delenv("NO_COLOR", raising=False) 35 | 36 | 37 | @pytest.fixture() 38 | def reset_loggers(): 39 | logging.root.handlers = list() 40 | logging.root.setLevel(logging.DEBUG) 41 | 42 | 43 | @pytest.fixture() 44 | def test_logger(reset_loggers, capsys): 45 | def function(logger, validator=None): 46 | lines = [ 47 | assert_log_message(capsys, logger.debug, "a debug message %s", 1), 48 | assert_log_message(capsys, logger.info, "an info message %s", 2), 49 | assert_log_message(capsys, logger.warning, "a warning message %s", 3), 50 | assert_log_message(capsys, logger.error, "an error message %s", 4), 51 | assert_log_message(capsys, logger.critical, "a critical message %s", 5), 52 | ] 53 | 54 | if validator is not None: 55 | for line in lines: 56 | valid = validator(line.strip()) 57 | assert valid, f"{line.strip()!r} did not validate" 58 | 59 | return lines 60 | 61 | return function 62 | 63 | 64 | @pytest.fixture() 65 | def create_and_test_logger(test_logger): 66 | def function(*args, **kwargs): 67 | validator = kwargs.pop("validator", None) 68 | formatter_cls = kwargs.pop("formatter_class", colorlog.ColoredFormatter) 69 | 70 | formatter = formatter_cls(*args, **kwargs) 71 | 72 | stream = TestingStreamHandler(stream=sys.stderr) 73 | stream.setLevel(logging.DEBUG) 74 | stream.setFormatter(formatter) 75 | 76 | logger = logging.getLogger(inspect.stack()[1][3]) 77 | logger.setLevel(logging.DEBUG) 78 | logger.addHandler(stream) 79 | 80 | return test_logger(logger, validator) 81 | 82 | return function 83 | -------------------------------------------------------------------------------- /colorlog/tests/test_colorlog.py: -------------------------------------------------------------------------------- 1 | """Test the colorlog.colorlog module.""" 2 | 3 | import sys 4 | 5 | import colorlog 6 | 7 | 8 | def test_colored_formatter(create_and_test_logger): 9 | create_and_test_logger() 10 | 11 | 12 | def test_custom_colors(create_and_test_logger): 13 | """Disable all colors and check no escape codes are output.""" 14 | create_and_test_logger( 15 | log_colors={}, reset=False, validator=lambda line: "\x1b[" not in line 16 | ) 17 | 18 | 19 | def test_reset(create_and_test_logger): 20 | create_and_test_logger(reset=True, validator=lambda line: line.endswith("\x1b[0m")) 21 | 22 | 23 | def test_no_reset(create_and_test_logger): 24 | create_and_test_logger( 25 | fmt="%(reset)s%(log_color)s%(levelname)s:%(name)s:%(message)s", 26 | reset=False, 27 | # Check that each line does not end with an escape code 28 | validator=lambda line: not line.endswith("\x1b[0m"), 29 | ) 30 | 31 | 32 | def test_secondary_colors(create_and_test_logger): 33 | expected = ":\x1b[31mtest_secondary_colors:\x1b[34m" 34 | create_and_test_logger( 35 | fmt=( 36 | "%(log_color)s%(levelname)s:" 37 | "%(name_log_color)s%(name)s:" 38 | "%(message_log_color)s%(message)s" 39 | ), 40 | secondary_log_colors={ 41 | "name": { 42 | "DEBUG": "red", 43 | "INFO": "red", 44 | "WARNING": "red", 45 | "ERROR": "red", 46 | "CRITICAL": "red", 47 | }, 48 | "message": { 49 | "DEBUG": "blue", 50 | "INFO": "blue", 51 | "WARNING": "blue", 52 | "ERROR": "blue", 53 | "CRITICAL": "blue", 54 | }, 55 | }, 56 | validator=lambda line: expected in line, 57 | ) 58 | 59 | 60 | def test_some_secondary_colors(create_and_test_logger): 61 | lines = create_and_test_logger( 62 | fmt="%(message_log_color)s%(message)s", 63 | secondary_log_colors={"message": {"ERROR": "red", "CRITICAL": "red"}}, 64 | ) 65 | # Check that only two lines are colored 66 | assert len([line for line in lines if "\x1b[31m" in line]) == 2 67 | 68 | 69 | def test_percent_style(create_and_test_logger): 70 | create_and_test_logger( 71 | fmt="%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s", style="%" 72 | ) 73 | 74 | 75 | def test_braces_style(create_and_test_logger): 76 | create_and_test_logger( 77 | fmt="{log_color}{levelname}{reset}:{name}:{message}", style="{" 78 | ) 79 | 80 | 81 | def test_template_style(create_and_test_logger): 82 | create_and_test_logger( 83 | fmt="${log_color}${levelname}${reset}:${name}:${message}", style="$" 84 | ) 85 | 86 | 87 | class TestLevelFormatter: 88 | def test_level_formatter(self, create_and_test_logger): 89 | create_and_test_logger( 90 | formatter_class=colorlog.LevelFormatter, 91 | fmt={ 92 | "DEBUG": "%(message)s", 93 | "INFO": "%(message)s", 94 | "WARNING": "%(message)s", 95 | "ERROR": "%(message)s", 96 | "CRITICAL": "%(message)s", 97 | }, 98 | ) 99 | 100 | 101 | def test_ttycolorlog(create_and_test_logger, monkeypatch): 102 | monkeypatch.setattr(sys.stderr, "isatty", lambda: True) 103 | create_and_test_logger( 104 | formatter_class=colorlog.TTYColoredFormatter, 105 | validator=lambda line: "\x1b[" in line, 106 | stream=sys.stderr, 107 | ) 108 | 109 | 110 | def test_ttycolorlog_notty(create_and_test_logger, monkeypatch): 111 | monkeypatch.setattr(sys.stderr, "isatty", lambda: False) 112 | create_and_test_logger( 113 | formatter_class=colorlog.TTYColoredFormatter, 114 | validator=lambda line: "\x1b[" not in line, 115 | stream=sys.stderr, 116 | ) 117 | -------------------------------------------------------------------------------- /colorlog/tests/test_config.ini: -------------------------------------------------------------------------------- 1 | [loggers] 2 | keys=root 3 | 4 | [logger_root] 5 | handlers=stream 6 | level=DEBUG 7 | 8 | [formatters] 9 | keys=color 10 | 11 | [formatter_color] 12 | class=colorlog.ColoredFormatter 13 | format=%(log_color)s%(levelname)s:%(name)s:%(message)s:test_config.ini 14 | datefmt=%H:%M:%S 15 | 16 | [handlers] 17 | keys=stream 18 | 19 | [handler_stream] 20 | class=StreamHandler 21 | formatter=color 22 | args=() 23 | -------------------------------------------------------------------------------- /colorlog/tests/test_config.py: -------------------------------------------------------------------------------- 1 | """Test using colorlog with logging.config""" 2 | 3 | import logging 4 | import logging.config 5 | import os.path 6 | 7 | 8 | def path(filename): 9 | """Return an absolute path to a file in the current directory.""" 10 | return os.path.join(os.path.dirname(os.path.realpath(__file__)), filename) 11 | 12 | 13 | def test_build_from_file(test_logger): 14 | logging.config.fileConfig(path("test_config.ini")) 15 | test_logger(logging.getLogger(), lambda line: ":test_config.ini" in line) 16 | 17 | 18 | def test_build_from_dictionary(test_logger): 19 | logging.config.dictConfig( 20 | { 21 | "version": 1, 22 | "formatters": { 23 | "colored": { 24 | "()": "colorlog.ColoredFormatter", 25 | "format": "%(log_color)s%(levelname)s:%(name)s:%(message)s:dict", 26 | } 27 | }, 28 | "handlers": { 29 | "stream": { 30 | "class": "logging.StreamHandler", 31 | "formatter": "colored", 32 | "level": "DEBUG", 33 | }, 34 | }, 35 | "loggers": { 36 | "": { 37 | "handlers": ["stream"], 38 | "level": "DEBUG", 39 | }, 40 | }, 41 | } 42 | ) 43 | test_logger(logging.getLogger(), lambda line: ":dict" in line) 44 | -------------------------------------------------------------------------------- /colorlog/tests/test_escape_codes.py: -------------------------------------------------------------------------------- 1 | """Test the colorlog.escape_codes module.""" 2 | 3 | import pytest 4 | 5 | from colorlog.escape_codes import esc, escape_codes, parse_colors 6 | 7 | 8 | def test_esc(): 9 | assert esc(1, 2, 3) == "\033[1;2;3m" 10 | 11 | 12 | def test_reset(): 13 | assert escape_codes["reset"] == "\033[0m" 14 | 15 | 16 | def test_bold_color(): 17 | assert escape_codes["bold_red"] == "\033[1;31m" 18 | 19 | 20 | def test_fg_color(): 21 | assert escape_codes["fg_bold_yellow"] == "\033[1;33m" 22 | 23 | 24 | def test_bg_color(): 25 | assert escape_codes["bg_bold_blue"] == "\033[104m" 26 | 27 | 28 | def test_rainbow(create_and_test_logger): 29 | """Test *all* escape codes, useful to ensure backwards compatibility.""" 30 | create_and_test_logger( 31 | "%(log_color)s%(levelname)s%(reset)s:%(bold_black)s%(name)s:" 32 | "%(message)s%(reset)s:" 33 | "%(bold_red)sr%(red)sa%(yellow)si%(green)sn%(bold_blue)sb" 34 | "%(blue)so%(purple)sw%(reset)s " 35 | "%(fg_bold_red)sr%(fg_red)sa%(fg_yellow)si%(fg_green)sn" 36 | "%(fg_bold_blue)sb%(fg_blue)so%(fg_purple)sw%(reset)s " 37 | "%(bg_red)sr%(bg_bold_red)sa%(bg_yellow)si%(bg_green)sn" 38 | "%(bg_bold_blue)sb%(bg_blue)so%(bg_purple)sw%(reset)s " 39 | ) 40 | 41 | 42 | def test_parse_colors(): 43 | assert parse_colors("reset") == "\033[0m" 44 | 45 | 46 | def test_parse_multiple_colors(): 47 | assert parse_colors("bold_red,bg_bold_blue") == "\033[1;31m\033[104m" 48 | 49 | 50 | def test_parse_invalid_colors(): 51 | with pytest.raises(KeyError): 52 | parse_colors("false") 53 | 54 | 55 | def test_256_colors(): 56 | for i in range(256): 57 | assert parse_colors("fg_%d" % i) == "\033[38;5;%dm" % i 58 | assert parse_colors("bg_%d" % i) == "\033[48;5;%dm" % i 59 | -------------------------------------------------------------------------------- /colorlog/tests/test_example.py: -------------------------------------------------------------------------------- 1 | def test_example(): 2 | """Tests the usage example from the README""" 3 | import colorlog 4 | 5 | handler = colorlog.StreamHandler() 6 | handler.setFormatter( 7 | colorlog.ColoredFormatter("%(log_color)s%(levelname)s:%(name)s:%(message)s") 8 | ) 9 | logger = colorlog.getLogger("example") 10 | logger.addHandler(handler) 11 | -------------------------------------------------------------------------------- /colorlog/tests/test_exports.py: -------------------------------------------------------------------------------- 1 | """Test that `from colorlog import *` works correctly.""" 2 | 3 | from colorlog import * # noqa 4 | 5 | 6 | def test_exports(): 7 | assert { 8 | "ColoredFormatter", 9 | "default_log_colors", 10 | "basicConfig", 11 | "root", 12 | "getLogger", 13 | "debug", 14 | "info", 15 | "warning", 16 | "error", 17 | "exception", 18 | "critical", 19 | "log", 20 | "exception", 21 | } < set(globals()) 22 | -------------------------------------------------------------------------------- /colorlog/tests/test_wrappers.py: -------------------------------------------------------------------------------- 1 | """Test the colorlog.wrappers module.""" 2 | 3 | import logging 4 | 5 | import colorlog 6 | 7 | 8 | def test_logging_module(test_logger): 9 | test_logger(logging) 10 | 11 | 12 | def test_colorlog_module(test_logger): 13 | test_logger(colorlog) 14 | 15 | 16 | def test_colorlog_basicConfig(test_logger): 17 | colorlog.basicConfig() 18 | test_logger(colorlog.getLogger()) 19 | 20 | 21 | def test_reexports(): 22 | assert colorlog.root is logging.root 23 | assert colorlog.getLogger is logging.getLogger 24 | assert colorlog.StreamHandler is logging.StreamHandler 25 | 26 | assert colorlog.CRITICAL is logging.CRITICAL 27 | assert colorlog.FATAL is logging.FATAL 28 | assert colorlog.ERROR is logging.ERROR 29 | assert colorlog.WARNING is logging.WARNING 30 | assert colorlog.WARN is logging.WARN 31 | assert colorlog.INFO is logging.INFO 32 | assert colorlog.DEBUG is logging.DEBUG 33 | assert colorlog.NOTSET is logging.NOTSET 34 | 35 | 36 | def test_wrappers(): 37 | assert colorlog.debug is not logging.debug 38 | assert colorlog.info is not logging.info 39 | assert colorlog.warning is not logging.warning 40 | assert colorlog.error is not logging.error 41 | assert colorlog.critical is not logging.critical 42 | assert colorlog.log is not logging.log 43 | assert colorlog.exception is not logging.exception 44 | -------------------------------------------------------------------------------- /colorlog/wrappers.py: -------------------------------------------------------------------------------- 1 | """Wrappers around the logging module.""" 2 | 3 | import functools 4 | import logging 5 | import sys 6 | import typing 7 | from logging import ( 8 | CRITICAL, 9 | DEBUG, 10 | ERROR, 11 | FATAL, 12 | INFO, 13 | NOTSET, 14 | StreamHandler, 15 | WARN, 16 | WARNING, 17 | getLogger, 18 | root, 19 | ) 20 | 21 | import colorlog.formatter 22 | 23 | __all__ = ( 24 | "CRITICAL", 25 | "DEBUG", 26 | "ERROR", 27 | "FATAL", 28 | "INFO", 29 | "NOTSET", 30 | "WARN", 31 | "WARNING", 32 | "StreamHandler", 33 | "basicConfig", 34 | "critical", 35 | "debug", 36 | "error", 37 | "exception", 38 | "getLogger", 39 | "info", 40 | "log", 41 | "root", 42 | "warning", 43 | ) 44 | 45 | 46 | def basicConfig( 47 | style: colorlog.formatter._FormatStyle = "%", 48 | log_colors: typing.Optional[colorlog.formatter.LogColors] = None, 49 | reset: bool = True, 50 | secondary_log_colors: typing.Optional[colorlog.formatter.SecondaryLogColors] = None, 51 | format: str = "%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s", 52 | datefmt: typing.Optional[str] = None, 53 | **kwargs 54 | ) -> None: 55 | """Call ``logging.basicConfig`` and override the formatter it creates.""" 56 | logging.basicConfig(**kwargs) 57 | 58 | def _basicConfig(): 59 | handler = logging.root.handlers[0] 60 | handler.setFormatter( 61 | colorlog.formatter.ColoredFormatter( 62 | fmt=format, 63 | datefmt=datefmt, 64 | style=style, 65 | log_colors=log_colors, 66 | reset=reset, 67 | secondary_log_colors=secondary_log_colors, 68 | stream=kwargs.get("stream", None), 69 | ) 70 | ) 71 | 72 | if sys.version_info >= (3, 13): 73 | with logging._lock: # type: ignore 74 | _basicConfig() 75 | else: 76 | logging._acquireLock() # type: ignore 77 | try: 78 | _basicConfig() 79 | finally: 80 | logging._releaseLock() # type: ignore 81 | 82 | 83 | def ensure_configured(func): 84 | """Modify a function to call our basicConfig() first if no handlers exist.""" 85 | 86 | @functools.wraps(func) 87 | def wrapper(*args, **kwargs): 88 | if len(logging.root.handlers) == 0: 89 | basicConfig() 90 | return func(*args, **kwargs) 91 | 92 | return wrapper 93 | 94 | 95 | debug = ensure_configured(logging.debug) 96 | info = ensure_configured(logging.info) 97 | warning = ensure_configured(logging.warning) 98 | error = ensure_configured(logging.error) 99 | critical = ensure_configured(logging.critical) 100 | log = ensure_configured(logging.log) 101 | exception = ensure_configured(logging.exception) 102 | -------------------------------------------------------------------------------- /docs/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to colorlog 2 | 3 | ## New features 4 | 5 | Open a thread in the "[Discussions]" section of the GitHub repository before doing any significant work on a new feature. This library is over a decade old, and my priority in maintaining it is stability rather than features. See the [Status](../README.md#Status]) section of the README file for more information. 6 | 7 | ## Bugfixes 8 | 9 | _Please_ provide a simple way to reproduce any bug you encounter when opening an issue. It's very common for bugs to be reported for this library that are actually caused by the calling code or another library being used alongside it. 10 | 11 | ## Pull requests 12 | 13 | Open pull requests against the `main` branch. 14 | 15 | Make sure your changes pass the test suite, which runs tests against most recent versions of Python 3 and checks the `black` formatter makes no changes. 16 | * You can run tests locally with `tox` if you have suitable versions of Python 3 installed... 17 | * ...or use the GitHub Actions pipeline which will run automatically once you open a pull request. 18 | 19 | [Discussions]: https://github.com/borntyping/python-colorlog/discussions 20 | -------------------------------------------------------------------------------- /docs/colors.py: -------------------------------------------------------------------------------- 1 | """ 2 | Print every color code supported by colorlog in it's own color. 3 | """ 4 | 5 | import colorlog.escape_codes 6 | 7 | if __name__ == "__main__": 8 | for key, value in colorlog.escape_codes.escape_codes.items(): 9 | print(value, key, colorlog.escape_codes.escape_codes["reset"]) 10 | -------------------------------------------------------------------------------- /docs/custom_level.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from colorlog import ColoredFormatter 4 | 5 | logging.addLevelName(5, "TRACE") 6 | 7 | 8 | def main(): 9 | """Create and use a logger.""" 10 | formatter = ColoredFormatter(log_colors={"TRACE": "yellow"}) 11 | 12 | handler = logging.StreamHandler() 13 | handler.setFormatter(formatter) 14 | 15 | logger = logging.getLogger("example") 16 | logger.addHandler(handler) 17 | logger.setLevel("TRACE") 18 | 19 | logger.log(5, "a message using a custom level") 20 | 21 | 22 | if __name__ == "__main__": 23 | main() 24 | -------------------------------------------------------------------------------- /docs/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/borntyping/python-colorlog/dfa10f59186d3d716aec4165ee79e58f2265c0eb/docs/example.png -------------------------------------------------------------------------------- /docs/example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """python-colorlog example.""" 3 | 4 | import logging 5 | from colorlog import ColoredFormatter 6 | 7 | 8 | def setup_logger(): 9 | """Return a logger with a default ColoredFormatter.""" 10 | formatter = ColoredFormatter( 11 | "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", 12 | datefmt=None, 13 | reset=True, 14 | log_colors={ 15 | "DEBUG": "cyan", 16 | "INFO": "green", 17 | "WARNING": "yellow", 18 | "ERROR": "red", 19 | "CRITICAL": "red", 20 | }, 21 | ) 22 | 23 | logger = logging.getLogger("example") 24 | handler = logging.StreamHandler() 25 | handler.setFormatter(formatter) 26 | logger.addHandler(handler) 27 | logger.setLevel(logging.DEBUG) 28 | 29 | return logger 30 | 31 | 32 | def main(): 33 | """Create and use a logger.""" 34 | logger = setup_logger() 35 | 36 | logger.debug("a debug message") 37 | logger.info("an info message") 38 | logger.warning("a warning message") 39 | logger.error("an error message") 40 | logger.critical("a critical message") 41 | 42 | 43 | if __name__ == "__main__": 44 | main() 45 | -------------------------------------------------------------------------------- /docs/yaml_example.py: -------------------------------------------------------------------------------- 1 | """ 2 | Based on an example provided by Ricardo Reis. 3 | https://github.com/ricardo-reis-1970/colorlog-YAML 4 | 5 | This configures the `logging` module from a YAML file, and provides specific 6 | configuration for the loggers named 'application' and 'example'. 7 | """ 8 | 9 | import logging.config 10 | import pathlib 11 | 12 | import yaml 13 | 14 | 15 | def config(): 16 | """ 17 | Configure `logging` from a YAML file. You might adjust this function to 18 | provide the configuration path as an argument. 19 | """ 20 | path = pathlib.Path(__file__).with_suffix(".yaml") 21 | logging.config.dictConfig(yaml.safe_load(path.read_text())) 22 | 23 | 24 | if __name__ == "__main__": 25 | config() 26 | 27 | root = logging.getLogger() 28 | root.debug("Root logs debug example") 29 | root.info("Root logs written to console without colours") 30 | root.warning("Root logs warning") 31 | root.error("Root logs error") 32 | root.critical("Root logs critical") 33 | 34 | unknown = logging.getLogger("unknown") 35 | unknown.debug("Unknown logs debug example") 36 | unknown.info("Unknown logs propagated to root logger") 37 | unknown.warning("Unknown logs warning") 38 | unknown.error("Unknown logs error") 39 | unknown.critical("Unknown logs critical") 40 | 41 | application = logging.getLogger("application") 42 | application.debug("Application logs debug filtered by log level") 43 | application.info("Application logs written to console and file") 44 | application.warning("Application logs not propagated to the root logger") 45 | application.error("Application logs error example") 46 | application.critical("Application logs critical example") 47 | 48 | example = logging.getLogger("example") 49 | example.debug("Example logs debug filtered by log level") 50 | example.info("Example logs configured to write to file") 51 | example.warning("Example logs propagated to the root logger") 52 | example.error("Example logs error example") 53 | example.critical("Example logs critical example") 54 | -------------------------------------------------------------------------------- /docs/yaml_example.yaml: -------------------------------------------------------------------------------- 1 | version: 1 2 | formatters: 3 | logging: 4 | format: '%(asctime)s - %(name)-11s - %(levelname)-8s - %(message)-60s - formatter=logging.Formatter' 5 | colorlog: 6 | (): 'colorlog.ColoredFormatter' 7 | format: '%(log_color)s%(asctime)s - %(name)-11s - %(levelname)-8s - %(message)-60s - formatter=colorlog.ColoredFormatter' 8 | handlers: 9 | console: 10 | class: logging.StreamHandler 11 | level: DEBUG 12 | formatter: logging 13 | stream: ext://sys.stdout 14 | file: 15 | class: logging.FileHandler 16 | level: WARNING 17 | formatter: logging 18 | filename: doc/example_yaml.log 19 | colour: 20 | class: logging.StreamHandler 21 | level: DEBUG 22 | formatter: colorlog 23 | loggers: 24 | '': 25 | level: DEBUG 26 | handlers: [console] 27 | example: 28 | level: INFO 29 | handlers: [file] 30 | propagate: yes 31 | application: 32 | level: INFO 33 | handlers: [colour, file] 34 | propagate: no 35 | -------------------------------------------------------------------------------- /sample.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import colorlog 3 | 4 | fmt = "{log_color}{levelname} {name}: {message}" 5 | colorlog.basicConfig(level=logging.DEBUG, style="{", format=fmt, stream=None) 6 | 7 | log = logging.getLogger() 8 | 9 | log.warning("hello") 10 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude = .tox,.venv 3 | ignore = W503 4 | max-line-length = 88 5 | 6 | [tool:pytest] 7 | addopts = -p no:logging 8 | 9 | [mypy] 10 | files = colorlog,doc 11 | ignore_missing_imports = True 12 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name="colorlog", 5 | version="6.9.0", 6 | description="Add colours to the output of Python's logging module.", 7 | long_description=open("README.md").read(), 8 | long_description_content_type="text/markdown", 9 | author="Sam Clements", 10 | author_email="sam@borntyping.co.uk", 11 | url="https://github.com/borntyping/python-colorlog", 12 | license="MIT License", 13 | packages=["colorlog"], 14 | package_data={"colorlog": ["py.typed"]}, 15 | setup_requires=["setuptools>=38.6.0"], 16 | extras_require={ 17 | ':sys_platform=="win32"': ["colorama"], 18 | "development": ["black", "flake8", "mypy", "pytest", "types-colorama"], 19 | }, 20 | python_requires=">=3.6", 21 | classifiers=[ 22 | "Development Status :: 5 - Production/Stable", 23 | "Environment :: Console", 24 | "Intended Audience :: Developers", 25 | "License :: OSI Approved :: MIT License", 26 | "Operating System :: OS Independent", 27 | "Programming Language :: Python", 28 | "Programming Language :: Python :: 3", 29 | "Programming Language :: Python :: 3.6", 30 | "Programming Language :: Python :: 3.7", 31 | "Programming Language :: Python :: 3.8", 32 | "Programming Language :: Python :: 3.9", 33 | "Programming Language :: Python :: 3.10", 34 | "Programming Language :: Python :: 3.11", 35 | "Programming Language :: Python :: 3.12", 36 | "Programming Language :: Python :: 3.13", 37 | "Topic :: Terminals", 38 | "Topic :: Utilities", 39 | ], 40 | ) 41 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = black,flake8,mypy,py38,py39,py310,py311,py312,py313 3 | 4 | [testenv] 5 | deps = pytest 6 | commands = pytest -v 7 | 8 | [testenv:black] 9 | deps = black 10 | commands = black --check --diff colorlog docs 11 | skip_install = true 12 | 13 | [testenv:flake8] 14 | deps = flake8 15 | commands = flake8 colorlog docs 16 | skip_install = true 17 | 18 | [testenv:mypy] 19 | deps = 20 | mypy 21 | types-PyYAML 22 | commands = mypy colorlog docs 23 | skip_install = true 24 | --------------------------------------------------------------------------------