Skip to main content

logquacious

https://img.shields.io/pypi/v/logquacious.svg https://travis-ci.com/tonysyu/logquacious.svg?branch=master Documentation Status https://codecov.io/gh/tonysyu/logquacious/branch/master/graph/badge.svg

Logquacious is a set of simple logging utilities to help you over-communicate. (Logorrhea would’ve been a good name, if it didn’t sound so terrible.)

Good application logging is easy to overlook, until you have to debug an error in production. Logquacious aims to make logging as easy as possible. You can find read more at the official ReadTheDocs documentation.

Quick start

To get started, first make sure logquacious is installed:

$ pip install logquacious

You’ll also need to set up logging for your application. For this example, we’ll use a really simple configuration:

import logging

logging.basicConfig(format='%(levelname)s: %(message)s',
                    level=logging.DEBUG)

Note that this simple configuration is used for demonstration purposes, only. See the Logging Cookbook in the official Python docs for examples of options used for real logging configuration.

The main interface to logquacious is the LogManager, which can be used for normal logging:

import logquacious

log = logquacious.LogManager(__name__)
log.debug('Nothing to see here.')

Due to our simplified logging format defined earlier, that would output:

DEBUG: Nothing to see here.

That isn’t a very interesting example. In addition to basic logging, LogManager has a context attribute for use as a context manager:

>>> with log.context.debug('greetings'):
...    print('Hello!')
DEBUG: Enter greetings
Hello!
DEBUG: Exit greetings

The same attribute can be used as a decorator, as well:

@log.context.info
def divide(numerator, denominator):
    if denominator == 0:
        log.warning('Attempted division by zero. Returning None')
        return None
    return numerator / denominator

>>> divide(1, 0)
INFO: Call `divide()`
WARNING: Attempted division by zero. Returning None
INFO: Return from `divide`

Even better, you can log input arguments as well:

@log.context.info(show_args=True, show_kwargs=True)
def greet(name, char='-'):
    msg = 'Hello, {name}'.format(name=name)
    print(msg)
    print(char * len(msg))

>>> greet('Tony', char='~')
INFO: Call `greet('Tony', char='~')`
Hello, Tony
~~~~~~~~~~~
INFO: Return from `greet`

There’s also a special context manager for suppressing errors and logging:

with log.and_suppress(ValueError, msg="It's ok, mistakes happen"):
    raise ValueError('Test error')
[ERROR] It's ok, mistakes happen
Traceback (most recent call last):
  File "/Users/tyu/code/logquacious/logquacious/log_manager.py", line 103, in and_suppress
    yield
  File "scripts/example.py", line 26, in <module>
    raise ValueError('Test error')
ValueError: Test error

Note the traceback above is logged, not streamed to stderr.

Configuration

The message templates used by LogManager.context can be configured to your liking by passing a context_templates argument to LogManager:

log = logquacious.LogManager(__name__, context_templates={
    'context.start': '=============== Enter {label} ===============',
    'context.finish': '=============== Exit {label} ===============',
})

with log.context.debug('greetings'):
    print('Hello!')
[DEBUG] =============== Enter greetings ===============
Hello!
[DEBUG] =============== Exit greetings ===============

The general format for context_templates keys is:

[CONTEXT_TYPE.]('start'|'finish')[.LOG_LEVEL_NAME]

where square-brackets marks optional fields.

CONTEXT_TYPE can be any of the following:

  • function: Template used when called as a decorator.

  • context: Template used when called as a context manager.

LOG_LEVEL_NAME can be any of the following logging levels:

  • DEBUG

  • INFO

  • WARNING

  • ERROR

  • CRITICAL

For example, consider the cascade graph for function.start.DEBUG, which looks like:

     function.start.DEBUG
          /       \
start.DEBUG       function.start
          \       /
            start

The cascade is performed using a breadth-first search. If function.start.DEBUG is not defined, check start.DEBUG then check function.start BEFORE checking start.

The default configuration is:

DEFAULT_TEMPLATES = {
    'start': 'Enter {label}',
    'finish': 'Exit {label}',
    'function.start': 'Call `{label}({arguments})`',
    'function.finish': 'Return from `{label}`',
}

Note that custom configuration updates these defaults. For example, if you want to if you want to skip logging on exit for all context managers and decorators, you’ll have set both 'finish' and 'function.finish' to None or an empty string.

As you can see above, two template variables may be passed to the template string: label and arguments. When called as a context manager, the label is the first argument to the context manager and arguments is always empty. When called as a decorator, label is the function’s __name__ and arguments a string representing input arguments, if show_args or show_kwargs parameters are True.

Credits

This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.

History

0.5.0 (2019-05-05)

  • Backport stacklevel keyword argument from Python 3.8 and configure stacklevel such that logging utilities report the context (e.g. filename and line number) where logquacious utilities are called.

0.4.0 (2018-10-05)

  • Fix config override behavior to extend rather than replace default templates

0.3.0 (2018-10-05)

  • Add decorator support for log.and_suppress and log.and_reraise context managers

  • Suppress logging for null/empty log message templates

0.2.0 (2018-10-03)

Changed default templates. In 0.1.0, the templates were:

DEFAULT_TEMPLATES = {
    'start': 'Start {label}',
    'finish': 'Finish {label}',
}

These defaults have been changed to:

DEFAULT_TEMPLATES = {
    'start': 'Enter {label}',
    'finish': 'Exit {label}',
    'function.start': 'Call `{label}({arguments})`',
    'function.finish': 'Return from `{label}`',
}

0.1.0 (2018-10-03)

  • First release on PyPI.

Metadata

Release files for logquacious 0.5.0

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

Source distribution (sdist)

Source distribution for logquacious 0.5.0
File Size Uploaded Provenance Actions
logquacious-0.5.0.tar.gz 25.9 kB Without provenance Details for logquacious-0.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for logquacious 0.5.0
File Interpreter ABI Platform Actions
logquacious-0.5.0-py2.py3-none-any.whl Python 3, Python 2 none any Details for logquacious-0.5.0-py2.py3-none-any.whl

Total release size: 40.1 kB

Release files / logquacious-0.5.0.tar.gz

Download URL logquacious-0.5.0.tar.gz
Size 25.9 kB
Tags Source
SHA-256 checksum
How to use checksums
97142f4a4709d03bf37db67213f82ed70eb1d8dddb587cb06e60520924c5cce5
BLAKE2b-256 checksum
How to use checksums
5d86e4b8f861fca5ad3a8da13f135dfb97d30d27b3c101563712bee79d54e06f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.12.1 pkginfo/1.4.2 requests/2.19.1 setuptools/39.0.1 requests-toolbelt/0.8.0 tqdm/4.26.0 CPython/3.6.5

Release files / logquacious-0.5.0-py2.py3-none-any.whl

Download URL logquacious-0.5.0-py2.py3-none-any.whl
Size 14.2 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
a31ad48746c1b2b6e1b80556436ca89fc9e86e445577de97219094c3486b12bf
BLAKE2b-256 checksum
How to use checksums
6082f80dd0cee782b1feb63655d82f3d2c2b64fcbd5a2c5b16ff6281ecab13bd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.12.1 pkginfo/1.4.2 requests/2.19.1 setuptools/39.0.1 requests-toolbelt/0.8.0 tqdm/4.26.0 CPython/3.6.5

Security for logquacious 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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