colorlog


Namecolorlog JSON
Version 6.9.0 PyPI version JSON
download
home_pagehttps://github.com/borntyping/python-colorlog
SummaryAdd colours to the output of Python's logging module.
upload_time2024-10-29 18:34:51
maintainerNone
docs_urlNone
authorSam Clements
requires_python>=3.6
licenseMIT License
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Log formatting with colors!

[![](https://img.shields.io/pypi/v/colorlog.svg)](https://pypi.org/project/colorlog/)
[![](https://img.shields.io/pypi/l/colorlog.svg)](https://pypi.org/project/colorlog/)

Add colours to the output of Python's `logging` module.

* [Source on GitHub](https://github.com/borntyping/python-colorlog)
* [Packages on PyPI](https://pypi.org/pypi/colorlog/)

## Status

colorlog currently requires Python 3.6 or higher. Older versions (below 5.x.x) 
support Python 2.6 and above.

* colorlog 6.x requires Python 3.6 or higher.
* colorlog 5.x is an interim version that will warn Python 2 users to downgrade.
* colorlog 4.x is the final version supporting Python 2.

[colorama] is included as a required dependency and initialised when using 
colorlog on Windows.

This library is over a decade old and supported a wide set of Python versions
for most of its life, which has made it a difficult library to add new features
to. colorlog 6 may break backwards compatibility so that newer features
can be added more easily, but may still not accept all changes or feature
requests. colorlog 4 might accept essential bugfixes but should not be
considered actively maintained and will not accept any major changes or new
features.

## Installation

Install from PyPI with:

```bash
pip install colorlog
```

Several Linux distributions provide official packages ([Debian], [Arch], [Fedora], 
[Gentoo], [OpenSuse] and [Ubuntu]), and others have user provided packages
([BSD ports], [Conda]).

## Usage

```python
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)
```

The `ColoredFormatter` class takes several arguments:

- `format`: The format string used to output the message (required).
- `datefmt`: An optional date format passed to the base class. See [`logging.Formatter`][Formatter].
- `reset`: Implicitly adds a color reset code to the message output, unless the output already ends with one. Defaults to `True`.
- `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.
- `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.
- `style`: Available on Python 3.2 and above. See [`logging.Formatter`][Formatter].

Color escape codes can be selected based on the log records level, by adding
parameters to the format string:

- `log_color`: Return the color associated with the records level.
- `<name>_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`
- `white`

You can also use "bright" colors. These aren't standard ANSI codes, and
support for these varies wildly across different terminals.

- `light_black`
- `light_red`
- `light_green`
- `light_yellow`
- `light_blue`
- `light_purple`
- `light_cyan`
- `light_white`

## Examples

![Example output](docs/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 <sam@borntyping.co.uk>

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]: https://archlinux.org/packages/extra/any/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](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

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/borntyping/python-colorlog",
    "name": "colorlog",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": null,
    "keywords": null,
    "author": "Sam Clements",
    "author_email": "sam@borntyping.co.uk",
    "download_url": "https://files.pythonhosted.org/packages/d3/7a/359f4d5df2353f26172b3cc39ea32daa39af8de522205f512f458923e677/colorlog-6.9.0.tar.gz",
    "platform": null,
    "description": "# Log formatting with colors!\n\n[![](https://img.shields.io/pypi/v/colorlog.svg)](https://pypi.org/project/colorlog/)\n[![](https://img.shields.io/pypi/l/colorlog.svg)](https://pypi.org/project/colorlog/)\n\nAdd colours to the output of Python's `logging` module.\n\n* [Source on GitHub](https://github.com/borntyping/python-colorlog)\n* [Packages on PyPI](https://pypi.org/pypi/colorlog/)\n\n## Status\n\ncolorlog currently requires Python 3.6 or higher. Older versions (below 5.x.x) \nsupport Python 2.6 and above.\n\n* colorlog 6.x requires Python 3.6 or higher.\n* colorlog 5.x is an interim version that will warn Python 2 users to downgrade.\n* colorlog 4.x is the final version supporting Python 2.\n\n[colorama] is included as a required dependency and initialised when using \ncolorlog on Windows.\n\nThis library is over a decade old and supported a wide set of Python versions\nfor most of its life, which has made it a difficult library to add new features\nto. colorlog 6 may break backwards compatibility so that newer features\ncan be added more easily, but may still not accept all changes or feature\nrequests. colorlog 4 might accept essential bugfixes but should not be\nconsidered actively maintained and will not accept any major changes or new\nfeatures.\n\n## Installation\n\nInstall from PyPI with:\n\n```bash\npip install colorlog\n```\n\nSeveral Linux distributions provide official packages ([Debian], [Arch], [Fedora], \n[Gentoo], [OpenSuse] and [Ubuntu]), and others have user provided packages\n([BSD ports], [Conda]).\n\n## Usage\n\n```python\nimport colorlog\n\nhandler = colorlog.StreamHandler()\nhandler.setFormatter(colorlog.ColoredFormatter(\n\t'%(log_color)s%(levelname)s:%(name)s:%(message)s'))\n\nlogger = colorlog.getLogger('example')\nlogger.addHandler(handler)\n```\n\nThe `ColoredFormatter` class takes several arguments:\n\n- `format`: The format string used to output the message (required).\n- `datefmt`: An optional date format passed to the base class. See [`logging.Formatter`][Formatter].\n- `reset`: Implicitly adds a color reset code to the message output, unless the output already ends with one. Defaults to `True`.\n- `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.\n- `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.\n- `style`: Available on Python 3.2 and above. See [`logging.Formatter`][Formatter].\n\nColor escape codes can be selected based on the log records level, by adding\nparameters to the format string:\n\n- `log_color`: Return the color associated with the records level.\n- `<name>_log_color`: Return another color based on the records level if the formatter has secondary colors configured (see `secondary_log_colors` below).\n\nMultiple escape codes can be used at once by joining them with commas when\nconfiguring the color for a log level (but can't be used directly in the format\nstring). For example, `black,bg_white` would use the escape codes for black\ntext on a white background.\n\nThe following escape codes are made available for use in the format string:\n\n- `{color}`, `fg_{color}`, `bg_{color}`: Foreground and background colors.\n- `bold`, `bold_{color}`, `fg_bold_{color}`, `bg_bold_{color}`: Bold/bright colors.\n- `thin`, `thin_{color}`, `fg_thin_{color}`: Thin colors (terminal dependent).\n- `reset`: Clear all formatting (both foreground and background colors).\n\nThe available color names are:\n\n- `black`\n- `red`\n- `green`\n- `yellow`\n- `blue`,\n- `purple`\n- `cyan`\n- `white`\n\nYou can also use \"bright\" colors. These aren't standard ANSI codes, and\nsupport for these varies wildly across different terminals.\n\n- `light_black`\n- `light_red`\n- `light_green`\n- `light_yellow`\n- `light_blue`\n- `light_purple`\n- `light_cyan`\n- `light_white`\n\n## Examples\n\n![Example output](docs/example.png)\n\nThe following code creates a `ColoredFormatter` for use in a logging setup,\nusing the default values for each argument.\n\n```python\nfrom colorlog import ColoredFormatter\n\nformatter = ColoredFormatter(\n\t\"%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s\",\n\tdatefmt=None,\n\treset=True,\n\tlog_colors={\n\t\t'DEBUG':    'cyan',\n\t\t'INFO':     'green',\n\t\t'WARNING':  'yellow',\n\t\t'ERROR':    'red',\n\t\t'CRITICAL': 'red,bg_white',\n\t},\n\tsecondary_log_colors={},\n\tstyle='%'\n)\n```\n\n### Using `secondary_log_colors`\n\nSecondary log colors are a way to have more than one color that is selected\nbased on the log level. Each key in `secondary_log_colors` adds an attribute\nthat can be used in format strings (`message` becomes `message_log_color`), and\nhas a corresponding value that is identical in format to the `log_colors`\nargument.\n\nThe following example highlights the level name using the default log colors,\nand highlights the message in red for `error` and `critical` level log messages.\n\n```python\nfrom colorlog import ColoredFormatter\n\nformatter = ColoredFormatter(\n\t\"%(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s\",\n\tsecondary_log_colors={\n\t\t'message': {\n\t\t\t'ERROR':    'red',\n\t\t\t'CRITICAL': 'red'\n\t\t}\n\t}\n)\n```\n\n### With [`dictConfig`][dictConfig]\n\n```python\nlogging.config.dictConfig({\n\t'formatters': {\n\t\t'colored': {\n\t\t\t'()': 'colorlog.ColoredFormatter',\n\t\t\t'format': \"%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s\"\n\t\t}\n\t}\n})\n```\n\nA full example dictionary can be found in `tests/test_colorlog.py`.\n\n### With [`fileConfig`][fileConfig]\n\n```ini\n...\n\n[formatters]\nkeys=color\n\n[formatter_color]\nclass=colorlog.ColoredFormatter\nformat=%(log_color)s%(levelname)-8s%(reset)s %(bg_blue)s[%(name)s]%(reset)s %(message)s from fileConfig\ndatefmt=%m-%d %H:%M:%S\n```\n\nAn instance of ColoredFormatter created with those arguments will then be used\nby any handlers that are configured to use the `color` formatter.\n\nA full example configuration can be found in `tests/test_config.ini`.\n\n### With custom log levels\n\nColoredFormatter will work with custom log levels added with\n[`logging.addLevelName`][addLevelName]:\n\n```python\nimport logging, colorlog\nTRACE = 5\nlogging.addLevelName(TRACE, 'TRACE')\nformatter = colorlog.ColoredFormatter(log_colors={'TRACE': 'yellow'})\nhandler = logging.StreamHandler()\nhandler.setFormatter(formatter)\nlogger = logging.getLogger('example')\nlogger.addHandler(handler)\nlogger.setLevel('TRACE')\nlogger.log(TRACE, 'a message using a custom level')\n```\n\n## Tests\n\nTests similar to the above examples are found in `tests/test_colorlog.py`.\n\n## Status\n\ncolorlog is in maintenance mode. I try and ensure bugfixes are published,\nbut compatibility with Python 2.6+ and Python 3+ makes this a difficult\ncodebase to add features to. Any changes that might break backwards\ncompatibility for existing users will not be considered.\n\n## Alternatives\n\nThere are some more modern libraries for improving Python logging you may\nfind useful.\n\n- [structlog]\n- [jsonlog]\n\n## Projects using colorlog\n\nGitHub provides [a list of projects that depend on colorlog][dependents].\n\nSome early adopters included [Errbot], [Pythran], and [zenlog].\n\n## Licence\n\nCopyright (c) 2012-2021 Sam Clements <sam@borntyping.co.uk>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n[dictConfig]: http://docs.python.org/3/library/logging.config.html#logging.config.dictConfig\n[fileConfig]: http://docs.python.org/3/library/logging.config.html#logging.config.fileConfig\n[addLevelName]: https://docs.python.org/3/library/logging.html#logging.addLevelName\n[Formatter]: http://docs.python.org/3/library/logging.html#logging.Formatter\n[tox]: http://tox.readthedocs.org/\n[Arch]: https://archlinux.org/packages/extra/any/python-colorlog/\n[BSD ports]: https://www.freshports.org/devel/py-colorlog/\n[colorama]: https://pypi.python.org/pypi/colorama\n[Conda]: https://anaconda.org/conda-forge/colorlog\n[Debian]: [https://packages.debian.org/buster/python3-colorlog](https://packages.debian.org/buster/python3-colorlog)\n[Errbot]: http://errbot.io/\n[Fedora]: https://src.fedoraproject.org/rpms/python-colorlog\n[Gentoo]: https://packages.gentoo.org/packages/dev-python/colorlog\n[OpenSuse]: http://rpm.pbone.net/index.php3?stat=3&search=python-colorlog&srodzaj=3\n[Pythran]: https://github.com/serge-sans-paille/pythran\n[Ubuntu]: https://launchpad.net/python-colorlog\n[zenlog]: https://github.com/ManufacturaInd/python-zenlog\n[structlog]: https://www.structlog.org/en/stable/\n[jsonlog]: https://github.com/borntyping/jsonlog\n[dependents]: https://github.com/borntyping/python-colorlog/network/dependents?package_id=UGFja2FnZS01MDk3NDcyMQ%3D%3D\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "Add colours to the output of Python's logging module.",
    "version": "6.9.0",
    "project_urls": {
        "Homepage": "https://github.com/borntyping/python-colorlog"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e3519b208e85196941db2f0654ad0357ca6388ab3ed67efdbfc799f35d1f83aa",
                "md5": "b928abf582a09ef49e996ac1b8928cab",
                "sha256": "5906e71acd67cb07a71e779c47c4bcb45fb8c2993eebe9e5adcd6a6f1b283eff"
            },
            "downloads": -1,
            "filename": "colorlog-6.9.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "b928abf582a09ef49e996ac1b8928cab",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 11424,
            "upload_time": "2024-10-29T18:34:49",
            "upload_time_iso_8601": "2024-10-29T18:34:49.815623Z",
            "url": "https://files.pythonhosted.org/packages/e3/51/9b208e85196941db2f0654ad0357ca6388ab3ed67efdbfc799f35d1f83aa/colorlog-6.9.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d37a359f4d5df2353f26172b3cc39ea32daa39af8de522205f512f458923e677",
                "md5": "eded3e4cf270c1d1fabc170826f4d735",
                "sha256": "bfba54a1b93b94f54e1f4fe48395725a3d92fd2a4af702f6bd70946bdc0c6ac2"
            },
            "downloads": -1,
            "filename": "colorlog-6.9.0.tar.gz",
            "has_sig": false,
            "md5_digest": "eded3e4cf270c1d1fabc170826f4d735",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 16624,
            "upload_time": "2024-10-29T18:34:51",
            "upload_time_iso_8601": "2024-10-29T18:34:51.011596Z",
            "url": "https://files.pythonhosted.org/packages/d3/7a/359f4d5df2353f26172b3cc39ea32daa39af8de522205f512f458923e677/colorlog-6.9.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-29 18:34:51",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "borntyping",
    "github_project": "python-colorlog",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "colorlog"
}
        
Elapsed time: 0.34520s