Logging integration for Click
click-log provides a simple and beautiful logging integration for Click applications, offering sensible defaults such as colorized output and an easy-to-use verbosity option. It simplifies the setup of Python's standard `logging` module within a Click CLI. The current version is 0.4.0, with an irregular release cadence, last updated in March 2022.
Warnings
- gotcha The `simple_verbosity_option()` decorator should be applied as early as possible in the decorator stack (i.e., immediately below `@click.command()` or `@click.group()`). Defining it too late might result in logging not being configured early enough for other eager Click options or parameters.
- gotcha Failing to call `click_log.basic_config(logger)` or manually attach a `logging.Handler` to your logger instance will prevent log messages from being displayed, even if `logger.info()` or `logger.error()` are called. `click-log`'s main purpose is to simplify this setup.
- gotcha Be careful not to confuse `click-log` (the correct package without a hyphen) with `click-logging` (an older, potentially unrelated project with a hyphen in the name on PyPI). Ensure you install and import from `click_log`.
Install
-
pip install click-log
Imports
- basic_config
from click_log import basic_config
- simple_verbosity_option
from click_log import simple_verbosity_option
- ClickHandler
from click_log import ClickHandler
Quickstart
import logging
import click
from click_log import basic_config, simple_verbosity_option
logger = logging.getLogger(__name__)
basic_config(logger)
@click.command()
@simple_verbosity_option(logger)
def cli():
logger.info("This is an info message.")
logger.warning("This is a warning message.")
try:
1 / 0
except ZeroDivisionError:
logger.error("Caught a division by zero error!")
if __name__ == '__main__':
cli()