Skip to main content

Utilities for making log output look pretty

Project description

Styled Logging

A collection of logging utilities to prettify logs in Python applications.

Install

pip install styled-logging

Usage

The most basic usage:

from styled_logging import setup
setup()

This will print pretty messages to the console, and does not log to a file.

By default, the console will log at INFO level.

You can also use the context manager (recommended):

from styled_logging import logging_context

with logging_context():
    ...

Recipes

Logging to a file

With quick setup:

from styled_logging import setup
setup(filename="test.log")

Or with more options:

import logging
from styled_logging import (
    logging_context,
    create_file_handler,
    create_console_handler,
)


if __name__ == "__main__":

    with logging_context(
        handlers=[
            create_console_handler(level=logging.DEBUG),
            create_file_handler("test.log"),
        ],
    ):
        try:
            logging.debug("A debug message")
            logging.info("An info message")
            logging.warning("A warning message")
            logging.error("An error message")
            raise ValueError("A critical message from an exception")
        except Exception as exc:
            # adding exc_info=True should not be done in production!
            logging.critical(str(exc), exc_info=True)

This will print the following in the console:

example

And write output in test.log:

WARNING:2022-06-14 17:59:51,794:root:A warning message
ERROR:2022-06-14 17:59:51,794:root:An error message
CRITICAL:2022-06-14 17:59:51,794:root:A critical message from an exception
    Traceback (most recent call last):
        /home/eb/projects/cli-logging/example.py  <module>  20: raise ValueError("A critical message from an exception")
    ValueError: A critical message from an exception

Change the format of a specific level

You can pass a custom formatter to create_console_formatter which contains an overridden format for a specific log level:

import logging
from styled_logging import (
    cli_logging_context,
    create_file_handler,
    create_console_handler,
    MultiFormatter,
    DEFAULT_FORMATS,
    make_formatters,
    style,
    prettify,
)


if __name__ == "__main__":

    my_formats = {
        **DEFAULT_FORMATS,
        logging.INFO: style("INFO ", fg="white") + " | %(message)s",
    }

    my_formatters = make_formatters(my_formats)

    with logging_context(
        handlers=[
            create_console_handler(
                level=logging.DEBUG,
                formatter=prettify(MultiFormatter)(formatters=my_formatters),
            ),
            create_file_handler("test.log"),
        ],
    ):
        try:
            logging.debug("A debug message")
            logging.info("An info message")
            logging.warning("A warning message")
            logging.error("An error message")
            raise ValueError("A critical message from an exception")
        except Exception as exc:
            logging.critical(str(exc), exc_info=True)

example with format

Use a custom file handler for file rotation

Creating your own handler is simple:

import logging
from styled_logging import prettify

formatter = prettify(logging.Formatter, color=False)(
    "%(levelname)s:%(asctime)s:%(name)s:%(message)s"
)
# rotate the file every day
file_handler = logging.handlers.TimedRotatingFileHandler(path, when="D")
file_handler.setFormatter(formatter)
file_handler.setLevel(level)

Then, use the custom handler:

with logging_context(handlers=[file_handler]):
    ...

Configure logging permanently

The logging context is a context manager, so just call its __enter__ method:

logging_context(...).__enter__()

This can be useful for setting up the logging inside a click main function, for example.

Adding pretty exceptions

This package provides a prettify class wrapper to prettify exceptions for a formatter:

from styled_logging import prettify

@prettify(color=True, indent=4)
class MyFormatter(logging.Formatter)
    ...

Or, just wrap the base formatter:

from styled_logging import prettify
import logging

PrettyFormatter = prettify(logging.Formatter, color=True, indent=4)

color controls whether or not the exception text contains color. indent will indent the exception text underneath the log message.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

styled-logging-0.0.4.tar.gz (14.2 kB view details)

Uploaded Source

Built Distribution

styled_logging-0.0.4-py3-none-any.whl (14.7 kB view details)

Uploaded Python 3

File details

Details for the file styled-logging-0.0.4.tar.gz.

File metadata

  • Download URL: styled-logging-0.0.4.tar.gz
  • Upload date:
  • Size: 14.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.10.5

File hashes

Hashes for styled-logging-0.0.4.tar.gz
Algorithm Hash digest
SHA256 524622bda7ad546ecea970011ec87f4f966ea486b82959d9ef94558a52d010e0
MD5 709711d0abb8f178079944091082dc54
BLAKE2b-256 35506b8fd2cc9058ad7f45b7953560afbf979d73e2c56de0623b9f77c196425e

See more details on using hashes here.

File details

Details for the file styled_logging-0.0.4-py3-none-any.whl.

File metadata

File hashes

Hashes for styled_logging-0.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 f38e6a3d6265604683bc2d22785b8e9a7562b7fa036905d7d31aa1ea776347a2
MD5 7766920b90042d638976dd0a1c8f2839
BLAKE2b-256 c81c94feb7f269b784cb75f5f65dff873bc8dc3cea81ae609fffb1aceb80c3f3

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page