Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

How do you log an exception with its traceback?

BeginnerConceptExceptions, context managers, files & logging
Answer

Inside an except block, use log.exception("msg"), which logs at ERROR and appends the traceback. At other levels pass exc_info=True.

try:
    client.delete_snapshot(SnapshotId=sid)
except ClientError:
    log.exception("failed to delete %s", sid)
    raise

log.error(str(e)) loses the stack, which is the one thing you need at 3 AM.

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging