Skip to content

Python logging

Code

import logging

logger = logging.getLogger(__name__)
logger.info("My message")

Error levels

Info levels - INFO

  • INFO: general info
  • WARNING: Minor problem
    • still info, give more details when debugging
  • ERROR: Major problem
    • something's broken! high priority
  • CRITICAL: Critical problem
    • system as as whole is down

warnings module

Fullchee Values

warns devs, not end users

Using warnings module

Useful for deprecation notices

stacklevel should be 2+ - default stacklevel is 1 - not helpful, doesn't say who called the module

import warnings

def old_func():
    warnings.warn(
        DeprecationWarning('use new_func instead'),
        stacklevel=2
    )
$ PYTHONWARNINGS=once python3 file.py

$ python3 -Wonce file.py

$ python3 -Werror file.py

logging.warning vs warnings.warn

  • logging.warning
    • issue with input/user
    • nothing the client app can do
  • warnings.warn
    • dev issue
      • examples
        • deprecated code
        • abstract class not implement

Adding a traceback

log stack trace

can only be in an except clause

  • otherwise you get an error
except Exception as e:
    logger.exception("Exception message")

Shorthand for

logger.error("something weird happened", exc_info=True)

Deprecated warning

warnings.warn(
              "message",
              category=DeprecationWarning,
)

Last update: 2022-11-04