Skip to main content

Click-logging

Simple and beautiful logging for click applications

PyPI PyPI - Python Version PyPI - License Build Status Code coverage semantic-release

Project sources and documentation are available on Github

Documentation

Getting started

Assuming you have this Click application:

import click

@click.command()
def cli():
    click.echo("Dividing by zero.")

    try:
        1 / 0
    except ZeroDivisionError:
        click.echo("ERROR: Failed to divide by zero.")

Ignore the application's core functionality for a moment. The much more pressing question here is: How do we add an option to not print anything on success? We could try this:

import click

@click.command()
@click.option('--quiet', default=False, is_flag=True)
def cli(quiet):
    if not quiet:
        click.echo("Dividing by zero.")

    try:
        1 / 0
    except ZeroDivisionError:
        click.echo("ERROR: Failed to divide by zero.")

Wrapping if-statements around each echo-call is cumbersome though. And with that, we discover logging:

import logging
import click

logger = logging.getLogger(__name__)
# More setup for logging handlers here

@click.command()
@click.option('--quiet', default=False, is_flag=True)
def cli(quiet):
    if quiet:
        logger.setLevel(logging.ERROR)
    else:
        logger.setLevel(logging.INFO)
    # ...

Logging is a better solution, but partly because Python's logging module aims to be so generic, it doesn't come with sensible defaults for CLI applications. At some point you might also want to expose more logging levels through more options, at which point the boilerplate code grows even more.

This is where click-logging comes in:

import logging
import click
import click_logging

logger = logging.getLogger(__name__)
click_logging.basic_config(logger)

@click.command()
@click_logging.simple_verbosity_option(logger)
def cli():
    logger.info("Dividing by zero.")

    try:
        1 / 0
    except ZeroDivisionError:
        logger.error("Failed to divide by zero.")

The output will look like this:

Dividing by zero.
error: Failed to divide by zero.

The error:-prefix will be red, unless the output is piped to another command.

The simple_verbosity_option decorator adds a --verbosity option that takes a (case-insensitive) value of DEBUG, INFO, WARNING, ERROR, or CRITICAL, and calls setLevel on the given logger accordingly.

note

Make sure to define the simple_verbosity_option as early as possible. Otherwise logging setup will not be early enough for some of your other eager options.

Customize output

You can customize click styles for each log level with style_kwargs keyword argument of basic_config function.

import logging
import click_logging

logger = logging.getLogger(__name__)
style_kwargs = {
    'error': dict(fg='red', blink=True),
    'exception': dict(fg='red', blink=True),
    'critical': dict(fg='red', blink=True)
}
click_logging.basic_config(logger, style_kwargs=style_kwargs)

You can customize click echo for each log level using echo_kwargs keyword argument of basic_config function.

import logging
import click_logging

logger = logging.getLogger(__name__)
echo_kwargs = {
    'error': dict(err=True),
    'exception': dict(err=True),
    'critical': dict(err=True),
}
click_logging.basic_config(logger, echo_kwargs=True)

Fork

This is a fork of click-contrib/click-log

Motivations of the fork:

  • semantic-release and github actions to merge and release often.
  • more configuration options.

License

Licensed under the MIT, see LICENSE.

Changelog

v1.0.1 (2021-01-06)

Fix

  • Add missing string interpolation in error message (3de6f06)
  • help: Add trailing dot to help text (1ed426f)

Documentation

  • readme: Enhance README.md formatting (3507ba3)

v1.0.0 (2021-01-06)

Feature

  • customize: Add more customization capabilities in basic_config (621c0a2)

Breaking

  • click_log has been renamed to click_logging (f4a8ddf)

Metadata

Release files for click-logging 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for click-logging 1.0.1
File Size Uploaded
click-logging-1.0.1.tar.gz 7.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for click-logging 1.0.1
File Interpreter ABI Platform
click_logging-1.0.1-py2.py3-none-any.whl Python 2, Python 3 none any Details

Total release size: 14.4 kB

Release files / click-logging-1.0.1.tar.gz

Download URL click-logging-1.0.1.tar.gz
Size 7.8 kB
Tags Source
SHA-256 checksum
How to use checksums
1c3b2835ad4834df7c42e47ac7591866535af499dded3a84403f14411c5041a8
BLAKE2b-256 checksum
How to use checksums
755ef42e093e6723bfe7df0070bbfce023fdf0008e08b4ea3f8756811f4196dd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.6.1 requests/2.25.1 setuptools/49.2.1 requests-toolbelt/0.9.1 tqdm/4.55.1 CPython/3.8.6

Release files / click_logging-1.0.1-py2.py3-none-any.whl

Download URL click_logging-1.0.1-py2.py3-none-any.whl
Size 6.6 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
3ce04f9fa93120343f5d727108f2066b59bd9c5aac2d770a02f37c69186dbf23
BLAKE2b-256 checksum
How to use checksums
f38231f403a7b19b8fed3c71011e8065d2dc670e13b2195133da11606d797736
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.6.1 requests/2.25.1 setuptools/49.2.1 requests-toolbelt/0.9.1 tqdm/4.55.1 CPython/3.8.6

Release history Release notifications | RSS feed

This release

1.0.1 This release

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page