lazy-log-formatter


Namelazy-log-formatter JSON
Version 0.8.1 PyPI version JSON
download
home_pageNone
SummaryA pre-commit script to make log lines lazzier
upload_time2025-11-02 21:00:57
maintainerNone
docs_urlNone
authorDaniel Marín
requires_python>=3.10
licenseApache-2.0
keywords code-quality f-strings lazy logging linting logging pre-commit pylint w1203
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ![PyPI - Version](https://img.shields.io/pypi/v/lazy-log-formatter) 
![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/dmar1n/lazy-log-formatter/.github%2Fworkflows%2Frelease.yaml)
![GitHub License](https://img.shields.io/github/license/dmar1n/lazy-log-formatter)
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/lazy-log-formatter)

# Lazy log formatter

Pre-commit hook to automatically detect and convert f-strings in Python code to 
[printf-style](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting) 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`:

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

## Options

- `--fix`: Automatically fix f-strings used in log calls to lazy log calls.
- `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:

```sh
python -m src.cli
```

Check all Python files in two directories:

```sh
python -m src.cli src/ tests/
```

Check specific files:

```sh
python -m src.cli src/cli.py tests/test_cli.py
```

Fix issues in all Python files in a directory:

```sh
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:

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

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

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

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

### Example in a Python class

```python
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
```

```bash
python src\cli.py tests\data
```

The output will be:

```text
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:

```python
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](https://loguru.readthedocs.io/en/stable/overview.html#lazy-evaluation-of-expensive-functions):

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


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "lazy-log-formatter",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "code-quality, f-strings, lazy logging, linting, logging, pre-commit, pylint, W1203",
    "author": "Daniel Mar\u00edn",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/df/55/1ae4a57a23e101dc6ff096e85dc3d9d0ff75919a10a61b5d8e0e30d55633/lazy_log_formatter-0.8.1.tar.gz",
    "platform": null,
    "description": "![PyPI - Version](https://img.shields.io/pypi/v/lazy-log-formatter) \n![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/dmar1n/lazy-log-formatter/.github%2Fworkflows%2Frelease.yaml)\n![GitHub License](https://img.shields.io/github/license/dmar1n/lazy-log-formatter)\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/lazy-log-formatter)\n\n# Lazy log formatter\n\nPre-commit hook to automatically detect and convert f-strings in Python code to \n[printf-style](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting) logging calls,\nfollowing W1203 Pylint rule:\n\nhttps://pylint.readthedocs.io/en/stable/user_guide/messages/warning/logging-fstring-interpolation.html\n\n## Usage\n\nTo use it with pre-commit, add the following lines to your `.pre-commit-config.yaml`:\n\n```yaml\n- repo: https://github.com/dmar1n/lazy-log-formatter\n  rev: 0.8.1\n  hooks:\n    - id: lazy-log-formatter\n      args: ['--fix']\n```\n\n## Options\n\n- `--fix`: Automatically fix f-strings used in log calls to lazy log calls.\n- `PATH [PATH ...]`: One or more directories or files to process. If not specified, defaults to the current directory.\n\n## Examples\n\nCheck all Python files in the current directory and subdirectories:\n\n```sh\npython -m src.cli\n```\n\nCheck all Python files in two directories:\n\n```sh\npython -m src.cli src/ tests/\n```\n\nCheck specific files:\n\n```sh\npython -m src.cli src/cli.py tests/test_cli.py\n```\n\nFix issues in all Python files in a directory:\n\n```sh\npython -m src.cli mydir --fix\n```\n\nIf the `--fix` option is used, the hook will convert f-strings in log calls to lazy log calls, as follows:\n\n```python\n# Before\nlogger.info(f'Hello {name}')\n\n# After\nlogger.info('Hello %s', name)\n```\n\n```python\n# Before\nlogger.info(f'Hello {name} {surname}')\n\n# After\nlogger.info('Hello %s %s', name, surname)\n```\n\n### Example in a Python class\n\n```python\nimport logging\nfrom datetime import datetime\n\n\ndef log_and_return_datetime():\n    now = datetime.now()\n    logging.info(f\"Current datetime: {now}\")\n    return now\n\n\nclass DateTimeLogger:\n    def __init__(self):\n        self._logger = logging.getLogger(self.__class__.__name__)\n\n    def log_datetime(self):\n        now = datetime.now()\n        self._logger.info(f\"Current datetime: {now}\")\n        return now\n```\n\n```bash\npython src\\cli.py tests\\data\n```\n\nThe output will be:\n\n```text\nF-string in logging call at ...\\tests\\data\\test.py:8: f'Current datetime: {now}'\nF-string in logging call at ...\\tests\\data\\test.py:18: f'Current datetime: {now}'\nF-strings found and fixed in '...\\tests\\data\\test.py'.\n```\n\nAfter running the formatter, the code will be transformed to:\n\n```python\nimport logging\nfrom datetime import datetime\n\n\ndef log_and_return_datetime():\n    now = datetime.now()\n    logging.info(\"Current datetime: %s\", now)\n    return now\n\n\nclass DateTimeLogger:\n    def __init__(self):\n        self._logger = logging.getLogger(self.__class__.__name__)\n\n    def log_datetime(self):\n        now = datetime.now()\n        self._logger.info(\"Current datetime: %s\", now)\n        return now\n```\n\n### Important\n\nOnly works with the native Python `logging` module. Other libraries, such as `loguru`, do not support lazy calls.\n\nFor `loguru`, see [Lazy evaluation of expensive functions](https://loguru.readthedocs.io/en/stable/overview.html#lazy-evaluation-of-expensive-functions):\n\n```python\nlogger.opt(lazy=True).debug(\"If sink level <= DEBUG: {x}\", x=lambda: expensive_function(2**64))\n```\n\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "A pre-commit script to make log lines lazzier",
    "version": "0.8.1",
    "project_urls": {
        "Homepage": "https://github.com/dmar1n/lazy-log-formatter",
        "Repository": "https://github.com/dmar1n/lazy-log-formatter"
    },
    "split_keywords": [
        "code-quality",
        " f-strings",
        " lazy logging",
        " linting",
        " logging",
        " pre-commit",
        " pylint",
        " w1203"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "1cfb7388d3b531b2ea045337d0a378fd7117d3b23a666e9f2c0e32620d96c4e2",
                "md5": "e3c85f6bb2d5e61f3a43f1fd969c44d7",
                "sha256": "1b76e53b30be68dadff3c6b4b49b47d0f14a3b4f69621a187b15325ca15dc072"
            },
            "downloads": -1,
            "filename": "lazy_log_formatter-0.8.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e3c85f6bb2d5e61f3a43f1fd969c44d7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 11512,
            "upload_time": "2025-11-02T21:00:56",
            "upload_time_iso_8601": "2025-11-02T21:00:56.088622Z",
            "url": "https://files.pythonhosted.org/packages/1c/fb/7388d3b531b2ea045337d0a378fd7117d3b23a666e9f2c0e32620d96c4e2/lazy_log_formatter-0.8.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "df551ae4a57a23e101dc6ff096e85dc3d9d0ff75919a10a61b5d8e0e30d55633",
                "md5": "4fe885ccc487ab9d63dfef66904ce422",
                "sha256": "37926635a0eec57caab064e8fad9f93c263971a40acab0af708db6452b50412b"
            },
            "downloads": -1,
            "filename": "lazy_log_formatter-0.8.1.tar.gz",
            "has_sig": false,
            "md5_digest": "4fe885ccc487ab9d63dfef66904ce422",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 9906,
            "upload_time": "2025-11-02T21:00:57",
            "upload_time_iso_8601": "2025-11-02T21:00:57.155056Z",
            "url": "https://files.pythonhosted.org/packages/df/55/1ae4a57a23e101dc6ff096e85dc3d9d0ff75919a10a61b5d8e0e30d55633/lazy_log_formatter-0.8.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-11-02 21:00:57",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "dmar1n",
    "github_project": "lazy-log-formatter",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "lazy-log-formatter"
}
        
Elapsed time: 4.47551s