diff --git a/README.md b/README.md index 7f78a02..4be7b7f 100644 --- a/README.md +++ b/README.md @@ -5,20 +5,20 @@ 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/) +- [Source on GitHub](https://github.com/borntyping/python-colorlog) +- [Package on PyPI](https://pypi.org/pypi/colorlog/) ## Status -colorlog currently requires Python 3.6 or higher. Older versions (below 5.x.x) +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. +- 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. +[colorama] is included as a dependency on Windows, where it is automatically +initialised to support colored output. 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 @@ -36,9 +36,9 @@ Install from PyPI with: 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]). +Several Linux distributions provide official packages ([Debian], [Arch], +[Fedora], [Gentoo], [OpenSuse] and [Ubuntu]), and others have user provided +packages ([BSD ports], [Conda]). ## Usage @@ -46,27 +46,46 @@ Several Linux distributions provide official packages ([Debian], [Arch], [Fedora import colorlog handler = colorlog.StreamHandler() -handler.setFormatter(colorlog.ColoredFormatter( - '%(log_color)s%(levelname)s:%(name)s:%(message)s')) +handler.setFormatter(colorlog.ColoredFormatter()) 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]. +### Arguments + +`ColoredFormatter` extends [`logging.Formatter`][formatter] and accepts the +following arguments: + +- `fmt` *(default=`None`)*: A format string used to output the message. If + `None`, a default format string is selected based on `style` (e.g. + `%(log_color)s%(levelname)s:%(name)s:%(message)s` for `%` style). +- `datefmt`, `style`, `validate`, `defaults`: see + [`logging.Formatter`][formatter]. +- `reset` *(default=`True`)*: Implicitly adds a color reset code to the + message output, unless the output already ends with one. +- `log_colors` *(default=`None`)*: A mapping of record level names to color + names. If `None`, `colorlog.default_log_colors` is used. +- `secondary_log_colors` *(default=`None`)*: A mapping of names to `log_colors` + style mappings, defining additional colors that can be used in format strings. + If `None`, an empty mapping is used. +- `stream` *(default=`None`)*: The stream being written to (e.g. `sys.stderr`). + Used to detect whether the output is a TTY. Colors are disabled automatically + on non-TTY streams unless `force_color` is set. +- `no_color` *(default=`False`)*: Disable color output. Can also be set via the + `NO_COLOR` environment variable. +- `force_color` *(default=`False`)*: Force color output even on non-TTY streams. + Takes precedence over `no_color`. Can also be set via the `FORCE_COLOR` + environment variable. + +### Color escape codes 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. -- `_log_color`: Return another color based on the records level if the formatter has secondary colors configured (see `secondary_log_colors` below). +- `_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 @@ -76,7 +95,8 @@ 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. +- `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). @@ -86,7 +106,7 @@ The available color names are: - `red` - `green` - `yellow` -- `blue`, +- `blue` - `purple` - `cyan` - `white` @@ -103,32 +123,33 @@ support for these varies wildly across different terminals. - `light_cyan` - `light_white` +In addition to pre-defined color names, you can use integers from 0 to 255 for +256-color support (e.g. `fg_196`, `bg_42`). + ## 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. +The following snippet creates a `ColoredFormatter` for use in a logging setup, +with a custom format string and log colors: ```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='%' + "DEBUG": "cyan", + "INFO": "green", + "WARNING": "yellow", + "ERROR": "red", + "CRITICAL": "red,bg_white", + } ) ``` +*See `docs/example.py` for full example script.* + ### Using `secondary_log_colors` Secondary log colors are a way to have more than one color that is selected @@ -147,14 +168,14 @@ formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s", secondary_log_colors={ 'message': { - 'ERROR': 'red', + 'ERROR': 'red', 'CRITICAL': 'red' } } ) ``` -### With [`dictConfig`][dictConfig] +### With [`dictConfig`][dictconfig] ```python logging.config.dictConfig({ @@ -169,7 +190,7 @@ logging.config.dictConfig({ A full example dictionary can be found in `tests/test_colorlog.py`. -### With [`fileConfig`][fileConfig] +### With [`fileConfig`][fileconfig] ```ini ... @@ -191,7 +212,7 @@ 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]: +[`logging.addLevelName`][addlevelname]: ```python import logging, colorlog @@ -252,23 +273,22 @@ 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/ +[addlevelname]: https://docs.python.org/3/library/logging.html#logging.addLevelName +[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 +[conda]: https://anaconda.org/conda-forge/colorlog +[debian]: https://packages.debian.org/trixie/python3-colorlog [dependents]: https://github.com/borntyping/python-colorlog/network/dependents?package_id=UGFja2FnZS01MDk3NDcyMQ%3D%3D +[dictconfig]: http://docs.python.org/3/library/logging.config.html#logging.config.dictConfig +[errbot]: http://errbot.io/ +[fedora]: https://src.fedoraproject.org/rpms/python-colorlog +[fileconfig]: http://docs.python.org/3/library/logging.config.html#logging.config.fileConfig +[formatter]: http://docs.python.org/3/library/logging.html#logging.Formatter +[gentoo]: https://packages.gentoo.org/packages/dev-python/colorlog +[jsonlog]: https://github.com/borntyping/jsonlog +[opensuse]: http://rpm.pbone.net/index.php3?stat=3&search=python-colorlog&srodzaj=3 +[pythran]: https://github.com/serge-sans-paille/pythran +[structlog]: https://www.structlog.org/en/stable/ +[ubuntu]: https://launchpad.net/python-colorlog +[zenlog]: https://github.com/ManufacturaInd/python-zenlog diff --git a/docs/example.png b/docs/example.png index aa8465f..0104707 100644 Binary files a/docs/example.png and b/docs/example.png differ diff --git a/docs/example.py b/docs/example.py index 5faf443..20bbb96 100644 --- a/docs/example.py +++ b/docs/example.py @@ -6,17 +6,15 @@ def setup_logger(): - """Return a logger with a default ColoredFormatter.""" + """Return a logger with a ColoredFormatter with custom format and colors.""" 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", + "CRITICAL": "red,bg_white", }, )