Skip to content

Python logging


import logging

logger = logging.getLogger(__name__)"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():
        DeprecationWarning('use new_func instead'),
$ PYTHONWARNINGS=once python3

$ python3 -Wonce

$ python3 -Werror

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


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