python.lang.best-practice.logging-error-without-handling.logging-error-without-handling

profile photo of semgrepsemgrep
Author
unknown
Download Count*

Errors should only be logged when handled. The code logs the error and propogates the exception, consider reducing the level to warning or info.

Run Locally

Run in CI

Defintion

rules:
  - id: logging-error-without-handling
    patterns:
      - pattern-inside: |
          try:
            ...
          except ...:
            ...
          ...
      - pattern-either:
          - pattern: |
              logger.$FUNC(...)
              ...
              raise
          - pattern: |
              logger.$FUNC(...)
              ...
              raise $EX
          - pattern: |
              logger.$FUNC(...)
              ...
              raise $EX from $EX2
      - metavariable-regex:
          metavariable: $FUNC
          regex: (error|exception)
    message: Errors should only be logged when handled. The code logs the error and
      propogates the exception, consider reducing the level to warning or info.
    languages:
      - python
    severity: WARNING
    metadata:
      category: best-practice
      technology:
        - python
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

logging-error-without-handling.py

# logger.error
try:
  pass
except:
  pass
  # ruleid:logging-error-without-handling
  logger.error("")
  raise

try:
  pass
except Exception as e:
  # ruleid:logging-error-without-handling
  logger.error("")
  raise e

try:
  pass
except ValueError as e:
  # ruleid:logging-error-without-handling
  logger.error("")
  raise e
except Exception:
  pass

try:
  pass
except Exception:
  pass
except ValueError as e:
  # ruleid:logging-error-without-handling
  logger.error("")
  raise e

try:
  pass
except Exception:
  # ruleid:logging-error-without-handling
  logger.error("")
  raise

try:
  pass
except Exception as e:
  # ruleid:logging-error-without-handling
  logger.error("")
  raise ValueError() from e


# logger.exception

try:
  pass
except:
  pass
  # ruleid:logging-error-without-handling
  logger.exception("")
  raise

try:
  pass
except Exception as e:
  # ruleid:logging-error-without-handling
  logger.exception("")
  raise e

try:
  pass
except ValueError as e:
  # ruleid:logging-error-without-handling
  logger.exception("")
  raise e
except Exception:
  pass

try:
  pass
except Exception:
  pass
except ValueError as e:
  # ruleid:logging-error-without-handling
  logger.exception("")
  raise e

try:
  pass
except Exception:
  # ruleid:logging-error-without-handling
  logger.exception("")
  raise

try:
  pass
except Exception as e:
  # ruleid:logging-error-without-handling
  logger.exception("")
  raise ValueError() from e

# Make sure we don't match info/warning
try:
  pass
except Exception as e:
  logger.info("")
  logger.warning("")
  raise ValueError() from e