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)
  • exc_info=True is useful if you want to log an error

Deprecated warning

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

Tips on logging message

  • multiple machines?
    • include a request ID so all logs can be grouped
  • per user
    • easily debug a user specific issue

Last update: 2023-04-24