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.8.0
  hooks:
    - id: lazy-log-formatter
      args: ['--fix']

Options

  • --fix: Automatically fix f-strings used in log calls to lazy log calls.
  • DIR [DIR ...]: One or more directories to search for Python files. If not specified, defaults to the current directory.

Examples

Check all Python files in the current directory and subdirectories:

python -m src.cli

Check all Python files in two directories:

python -m src.cli src/ tests/

Fix issues in all Python files in a directory:

python -m src.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 src\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.8.0.tar.gz (9.8 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.8.0-py3-none-any.whl (11.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: lazy_log_formatter-0.8.0.tar.gz
  • Upload date:
  • Size: 9.8 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.8.0.tar.gz
Algorithm Hash digest
SHA256 9d53aa7623a2a96997b557c5c8553aa623f8a7a59f830edac2ef907f585a3cbc
MD5 6d670dd52d429f7470fa32ee8330c7a8
BLAKE2b-256 274cad7213bc2630dbf7586db3ea77a1e62bedf68e601aa694c6cb87ae83b734

See more details on using hashes here.

Provenance

The following attestation bundles were made for lazy_log_formatter-0.8.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.8.0-py3-none-any.whl.

File metadata

File hashes

Hashes for lazy_log_formatter-0.8.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a634fb8219e7225c120de39ccb5f11910be049957fd05f201e5abc7acb33660a
MD5 292afa23db4959178c133d572db1332f
BLAKE2b-256 8dcfd2e5196e9a96c890adb2d1f64c254c29ffc91f2f856579d6a02256528f7b

See more details on using hashes here.

Provenance

The following attestation bundles were made for lazy_log_formatter-0.8.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