Skip to main content

A pre-commit script to make log lines lazzier

Project description

PyPI - Version GitHub Actions Workflow Status GitHub License PyPI - Python Version

Lazy log formatter

Pre-commit hook to automatically detect and convert f-strings in Python code to printf-style logging calls, following W1203 Pylint rule:

https://pylint.readthedocs.io/en/stable/user_guide/messages/warning/logging-fstring-interpolation.html

Usage

To use it with pre-commit, add the following lines to your .pre-commit-config.yaml:

- repo: https://github.com/dmar1n/lazy-log-formatter
  rev: 0.9.0
  hooks:
    - id: lazy-log-formatter
      args: ['--fix']

Options

  • --fix: Automatically fix f-strings used in log calls to lazy log calls.
  • --exclude [PATTERN ...]: Exclude files or directories matching these patterns.
  • PATH [PATH ...]: One or more directories or files to process. If not specified, defaults to the current directory.

Examples

Check all Python files in the current directory and subdirectories:

python -m lazy_log.cli

Check all Python files in two directories:

python -m lazy_log.cli lazy_log/ tests/

Check specific files:

python -m lazy_log.cli lazy_log/cli.py tests/data/test.py

Exclude specific files or directories:

python -m lazy_log.cli tests/data --exclude "*.pyc" "__pycache__/*" 

Fix issues in all Python files in a directory:

python -m lazy_log.cli mydir --fix

If the --fix option is used, the hook will convert f-strings in log calls to lazy log calls, as follows:

# Before
logger.info(f'Hello {name}')

# After
logger.info('Hello %s', name)
# Before
logger.info(f'Hello {name} {surname}')

# After
logger.info('Hello %s %s', name, surname)

Example in a Python class

import logging
from datetime import datetime


def log_and_return_datetime():
    now = datetime.now()
    logging.info(f"Current datetime: {now}")
    return now


class DateTimeLogger:
    def __init__(self):
        self._logger = logging.getLogger(self.__class__.__name__)

    def log_datetime(self):
        now = datetime.now()
        self._logger.info(f"Current datetime: {now}")
        return now
python lazy_log\cli.py tests\data

The output will be:

F-string in logging call at ...\tests\data\test.py:8: f'Current datetime: {now}'
F-string in logging call at ...\tests\data\test.py:18: f'Current datetime: {now}'
F-strings found and fixed in '...\tests\data\test.py'.

After running the formatter, the code will be transformed to:

import logging
from datetime import datetime


def log_and_return_datetime():
    now = datetime.now()
    logging.info("Current datetime: %s", now)
    return now


class DateTimeLogger:
    def __init__(self):
        self._logger = logging.getLogger(self.__class__.__name__)

    def log_datetime(self):
        now = datetime.now()
        self._logger.info("Current datetime: %s", now)
        return now

Important

Only works with the native Python logging module. Other libraries, such as loguru, do not support lazy calls.

For loguru, see Lazy evaluation of expensive functions:

logger.opt(lazy=True).debug("If sink level <= DEBUG: {x}", x=lambda: expensive_function(2**64))

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

lazy_log_formatter-0.9.0.tar.gz (10.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

lazy_log_formatter-0.9.0-py3-none-any.whl (12.2 kB view details)

Uploaded Python 3

File details

Details for the file lazy_log_formatter-0.9.0.tar.gz.

File metadata

  • Download URL: lazy_log_formatter-0.9.0.tar.gz
  • Upload date:
  • Size: 10.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for lazy_log_formatter-0.9.0.tar.gz
Algorithm Hash digest
SHA256 7cc876331bee5bd878ff991212ce806548be27899f83e7378e08501161f52c20
MD5 bd208b33f01c927e8a2a026c540771ab
BLAKE2b-256 a0b809b80d2ef4138fcd6ba467b1afce258584b2c0f3d26aa17a0f01a8fb2513

See more details on using hashes here.

Provenance

The following attestation bundles were made for lazy_log_formatter-0.9.0.tar.gz:

Publisher: release.yaml on dmar1n/lazy-log-formatter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file lazy_log_formatter-0.9.0-py3-none-any.whl.

File metadata

File hashes

Hashes for lazy_log_formatter-0.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 410d8e42a56d45d85a3bfaee25c936e8baf290c28a9ffe56670d386d9bd37768
MD5 98d44369985fb87f6d24eaf86337b530
BLAKE2b-256 6909d2402c82d0275b4dfff2c5872e304cd038b494ff7464e3bed52f32faa6d9

See more details on using hashes here.

Provenance

The following attestation bundles were made for lazy_log_formatter-0.9.0-py3-none-any.whl:

Publisher: release.yaml on dmar1n/lazy-log-formatter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

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