Skip to main content

Lazy log formatter

PyPI - Version PyPI - Python Version PyPI - Downloads License GitHub Actions Workflow Status pre-commit

A tool that automatically converts f-strings in Python logging calls into lazy logging calls for consistency with Python documentation, improved performance and linting compliance.

See PyPI page for more details. See Changelog for release notes.

Example:

# Before (f-string in log call; not recommended)
logger.info(f"On {datetime.now()} temperature in {city} is {temp:.2f}°C.")

# After lazy-log-formatter
logger.info("On %s temperature in %s is %.2f°C.", datetime.now(), city, temp)

# Prints: On 2024-06-01 12:00:00 temperature in Madrid is 21.50°C.

Why this tool?

In Python, the recommended way to log variable data is to use format-string placeholders and pass values separately:

import logging

logging.warning("%s before you %s", "Look", "leap!")

This approach:

References

Features

  • Scans Python files for f-strings used in logging calls.
  • Provides an option to automatically convert f-strings in logging calls to lazy logging calls.
  • Can be integrated as a pre-commit hook to enforce logging best practices in codebases.

Installation

Install from PyPI:

pip install lazy-log-formatter

Usage

You can either run the tool as a Python module, use it as a pre-commit hook, run the entry point script:

lazy-log-formatter [OPTIONS] [PATH...]

or

python -m lazy_log.cli [OPTIONS] [PATH...]

Pre-commit integration

Add the following to your .pre-commit-config.yaml:

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

Command-line options

You can run the tool from the command line using the following options:

Option Description
--fix Converts f-strings in log calls to lazy logging syntax
--exclude [PATTERN...] Excludes files/directories matching one or more patterns
PATH [PATH...] One or more paths to scan (defaults to current directory)

Examples

Check all Python files in the current directory and subdirectories:

lazy-log-formatter .

Fix all Python files in the current directory and subdirectories:

lazy-log-formatter . --fix

Check all Python files in two directories:

lazy-log-formatter lazy_log/ tests/

Check specific files:

lazy-log-formatter lazy_log/cli.py tests/data/test.py

Exclude specific files or directories:

lazy-log-formatter tests/data --exclude "*.pyc" "__pycache__/*"

Fix issues in all Python files in a directory:

lazy-log-formatter mydir --fix

Example transformations

Simple f-string

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

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

Multiple variables

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

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

Class-based logging example

import logging
from datetime import datetime

logger = logging.getLogger(__name__)


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


class DateTimeLogger:
    def log_datetime(self):
        now = datetime.now()
        logger.info(f"Current datetime: {now}")
        return now

After running the formatter without --fix, the output will be:

F-strings found in '...\tests\data\test.py':
 - 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}'

After running the formatter with --fix, the output will be:

F-strings found and fixed in '...\tests\data\test.py'.

The transformed code will be:

import logging
from datetime import datetime

logger = logging.getLogger(__name__)


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


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

Notes

Minimal, formatting-preserving changes

The tool rewrites code with LibCST. Only the logging calls being converted are modified; the rest of the file (quoting, spacing, blank lines and line endings) is left as it was. Generated format strings use double quotes.

Detection of log calls

The tool includes logic to detect logging calls based on the assumption that your logger instances follow common naming conventions (e.g., logger.info(...), log.info(...)). If a logger variable does not contain the substring "log" in its name, the tool will ignore it.

Other logging libraries

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)
)

Metadata

Release files for lazy-log-formatter 0.12.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 lazy-log-formatter 0.12.1
File Size Uploaded Provenance Actions
lazy_log_formatter-0.12.1.tar.gz 11.0 kB With provenance Details for lazy_log_formatter-0.12.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for lazy-log-formatter 0.12.1
File Interpreter ABI Platform Actions
lazy_log_formatter-0.12.1-py3-none-any.whl Python 3 none any Details for lazy_log_formatter-0.12.1-py3-none-any.whl

Total release size: 24.6 kB

Release files / lazy_log_formatter-0.12.1.tar.gz

Download URL lazy_log_formatter-0.12.1.tar.gz
Size 11.0 kB
Tags Source
SHA-256 checksum
How to use checksums
c06e20571297fb25963b64fd61eec6a352326326380a396f9093e9620d9c5c3f
BLAKE2b-256 checksum
How to use checksums
52355ff63a1f6bb2d490e4cb089c9d1d70e976a0011ddae5abfdd66675f91fd1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 6, 2026.

Transparency log

Release files / lazy_log_formatter-0.12.1-py3-none-any.whl

Download URL lazy_log_formatter-0.12.1-py3-none-any.whl
Size 13.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8d25e875bb6d490f5211f56f96a01b9da49ee754c51ff6b44acc7ee54f0ebd6b
BLAKE2b-256 checksum
How to use checksums
ce395be512a080479932d47c77a207dbefc43e03d7e2411ecdbe03c5f49834c0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 6, 2026.

Transparency log

Security for lazy-log-formatter 0.12.1

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for lazy_log_formatter-0.12.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 6, 2026.

Transparency log

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.

Release history Release notifications | RSS feed

This release

0.12.1 This release

2 release files Full provenance

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