When code that uses logging catches an exception, log.error(str(e)) is a common sight. That loses the traceback. log.exception keeps it.
import logging
log = logging.getLogger(__name__)
def sync(host):
try:
upload(host)
except OSError:
log.exception("sync failed for %s", host)
It logs at ERROR level, like log.error, and then adds the traceback of the exception that’s being handled. In a log file or the journal you get your own message on the first line and the stack below it, so later you can see where it went wrong without reproducing anything.
I pass the host as an argument instead of building an f-string. Logging only formats the message when it’s actually written, and handlers that group similar errors see the same template every time.
Only call it from inside an except block. Outside one there’s no current exception, and you get your message followed by NoneType: None, which looks like a bug of its own. If you want a traceback at a different level, for example a warning for an error you expect now and then, use log.warning("...", exc_info=True) instead.
Further reading: Logger.exception