├── tests ├── __init__.py └── test_flake8_logging.py ├── src └── flake8_logging │ ├── py.typed │ └── __init__.py ├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── feature-request.yml │ └── issue.yml ├── SECURITY.md ├── CODE_OF_CONDUCT.md ├── dependabot.yml └── workflows │ └── main.yml ├── .gitignore ├── MANIFEST.in ├── .editorconfig ├── .typos.toml ├── tox.ini ├── LICENSE ├── .pre-commit-config.yaml ├── CHANGELOG.rst ├── pyproject.toml ├── README.rst └── uv.lock /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/flake8_logging/py.typed: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | -------------------------------------------------------------------------------- /.github/SECURITY.md: -------------------------------------------------------------------------------- 1 | Please report security issues directly over email to me@adamj.eu 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.egg-info/ 2 | *.pyc 3 | /.coverage 4 | /.coverage.* 5 | /.tox 6 | /build/ 7 | /dist/ 8 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | This project follows [Django's Code of Conduct](https://www.djangoproject.com/conduct/). 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | prune tests 2 | include CHANGELOG.rst 3 | include LICENSE 4 | include pyproject.toml 5 | include README.rst 6 | include src/*/py.typed 7 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: github-actions 4 | directory: "/" 5 | groups: 6 | "GitHub Actions": 7 | patterns: 8 | - "*" 9 | schedule: 10 | interval: monthly 11 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 2 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.py] 14 | indent_size = 4 15 | 16 | [Makefile] 17 | indent_style = tab 18 | -------------------------------------------------------------------------------- /.typos.toml: -------------------------------------------------------------------------------- 1 | # Configuration file for 'typos' tool 2 | # https://github.com/crate-ci/typos 3 | 4 | [default] 5 | extend-ignore-re = [ 6 | # Single line ignore comments 7 | "(?Rm)^.*(#|//)\\s*typos: ignore$", 8 | # Multi-line ignore comments 9 | "(?s)(#|//)\\s*typos: off.*?\\n\\s*(#|//)\\s*typos: on" 10 | ] 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.yml: -------------------------------------------------------------------------------- 1 | name: Feature Request 2 | description: Request an enhancement or new feature. 3 | body: 4 | - type: textarea 5 | id: description 6 | attributes: 7 | label: Description 8 | description: Please describe your feature request with appropriate detail. 9 | validations: 10 | required: true 11 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | requires = 3 | tox>=4.2 4 | env_list = 5 | py{314, 313, 312, 311, 310} 6 | 7 | [testenv] 8 | runner = uv-venv-lock-runner 9 | package = wheel 10 | wheel_build_env = .pkg 11 | set_env = 12 | PYTHONDEVMODE = 1 13 | commands = 14 | python \ 15 | -W error::ResourceWarning \ 16 | -W error::DeprecationWarning \ 17 | -W error::PendingDeprecationWarning \ 18 | -m coverage run \ 19 | -m pytest {posargs:tests} 20 | dependency_groups = 21 | test 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/issue.yml: -------------------------------------------------------------------------------- 1 | name: Issue 2 | description: File an issue 3 | body: 4 | - type: input 5 | id: python_version 6 | attributes: 7 | label: Python Version 8 | description: Which version of Python were you using? 9 | placeholder: 3.14.0 10 | validations: 11 | required: false 12 | - type: input 13 | id: flake8_version 14 | attributes: 15 | label: flake8 Version 16 | description: Which version of flake8 were you using? 17 | placeholder: 3.9.2 18 | validations: 19 | required: false 20 | - type: input 21 | id: package_version 22 | attributes: 23 | label: Package Version 24 | description: Which version of this package were you using? If not the latest version, please check this issue has not since been resolved. 25 | placeholder: 1.0.0 26 | validations: 27 | required: false 28 | - type: textarea 29 | id: description 30 | attributes: 31 | label: Description 32 | description: Please describe your issue. 33 | validations: 34 | required: true 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Adam Johnson 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | ci: 2 | autoupdate_schedule: monthly 3 | 4 | default_language_version: 5 | python: python3.13 6 | 7 | repos: 8 | - repo: https://github.com/pre-commit/pre-commit-hooks 9 | rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # frozen: v6.0.0 10 | hooks: 11 | - id: check-added-large-files 12 | - id: check-case-conflict 13 | - id: check-json 14 | - id: check-merge-conflict 15 | - id: check-symlinks 16 | - id: check-toml 17 | - id: end-of-file-fixer 18 | - id: trailing-whitespace 19 | - repo: https://github.com/crate-ci/typos 20 | rev: 802d5794ff9cf7b15610c47eca99cd1ab757d8d4 # frozen: v1 21 | hooks: 22 | - id: typos 23 | - repo: https://github.com/tox-dev/pyproject-fmt 24 | rev: d252a2a7678b47d1f2eea2f6b846ddfdcd012759 # frozen: v2.11.1 25 | hooks: 26 | - id: pyproject-fmt 27 | - repo: https://github.com/tox-dev/tox-ini-fmt 28 | rev: be26ee0d710a48f7c1acc1291d84082036207bd3 # frozen: 1.7.0 29 | hooks: 30 | - id: tox-ini-fmt 31 | - repo: https://github.com/rstcheck/rstcheck 32 | rev: 27258fde1ee7d3b1e6a7bbc58f4c7b1dd0e719e5 # frozen: v6.2.5 33 | hooks: 34 | - id: rstcheck 35 | additional_dependencies: 36 | - tomli==2.0.1 37 | - repo: https://github.com/adamchainz/blacken-docs 38 | rev: dda8db18cfc68df532abf33b185ecd12d5b7b326 # frozen: 1.20.0 39 | hooks: 40 | - id: blacken-docs 41 | additional_dependencies: 42 | - black==25.1.0 43 | - repo: https://github.com/astral-sh/ruff-pre-commit 44 | rev: 36243b70e5ce219623c3503f5afba0f8c96fda55 # frozen: v0.14.7 45 | hooks: 46 | - id: ruff-check 47 | args: [ --fix ] 48 | - id: ruff-format 49 | - repo: https://github.com/pre-commit/mirrors-mypy 50 | rev: c2738302f5cf2bfb559c1f210950badb133613ea # frozen: v1.19.0 51 | hooks: 52 | - id: mypy 53 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | ========= 2 | Changelog 3 | ========= 4 | 5 | * Drop Python 3.9 support. 6 | 7 | 1.8.0 (2025-09-09) 8 | ------------------ 9 | 10 | * Support Python 3.14. 11 | 12 | 1.7.0 (2024-10-27) 13 | ------------------ 14 | 15 | * Drop Python 3.8 support. 16 | 17 | * Support Python 3.13. 18 | 19 | 1.6.0 (2024-03-20) 20 | ------------------ 21 | 22 | * Add rule LOG015 that detects use of the root logger through calls like ``logging.info()``. 23 | 24 | Thanks to John Litborn in `PR #96 `__. 25 | 26 | 1.5.0 (2024-01-23) 27 | ------------------ 28 | 29 | * Extend LOG003 disallowed ``extra`` keys to include ``message``. 30 | 31 | Thanks to Bartek Ogryczak in `PR #77 `__. 32 | 33 | 1.4.0 (2023-10-10) 34 | ------------------ 35 | 36 | * Add rule LOG013 that detects mismatches between named ``%``-style formatting placeholders and keys in dict argument. 37 | 38 | * Add rule LOG014 that detects ``exc_info=True`` outside of exception handlers. 39 | 40 | 1.3.1 (2023-09-17) 41 | ------------------ 42 | 43 | * Fix LOG012 false positive with unpacked arguments like ``*args``. 44 | 45 | * Fix LOG012 false positive with ``%%`` in formatting strings. 46 | 47 | 1.3.0 (2023-09-17) 48 | ------------------ 49 | 50 | * Add rule LOG012 that detects mismatches between ``%``-style formatting placeholders and arguments. 51 | 52 | 1.2.0 (2023-09-04) 53 | ------------------ 54 | 55 | * Add rule LOG009 that detects use of the undocumented ``WARN`` constant. 56 | 57 | * Add rule LOG010 that detects passing calls to ``exception()`` passing a handled exception as the first argument. 58 | 59 | * Add rule LOG011 that detects pre-formatted log messages. 60 | 61 | 1.1.0 (2023-08-25) 62 | ------------------ 63 | 64 | * LOG001: Avoid detecting inside function definitions when using ``Logger`` directly. 65 | 66 | * Add rule LOG005 that recommends ``exception()`` over ``error()`` within ``except`` clauses. 67 | 68 | * Add rule LOG006 that detects redundant ``exc_info`` arguments in calls to ``exception()``. 69 | 70 | * Add rule LOG007 that detects ``exception()`` calls with falsy ``exc_info`` arguments, which are better written as ``error()``. 71 | 72 | * Add rule LOG008 that detects calls to the deprecated, undocumented ``warn()`` method. 73 | 74 | 1.0.2 (2023-08-24) 75 | ------------------ 76 | 77 | * Change error codes to start with ``LOG`` so they are more specific. 78 | 79 | 1.0.1 (2023-08-24) 80 | ------------------ 81 | 82 | * Correct entry point definition so codes are picked up by default. 83 | 84 | 1.0.0 (2023-08-24) 85 | ------------------ 86 | 87 | * Initial release. 88 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | tags: 8 | - '**' 9 | pull_request: 10 | 11 | concurrency: 12 | group: ${{ github.head_ref || github.run_id }} 13 | cancel-in-progress: true 14 | 15 | jobs: 16 | tests: 17 | name: Python ${{ matrix.python-version }} 18 | runs-on: ubuntu-24.04 19 | 20 | strategy: 21 | matrix: 22 | python-version: 23 | - '3.10' 24 | - '3.11' 25 | - '3.12' 26 | - '3.13' 27 | - '3.14' 28 | 29 | steps: 30 | - uses: actions/checkout@v6 31 | 32 | - uses: actions/setup-python@v6 33 | with: 34 | python-version: ${{ matrix.python-version }} 35 | allow-prereleases: true 36 | 37 | - name: Install uv 38 | uses: astral-sh/setup-uv@v7 39 | with: 40 | enable-cache: true 41 | 42 | - name: Run tox targets for ${{ matrix.python-version }} 43 | run: uvx --with tox-uv tox run -f py$(echo ${{ matrix.python-version }} | tr -d .) 44 | 45 | - name: Upload coverage data 46 | uses: actions/upload-artifact@v5 47 | with: 48 | name: coverage-data-${{ matrix.python-version }} 49 | path: '${{ github.workspace }}/.coverage.*' 50 | include-hidden-files: true 51 | if-no-files-found: error 52 | 53 | coverage: 54 | name: Coverage 55 | runs-on: ubuntu-24.04 56 | needs: tests 57 | steps: 58 | - uses: actions/checkout@v6 59 | 60 | - uses: actions/setup-python@v6 61 | with: 62 | python-version: '3.13' 63 | 64 | - name: Install uv 65 | uses: astral-sh/setup-uv@v7 66 | 67 | - name: Install dependencies 68 | run: uv pip install --system coverage[toml] 69 | 70 | - name: Download data 71 | uses: actions/download-artifact@v6 72 | with: 73 | path: ${{ github.workspace }} 74 | pattern: coverage-data-* 75 | merge-multiple: true 76 | 77 | - name: Combine coverage and fail if it's <100% 78 | run: | 79 | python -m coverage combine 80 | python -m coverage html --skip-covered --skip-empty 81 | python -m coverage report --fail-under=100 82 | echo "## Coverage summary" >> $GITHUB_STEP_SUMMARY 83 | python -m coverage report --format=markdown >> $GITHUB_STEP_SUMMARY 84 | 85 | - name: Upload HTML report 86 | if: ${{ failure() }} 87 | uses: actions/upload-artifact@v5 88 | with: 89 | name: html-report 90 | path: htmlcov 91 | 92 | release: 93 | needs: [coverage] 94 | if: success() && startsWith(github.ref, 'refs/tags/') 95 | runs-on: ubuntu-24.04 96 | environment: release 97 | 98 | permissions: 99 | contents: read 100 | id-token: write 101 | 102 | steps: 103 | - uses: actions/checkout@v6 104 | 105 | - uses: astral-sh/setup-uv@v7 106 | 107 | - name: Build 108 | run: uv build 109 | 110 | - uses: pypa/gh-action-pypi-publish@release/v1 111 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | build-backend = "setuptools.build_meta" 3 | requires = [ 4 | "setuptools>=77", 5 | ] 6 | 7 | [project] 8 | name = "flake8-logging" 9 | version = "1.8.0" 10 | description = "A Flake8 plugin that checks for issues using the standard library logging module." 11 | readme = "README.rst" 12 | keywords = [ 13 | "flake8", 14 | ] 15 | license = "MIT" 16 | license-files = [ "LICENSE" ] 17 | authors = [ 18 | { name = "Adam Johnson", email = "me@adamj.eu" }, 19 | ] 20 | requires-python = ">=3.10" 21 | classifiers = [ 22 | "Development Status :: 5 - Production/Stable", 23 | "Framework :: Flake8", 24 | "Intended Audience :: Developers", 25 | "Natural Language :: English", 26 | "Programming Language :: Python :: 3 :: Only", 27 | "Programming Language :: Python :: 3.10", 28 | "Programming Language :: Python :: 3.11", 29 | "Programming Language :: Python :: 3.12", 30 | "Programming Language :: Python :: 3.13", 31 | "Programming Language :: Python :: 3.14", 32 | "Typing :: Typed", 33 | ] 34 | dependencies = [ 35 | "flake8>=3,!=3.2", 36 | ] 37 | urls = { Changelog = "https://github.com/adamchainz/flake8-logging/blob/main/CHANGELOG.rst", Funding = "https://adamj.eu/books/", Repository = "https://github.com/adamchainz/flake8-logging" } 38 | entry-points."flake8.extension".L = "flake8_logging:Plugin" 39 | 40 | [dependency-groups] 41 | test = [ 42 | "coverage[toml]", 43 | "flake8", 44 | "pytest", 45 | "pytest-flake8-path", 46 | "pytest-randomly", 47 | ] 48 | 49 | [tool.ruff] 50 | lint.select = [ 51 | # flake8-bugbear 52 | "B", 53 | # flake8-comprehensions 54 | "C4", 55 | # pycodestyle 56 | "E", 57 | # Pyflakes errors 58 | "F", 59 | # isort 60 | "I", 61 | # flake8-simplify 62 | "SIM", 63 | # flake8-tidy-imports 64 | "TID", 65 | # pyupgrade 66 | "UP", 67 | # Pyflakes warnings 68 | "W", 69 | ] 70 | lint.ignore = [ 71 | # flake8-bugbear opinionated rules 72 | "B9", 73 | # line-too-long 74 | "E501", 75 | # suppressible-exception 76 | "SIM105", 77 | # if-else-block-instead-of-if-exp 78 | "SIM108", 79 | ] 80 | lint.extend-safe-fixes = [ 81 | # non-pep585-annotation 82 | "UP006", 83 | ] 84 | lint.isort.required-imports = [ "from __future__ import annotations" ] 85 | 86 | [tool.pyproject-fmt] 87 | max_supported_python = "3.14" 88 | 89 | [tool.pytest.ini_options] 90 | addopts = """\ 91 | --strict-config 92 | --strict-markers 93 | """ 94 | xfail_strict = true 95 | 96 | [tool.coverage.run] 97 | branch = true 98 | parallel = true 99 | source = [ 100 | "flake8_logging", 101 | "tests", 102 | ] 103 | 104 | [tool.coverage.paths] 105 | source = [ 106 | "src", 107 | ".tox/**/site-packages", 108 | ] 109 | 110 | [tool.coverage.report] 111 | show_missing = true 112 | 113 | [tool.mypy] 114 | enable_error_code = [ 115 | "ignore-without-code", 116 | "redundant-expr", 117 | "truthy-bool", 118 | ] 119 | mypy_path = "src/" 120 | namespace_packages = false 121 | strict = true 122 | warn_unreachable = true 123 | 124 | [[tool.mypy.overrides]] 125 | module = "tests.*" 126 | allow_untyped_defs = true 127 | 128 | [tool.rstcheck] 129 | report_level = "ERROR" 130 | -------------------------------------------------------------------------------- /src/flake8_logging/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import ast 4 | import re 5 | from collections.abc import Generator, Sequence 6 | from functools import cache 7 | from importlib.metadata import version 8 | from typing import Any, cast 9 | 10 | 11 | class Plugin: 12 | name = "flake8-logging" 13 | version = version("flake8-logging") 14 | 15 | def __init__(self, tree: ast.AST) -> None: 16 | self._tree = tree 17 | 18 | def run(self) -> Generator[tuple[int, int, str, type[Any]]]: 19 | visitor = Visitor() 20 | visitor.visit(self._tree) 21 | 22 | type_ = type(self) 23 | for line, col, msg in visitor.errors: 24 | yield line, col, msg, type_ 25 | 26 | 27 | logger_methods = frozenset( 28 | ( 29 | "debug", 30 | "info", 31 | "warn", 32 | "warning", 33 | "error", 34 | "critical", 35 | "log", 36 | "exception", 37 | ) 38 | ) 39 | logrecord_attributes = frozenset( 40 | ( 41 | "asctime", 42 | "args", 43 | "created", 44 | "exc_info", 45 | "exc_text", 46 | "filename", 47 | "funcName", 48 | "levelname", 49 | "levelno", 50 | "lineno", 51 | "message", 52 | "module", 53 | "msecs", 54 | "msg", 55 | "name", 56 | "pathname", 57 | "process", 58 | "processName", 59 | "relativeCreated", 60 | "stack_info", 61 | "taskName", 62 | "thread", 63 | "threadName", 64 | ) 65 | ) 66 | 67 | 68 | @cache 69 | def modpos_placeholder_re() -> re.Pattern[str]: 70 | # https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting 71 | return re.compile( 72 | r""" 73 | % 74 | (?P 75 | % | # raw % character 76 | (?: 77 | ([-#0 +]+)? # conversion flags 78 | (?P\d+|\*)? # minimum field width 79 | (?P\.\d+|\.\*)? # precision 80 | [hlL]? # length modifier 81 | [acdeEfFgGiorsuxX] # conversion type 82 | ) 83 | ) 84 | """, 85 | re.VERBOSE, 86 | ) 87 | 88 | 89 | @cache 90 | def modnamed_placeholder_re() -> re.Pattern[str]: 91 | # https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting 92 | return re.compile( 93 | r""" 94 | % 95 | \( 96 | (?P.*?) 97 | \) 98 | ([-#0 +]+)? # conversion flags 99 | (\d+)? # minimum field width 100 | (\.\d+)? # precision 101 | [hlL]? # length modifier 102 | [acdeEfFgGiorsuxX] # conversion type 103 | """, 104 | re.VERBOSE, 105 | ) 106 | 107 | 108 | LOG001 = "LOG001 use logging.getLogger() to instantiate loggers" 109 | LOG002 = "LOG002 use __name__ with getLogger()" 110 | LOG002_names = frozenset( 111 | ( 112 | "__cached__", 113 | "__file__", 114 | ) 115 | ) 116 | LOG003 = "LOG003 extra key {} clashes with LogRecord attribute" 117 | LOG004 = "LOG004 avoid exception() outside of exception handlers" 118 | LOG005 = "LOG005 use exception() within an exception handler" 119 | LOG006 = "LOG006 redundant exc_info argument for exception()" 120 | LOG007 = "LOG007 use error() instead of exception() with exc_info=False" 121 | LOG008 = "LOG008 warn() is deprecated, use warning() instead" 122 | LOG009 = "LOG009 WARN is undocumented, use WARNING instead" 123 | LOG010 = "LOG010 exception() does not take an exception" 124 | LOG011 = "LOG011 avoid pre-formatting log messages" 125 | LOG012 = "LOG012 formatting error: {n} {style} placeholder{ns} but {m} argument{ms}" 126 | LOG013 = "LOG013 formatting error: {mistake} key{ns}: {keys}" 127 | LOG014 = "LOG014 avoid exc_info=True outside of exception handlers" 128 | LOG015 = "LOG015 avoid logging calls on the root logger" 129 | 130 | 131 | class Visitor(ast.NodeVisitor): 132 | def __init__(self) -> None: 133 | self.errors: list[tuple[int, int, str]] = [] 134 | self._logging_name: str | None = None 135 | self._logger_name: str | None = None 136 | self._from_imports: dict[str, str] = {} 137 | self._stack: list[ast.AST] = [] 138 | 139 | def visit(self, node: ast.AST) -> None: 140 | self._stack.append(node) 141 | super().visit(node) 142 | self._stack.pop() 143 | 144 | def visit_Import(self, node: ast.Import) -> None: 145 | for alias in node.names: 146 | if alias.name == "logging": 147 | self._logging_name = alias.asname or alias.name 148 | self.generic_visit(node) 149 | 150 | def visit_ImportFrom(self, node: ast.ImportFrom) -> None: 151 | if node.module == "logging": 152 | for alias in node.names: 153 | if alias.name == "WARN": 154 | lineno = alias.lineno 155 | col_offset = alias.col_offset 156 | self.errors.append((lineno, col_offset, LOG009)) 157 | if not alias.asname: 158 | self._from_imports[alias.name] = node.module 159 | self.generic_visit(node) 160 | 161 | def visit_Attribute(self, node: ast.Attribute) -> None: 162 | if ( 163 | self._logging_name 164 | and isinstance(node.value, ast.Name) 165 | and node.value.id == self._logging_name 166 | and node.attr == "WARN" 167 | ): 168 | self.errors.append((node.lineno, node.col_offset, LOG009)) 169 | self.generic_visit(node) 170 | 171 | def visit_Call(self, node: ast.Call) -> None: 172 | if ( 173 | ( 174 | self._logging_name 175 | and isinstance(node.func, ast.Attribute) 176 | and node.func.attr == "Logger" 177 | and isinstance(node.func.value, ast.Name) 178 | and node.func.value.id == self._logging_name 179 | ) 180 | or ( 181 | isinstance(node.func, ast.Name) 182 | and node.func.id == "Logger" 183 | and self._from_imports.get("Logger") == "logging" 184 | ) 185 | ) and not self._at_module_level(): 186 | self.errors.append((node.lineno, node.col_offset, LOG001)) 187 | 188 | # LOG015 189 | if ( 190 | isinstance(node.func, ast.Attribute) 191 | and node.func.attr in logger_methods 192 | and isinstance(node.func.value, ast.Name) 193 | and self._logging_name 194 | and node.func.value.id == self._logging_name 195 | ) or ( 196 | isinstance(node.func, ast.Name) 197 | and node.func.id in logger_methods 198 | and self._from_imports.get(node.func.id) == "logging" 199 | ): 200 | self.errors.append((node.lineno, node.col_offset, LOG015)) 201 | 202 | if ( 203 | self._logging_name 204 | and isinstance(node.func, ast.Attribute) 205 | and node.func.attr == "getLogger" 206 | and isinstance(node.func.value, ast.Name) 207 | and node.func.value.id == self._logging_name 208 | ) or ( 209 | isinstance(node.func, ast.Name) 210 | and node.func.id == "getLogger" 211 | and self._from_imports.get("getLogger") == "logging" 212 | ): 213 | if ( 214 | len(self._stack) >= 2 215 | and isinstance(assign := self._stack[-2], ast.Assign) 216 | and len(assign.targets) == 1 217 | and isinstance(assign.targets[0], ast.Name) 218 | and not self._at_module_level() 219 | ): 220 | self._logger_name = assign.targets[0].id 221 | 222 | if ( 223 | node.args 224 | and isinstance(node.args[0], ast.Name) 225 | and node.args[0].id in LOG002_names 226 | ): 227 | self.errors.append( 228 | (node.args[0].lineno, node.args[0].col_offset, LOG002), 229 | ) 230 | 231 | if ( 232 | isinstance(node.func, ast.Attribute) 233 | and node.func.attr in logger_methods 234 | and isinstance(node.func.value, ast.Name) 235 | ) and ( 236 | (self._logging_name and node.func.value.id == self._logging_name) 237 | or (self._logger_name and node.func.value.id == self._logger_name) 238 | ): 239 | exc_handler = self._current_except_handler() 240 | 241 | # LOG008 242 | if node.func.attr == "warn": 243 | self.errors.append((node.lineno, node.col_offset, LOG008)) 244 | 245 | # LOG003 246 | extra_keys: Sequence[tuple[str, ast.Constant | ast.keyword]] = () 247 | if any((extra_node := kw).arg == "extra" for kw in node.keywords): 248 | if isinstance(extra_node.value, ast.Dict): 249 | extra_keys = [ 250 | (k.value, k) 251 | for k in extra_node.value.keys 252 | if isinstance(k, ast.Constant) and isinstance(k.value, str) 253 | ] 254 | elif ( 255 | isinstance(extra_node.value, ast.Call) 256 | and isinstance(extra_node.value.func, ast.Name) 257 | and extra_node.value.func.id == "dict" 258 | ): 259 | extra_keys = [ 260 | (k.arg, k) 261 | for k in extra_node.value.keywords 262 | if k.arg is not None 263 | ] 264 | 265 | for key, key_node in extra_keys: 266 | if key in logrecord_attributes: 267 | self.errors.append( 268 | ( 269 | key_node.lineno, 270 | key_node.col_offset, 271 | LOG003.format(repr(key)), 272 | ) 273 | ) 274 | 275 | if node.func.attr == "exception": 276 | # LOG004 277 | if not exc_handler: 278 | self.errors.append( 279 | (node.lineno, node.col_offset, LOG004), 280 | ) 281 | 282 | if any((exc_info := kw).arg == "exc_info" for kw in node.keywords): 283 | # LOG006 284 | if ( 285 | isinstance(exc_info.value, ast.Constant) 286 | and exc_info.value.value 287 | ) or ( 288 | exc_handler 289 | and isinstance(exc_info.value, ast.Name) 290 | and exc_info.value.id == exc_handler.name 291 | ): 292 | self.errors.append( 293 | (exc_info.lineno, exc_info.col_offset, LOG006), 294 | ) 295 | 296 | # LOG007 297 | elif ( 298 | isinstance(exc_info.value, ast.Constant) 299 | and not exc_info.value.value 300 | ): 301 | self.errors.append( 302 | (exc_info.lineno, exc_info.col_offset, LOG007), 303 | ) 304 | 305 | # LOG005 306 | elif node.func.attr == "error" and exc_handler is not None: 307 | rewritable = False 308 | if any((exc_info := kw).arg == "exc_info" for kw in node.keywords): 309 | if ( 310 | isinstance(exc_info.value, ast.Constant) 311 | and exc_info.value.value 312 | ) or ( 313 | isinstance(exc_info.value, ast.Name) 314 | and exc_info.value.id == exc_handler.name 315 | ): 316 | rewritable = True 317 | else: 318 | rewritable = True 319 | 320 | if rewritable: 321 | self.errors.append( 322 | (node.lineno, node.col_offset, LOG005), 323 | ) 324 | 325 | elif ( 326 | exc_handler is None 327 | and any((exc_info := kw).arg == "exc_info" for kw in node.keywords) 328 | and isinstance(exc_info.value, ast.Constant) 329 | and exc_info.value.value 330 | ): 331 | self.errors.append( 332 | (exc_info.lineno, exc_info.col_offset, LOG014), 333 | ) 334 | 335 | # LOG010 336 | if ( 337 | node.func.attr == "exception" 338 | and len(node.args) >= 1 339 | and isinstance(node.args[0], ast.Name) 340 | and exc_handler is not None 341 | and node.args[0].id == exc_handler.name 342 | ): 343 | self.errors.append( 344 | (node.args[0].lineno, node.args[0].col_offset, LOG010) 345 | ) 346 | 347 | msg_arg_kwarg = False 348 | if node.func.attr == "log" and len(node.args) >= 2: 349 | msg_arg = node.args[1] 350 | elif node.func.attr != "log" and len(node.args) >= 1: 351 | msg_arg = node.args[0] 352 | else: 353 | try: 354 | msg_arg = [k for k in node.keywords if k.arg == "msg"][0].value 355 | msg_arg_kwarg = True 356 | except IndexError: 357 | msg_arg = None 358 | 359 | # LOG011 360 | if ( 361 | isinstance(msg_arg, ast.JoinedStr) 362 | or ( 363 | isinstance(msg_arg, ast.Call) 364 | and isinstance(msg_arg.func, ast.Attribute) 365 | and isinstance(msg_arg.func.value, ast.Constant) 366 | and isinstance(msg_arg.func.value.value, str) 367 | and msg_arg.func.attr == "format" 368 | ) 369 | or ( 370 | isinstance(msg_arg, ast.BinOp) 371 | and isinstance(msg_arg.op, ast.Mod) 372 | and isinstance(msg_arg.left, ast.Constant) 373 | and isinstance(msg_arg.left.value, str) 374 | ) 375 | or ( 376 | isinstance(msg_arg, ast.BinOp) 377 | and is_add_chain_with_non_str(msg_arg) 378 | ) 379 | ): 380 | self.errors.append((msg_arg.lineno, msg_arg.col_offset, LOG011)) 381 | 382 | # LOG012 383 | if ( 384 | msg_arg is not None 385 | and not msg_arg_kwarg 386 | and (msg := flatten_str_chain(msg_arg)) 387 | and not any(isinstance(arg, ast.Starred) for arg in node.args) 388 | ): 389 | self._check_msg_and_args(node, msg_arg, msg) 390 | 391 | self.generic_visit(node) 392 | 393 | def _at_module_level(self) -> bool: 394 | return any( 395 | isinstance(parent, (ast.FunctionDef, ast.AsyncFunctionDef)) 396 | for parent in self._stack 397 | ) 398 | 399 | def _current_except_handler(self) -> ast.ExceptHandler | None: 400 | for node in reversed(self._stack): 401 | if isinstance(node, ast.ExceptHandler): 402 | return node 403 | elif isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)): 404 | break 405 | return None 406 | 407 | def _check_msg_and_args(self, node: ast.Call, msg_arg: ast.expr, msg: str) -> None: 408 | assert isinstance(node.func, ast.Attribute) 409 | if ( 410 | ( 411 | (node.func.attr != "log" and (dict_idx := 1)) 412 | or (node.func.attr == "log" and (dict_idx := 2)) 413 | ) 414 | and len(node.args) == dict_idx + 1 415 | and isinstance( 416 | (dict_node := node.args[dict_idx]), 417 | ast.Dict, 418 | ) 419 | and all( 420 | isinstance(k, ast.Constant) and isinstance(k.value, str) 421 | for k in dict_node.keys 422 | ) 423 | and ( 424 | modnames := {m["name"] for m in modnamed_placeholder_re().finditer(msg)} 425 | ) 426 | ): 427 | # LOG013 428 | given = {cast(ast.Constant, k).value for k in dict_node.keys} 429 | if missing := modnames - given: 430 | self.errors.append( 431 | ( 432 | msg_arg.lineno, 433 | msg_arg.col_offset, 434 | LOG013.format( 435 | mistake="missing", 436 | ns="s" if len(missing) != 1 else "", 437 | keys=", ".join([repr(k) for k in missing]), 438 | ), 439 | ) 440 | ) 441 | 442 | if missing := given - modnames: 443 | self.errors.append( 444 | ( 445 | dict_node.lineno, 446 | dict_node.col_offset, 447 | LOG013.format( 448 | mistake="unreferenced", 449 | ns="s" if len(missing) != 1 else "", 450 | keys=", ".join([repr(k) for k in missing]), 451 | ), 452 | ) 453 | ) 454 | 455 | return 456 | 457 | modpos_count = sum( 458 | 1 + (m["minwidth"] == "*") + (m["precision"] == ".*") 459 | for m in modpos_placeholder_re().finditer(msg) 460 | if m["spec"] != "%" 461 | ) 462 | arg_count = len(node.args) - 1 - (node.func.attr == "log") 463 | 464 | if modpos_count > 0 and modpos_count != arg_count: 465 | self.errors.append( 466 | ( 467 | msg_arg.lineno, 468 | msg_arg.col_offset, 469 | LOG012.format( 470 | n=modpos_count, 471 | ns="s" if modpos_count != 1 else "", 472 | style="%", 473 | m=arg_count, 474 | ms="s" if arg_count != 1 else "", 475 | ), 476 | ) 477 | ) 478 | return 479 | 480 | 481 | def is_add_chain_with_non_str(node: ast.BinOp) -> bool: 482 | if not isinstance(node.op, ast.Add): 483 | return False 484 | 485 | for side in (node.left, node.right): 486 | if isinstance(side, ast.BinOp): 487 | if is_add_chain_with_non_str(side): 488 | return True 489 | elif not (isinstance(side, ast.Constant) and isinstance(side.value, str)): 490 | return True 491 | 492 | return False 493 | 494 | 495 | def flatten_str_chain(node: ast.AST) -> str | None: 496 | parts = [] 497 | 498 | def visit(node: ast.AST) -> bool: 499 | if isinstance(node, ast.Constant) and isinstance(node.value, str): 500 | parts.append(node.value) 501 | return True 502 | elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): 503 | return visit(node.left) and visit(node.right) 504 | return False 505 | 506 | result = visit(node) 507 | if not result: 508 | return None 509 | if len(parts) == 1: 510 | return parts[0] 511 | else: 512 | return "".join(parts) 513 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============== 2 | flake8-logging 3 | ============== 4 | 5 | .. image:: https://img.shields.io/github/actions/workflow/status/adamchainz/flake8-logging/main.yml.svg?branch=main&style=for-the-badge 6 | :target: https://github.com/adamchainz/flake8-logging/actions?workflow=CI 7 | 8 | .. image:: https://img.shields.io/badge/Coverage-100%25-success?style=for-the-badge 9 | :target: https://github.com/adamchainz/flake8-logging/actions?workflow=CI 10 | 11 | .. image:: https://img.shields.io/pypi/v/flake8-logging.svg?style=for-the-badge 12 | :target: https://pypi.org/project/flake8-logging/ 13 | 14 | .. image:: https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge 15 | :target: https://github.com/psf/black 16 | 17 | .. image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=for-the-badge 18 | :target: https://github.com/pre-commit/pre-commit 19 | :alt: pre-commit 20 | 21 | A `Flake8 `_ plugin that checks for issues using the standard library logging module. 22 | 23 | For a brief overview and background, see `the introductory blog post `__. 24 | 25 | Requirements 26 | ============ 27 | 28 | Python 3.10 to 3.14 supported. 29 | 30 | Installation 31 | ============ 32 | 33 | First, install with ``pip``: 34 | 35 | .. code-block:: sh 36 | 37 | python -m pip install flake8-logging 38 | 39 | Second, if you define Flake8’s ``select`` setting, add the ``L`` prefix to it. 40 | Otherwise, the plugin should be active by default. 41 | 42 | ---- 43 | 44 | **Linting a Django project?** 45 | Check out my book `Boost Your Django DX `__ which covers Flake8 and many other code quality tools. 46 | 47 | ---- 48 | 49 | Rules 50 | ===== 51 | 52 | LOG001 use ``logging.getLogger()`` to instantiate loggers 53 | --------------------------------------------------------- 54 | 55 | The `Logger Objects documentation section `__ starts: 56 | 57 | Note that Loggers should NEVER be instantiated directly, but always through the module-level function ``logging.getLogger(name)``. 58 | 59 | Directly instantiated loggers are not added into the logger tree. 60 | This means that they bypass all configuration and their messages are only sent to the `last resort handler `__. 61 | This can mean their messages are incorrectly filtered, formatted, and sent only to ``stderr``. 62 | Potentially, such messages will not be visible in your logging tooling and you won’t be alerted to issues. 63 | 64 | Use |getLogger()|__ to correctly instantiate loggers. 65 | 66 | .. |getLogger()| replace:: ``getLogger()`` 67 | __ https://docs.python.org/3/library/logging.html#logging.getLogger 68 | 69 | This rule detects any module-level calls to ``Logger()``. 70 | 71 | Failing example: 72 | 73 | .. code-block:: python 74 | 75 | import logging 76 | 77 | logger = logging.Logger(__name__) 78 | 79 | Corrected: 80 | 81 | .. code-block:: python 82 | 83 | import logging 84 | 85 | logger = logging.getLogger(__name__) 86 | 87 | LOG002 use ``__name__`` with ``getLogger()`` 88 | -------------------------------------------- 89 | 90 | The `logging documentation `__ recommends this pattern: 91 | 92 | .. code-block:: python 93 | 94 | logging.getLogger(__name__) 95 | 96 | |__name__|__ is the fully qualified module name, such as ``camelot.spam``, which is the intended format for logger names. 97 | 98 | .. |__name__| replace:: ``__name__`` 99 | __ https://docs.python.org/3/reference/import.html?#name__ 100 | 101 | This rule detects probably-mistaken usage of similar module-level dunder constants: 102 | 103 | * |__cached__|__ - the pathname of the module’s compiled version˜, such as ``camelot/__pycache__/spam.cpython-311.pyc``. 104 | 105 | .. |__cached__| replace:: ``__cached__`` 106 | __ https://docs.python.org/3/reference/import.html?#cached__ 107 | 108 | * |__file__|__ - the pathname of the module, such as ``camelot/spam.py``. 109 | 110 | .. |__file__| replace:: ``__file__`` 111 | __ https://docs.python.org/3/reference/import.html?#file__ 112 | 113 | Failing example: 114 | 115 | .. code-block:: python 116 | 117 | import logging 118 | 119 | logger = logging.getLogger(__file__) 120 | 121 | Corrected: 122 | 123 | .. code-block:: python 124 | 125 | import logging 126 | 127 | logger = logging.getLogger(__name__) 128 | 129 | LOG003 ``extra`` key ``''`` clashes with LogRecord attribute 130 | ----------------------------------------------------------------- 131 | 132 | The |extra documentation|__ states: 133 | 134 | .. |extra documentation| replace:: ``extra`` documentation 135 | __ https://docs.python.org/3/library/logging.html#logging.Logger.debug 136 | 137 | The keys in the dictionary passed in ``extra`` should not clash with the keys used by the logging system. 138 | 139 | Such clashes crash at runtime with an error like: 140 | 141 | .. code-block:: text 142 | 143 | KeyError: "Attempt to overwrite 'msg' in LogRecord" 144 | 145 | Unfortunately, this error is only raised if the message is not filtered out by level. 146 | Tests may therefore not encounter the check, if they run with a limited logging configuration. 147 | 148 | This rule detects such clashes by checking for keys matching the |LogRecord attributes|__. 149 | 150 | .. |LogRecord attributes| replace:: ``LogRecord`` attributes 151 | __ https://docs.python.org/3/library/logging.html#logrecord-attributes 152 | 153 | Failing example: 154 | 155 | .. code-block:: python 156 | 157 | import logging 158 | 159 | logger = logging.getLogger(__name__) 160 | 161 | response = acme_api() 162 | logger.info("ACME Response", extra={"msg": response.msg}) 163 | 164 | Corrected: 165 | 166 | .. code-block:: python 167 | 168 | import logging 169 | 170 | logger = logging.getLogger(__name__) 171 | 172 | response = acme_api() 173 | logger.info("ACME Response", extra={"response_msg": response.msg}) 174 | 175 | LOG004 avoid ``exception()`` outside of exception handlers 176 | ---------------------------------------------------------- 177 | 178 | The |exception() documentation|__ states: 179 | 180 | .. |exception() documentation| replace:: ``exception()`` documentation 181 | __ https://docs.python.org/3/library/logging.html#logging.exception 182 | 183 | This function should only be called from an exception handler. 184 | 185 | Calling ``exception()`` outside of an exception handler attaches ``None`` exception information, leading to confusing messages: 186 | 187 | .. code-block:: pycon 188 | 189 | >>> logging.exception("example") 190 | ERROR:root:example 191 | NoneType: None 192 | 193 | Use ``error()`` instead. 194 | To log a caught exception, pass it in the ``exc_info`` argument. 195 | 196 | This rule detects ``exception()`` calls outside of exception handlers. 197 | 198 | Failing example: 199 | 200 | .. code-block:: python 201 | 202 | import logging 203 | 204 | response = acme_api() 205 | if response is None: 206 | logging.exception("ACME failed") 207 | 208 | Corrected: 209 | 210 | .. code-block:: python 211 | 212 | import logging 213 | 214 | response = acme_api() 215 | if response is None: 216 | logging.error("ACME failed") 217 | 218 | LOG005 use ``exception()`` within an exception handler 219 | ------------------------------------------------------ 220 | 221 | Within an exception handler, the |exception()|__ method is preferable over ``logger.error()``. 222 | The ``exception()`` method captures the exception automatically, whilst ``error()`` needs it to be passed explicitly in the ``exc_info`` argument. 223 | Both methods log with the level ``ERROR``. 224 | 225 | .. |exception()| replace:: ``exception()`` 226 | __ https://docs.python.org/3/library/logging.html#logging.Logger.exception 227 | 228 | This rule detects ``error()`` calls within exception handlers, excluding those with a falsy ``exc_info`` argument. 229 | 230 | Failing example: 231 | 232 | .. code-block:: python 233 | 234 | try: 235 | acme_api() 236 | except AcmeError as exc: 237 | logger.error("ACME API failed", exc_info=exc) 238 | 239 | Corrected: 240 | 241 | .. code-block:: python 242 | 243 | try: 244 | acme_api() 245 | except AcmeError: 246 | logger.exception("ACME API failed") 247 | 248 | Or alternatively, if the exception information is truly uninformative: 249 | 250 | .. code-block:: python 251 | 252 | try: 253 | acme_api() 254 | except DuplicateError: 255 | logger.error("ACME Duplicate Error", exc_info=False) 256 | 257 | LOG006 redundant ``exc_info`` argument for ``exception()`` 258 | ---------------------------------------------------------- 259 | 260 | The |exception()2|__ method captures the exception automatically, making a truthy ``exc_info`` argument redundant. 261 | 262 | .. |exception()2| replace:: ``exception()`` 263 | __ https://docs.python.org/3/library/logging.html#logging.Logger.exception 264 | 265 | This rule detects ``exception()`` calls within exception handlers with an ``exc_info`` argument that is truthy or the captured exception object. 266 | 267 | Failing example: 268 | 269 | .. code-block:: python 270 | 271 | try: 272 | acme_api() 273 | except AcmeError: 274 | logger.exception("ACME API failed", exc_info=True) 275 | 276 | Corrected: 277 | 278 | .. code-block:: python 279 | 280 | try: 281 | acme_api() 282 | except AcmeError: 283 | logger.exception("ACME API failed") 284 | 285 | LOG007 use ``error()`` instead of ``exception()`` with ``exc_info=False`` 286 | ------------------------------------------------------------------------- 287 | 288 | The |exception()3|__ method captures the exception automatically. 289 | Disabling this by setting ``exc_info=False`` is the same as using ``error()``, which is clearer and doesn’t need the ``exc_info`` argument. 290 | 291 | .. |exception()3| replace:: ``exception()`` 292 | __ https://docs.python.org/3/library/logging.html#logging.Logger.exception 293 | 294 | This rule detects ``exception()`` calls with an ``exc_info`` argument that is falsy. 295 | 296 | Failing example: 297 | 298 | .. code-block:: python 299 | 300 | logger.exception("Left phalange missing", exc_info=False) 301 | 302 | Corrected: 303 | 304 | .. code-block:: python 305 | 306 | logger.error("Left phalange missing") 307 | 308 | LOG008 ``warn()`` is deprecated, use ``warning()`` instead 309 | ---------------------------------------------------------- 310 | 311 | The ``warn()`` method is a deprecated, undocumented alias for |warning()|__ 312 | ``warning()`` should always be used instead. 313 | The method was deprecated in Python 2.7, in commit `04d5bc00a2 `__, and removed in Python 3.13, in commit `dcc028d924 `__. 314 | 315 | .. |warning()| replace:: ``warning()`` 316 | __ https://docs.python.org/3/library/logging.html#logging.Logger.warning 317 | 318 | This rule detects calls to ``warn()``. 319 | 320 | Failing example: 321 | 322 | .. code-block:: python 323 | 324 | logger.warn("Cheesy puns incoming") 325 | 326 | Corrected: 327 | 328 | .. code-block:: python 329 | 330 | logger.warning("Cheesy puns incoming") 331 | 332 | LOG009 ``WARN`` is undocumented, use ``WARNING`` instead 333 | -------------------------------------------------------- 334 | 335 | The ``WARN`` constant is an undocumented alias for |WARNING|__. 336 | Whilst it’s not deprecated, it’s not mentioned at all in the documentation, so the documented ``WARNING`` should always be used instead. 337 | 338 | .. |WARNING| replace:: ``WARNING`` 339 | __ https://docs.python.org/3/library/logging.html#logging-levels 340 | 341 | This rule detects any import or access of ``WARN``. 342 | 343 | Failing example: 344 | 345 | .. code-block:: python 346 | 347 | import logging 348 | 349 | logging.WARN 350 | 351 | Corrected: 352 | 353 | .. code-block:: python 354 | 355 | import logging 356 | 357 | logging.WARNING 358 | 359 | LOG010 ``exception()`` does not take an exception 360 | ------------------------------------------------- 361 | 362 | Like other logger methods, the |exception()4|__ method takes a string as its first argument. 363 | A common misunderstanding is to pass it an exception instead. 364 | Doing so is redundant, as ``exception()`` will already capture the exception object. 365 | It can also lead to unclear log messages, as the logger will call ``str()`` on the exception, which doesn’t always produce a sensible message. 366 | 367 | .. |exception()4| replace:: ``exception()`` 368 | __ https://docs.python.org/3/library/logging.html#logging.Logger.exception 369 | 370 | This rule detects ``exception()`` calls with a first argument that is the current exception handler’s capture variable. 371 | 372 | Failing example: 373 | 374 | .. code-block:: python 375 | 376 | try: 377 | shuffle_deck() 378 | except Exception as exc: 379 | logger.exception(exc) 380 | 381 | Corrected: 382 | 383 | .. code-block:: python 384 | 385 | try: 386 | shuffle_deck() 387 | except Exception: 388 | logger.exception("Failed to shuffle deck") 389 | 390 | LOG011 avoid pre-formatting log messages 391 | ---------------------------------------- 392 | 393 | Logger methods support string formatting for `logging variable data `__, such as: 394 | 395 | .. code-block:: python 396 | 397 | logger.info("Couldn’t chop %s", vegetable) 398 | 399 | Log-aggregating tools, such as `Sentry `__ can group messages based on their unformatted message templates. 400 | Using a pre-formatted message, such as from an f-string, prevents this from happening. 401 | Tools have to rely on imperfect heuristics, which can lead to duplicate groups. 402 | 403 | Additionally, the logging framework skips formatting messages that won’t be logged. 404 | Using a pre-formatted string, such as from an f-string, has no such optimization. 405 | This overhead can add up when you have a high volume of logs that are normally skipped. 406 | 407 | This rule detects logger method calls with a ``msg`` argument that is one of: 408 | 409 | * an f-string 410 | * a call to ``str.format()`` 411 | * a string used with the modulus operator (``%``) 412 | * a concatenation of strings with non-strings 413 | 414 | Failing examples: 415 | 416 | .. code-block:: python 417 | 418 | logging.error(f"Couldn’t chop {vegetable}") 419 | 420 | .. code-block:: python 421 | 422 | logging.error("Couldn’t chop {}".format(vegetable)) 423 | 424 | .. code-block:: python 425 | 426 | logging.error("Couldn’t chop %s" % (vegetable,)) 427 | 428 | .. code-block:: python 429 | 430 | logging.error("Couldn’t chop " + vegetable) 431 | 432 | Corrected: 433 | 434 | .. code-block:: python 435 | 436 | logging.error("Couldn’t chop %s", vegetable) 437 | 438 | LOG012 formatting error: ```` ``