3 ms·
I mentioned this almost every time logging and python come up but one of my favorite feature is logging.exception: https://docs.python.org/3/library/logging.htm
by memco 4y ago
I mentioned this almost every time logging and python come up but one of my favorite feature is logging.exception: https://docs.python.org/3/library/logging.html#logging.Logger.exception https://docs.python.org/3/library/logging.html#logging.Logge.... It allows you to attach the whole exception with stack trace without having to explicitly used “as e” and then use traceback or embed the error in the message. Something like logger.exception(“Failed to connect.”) will print the message and the exception in one go.
- Narushia 4y agoI second this, very useful. I kind of expected the article to mention it, but it didn’t!
- atorodius 4y agoI'm using this too, but I always found it very unreadable for people unfamiliar with it. It's so surprising that it catches the exception for you! I end up always adding a commend ``` logger.exception("Failed to connect.") # Will print exception. ```
- pR0Ps 4y agoYou can actually do this with any level of log message by passing `exc_info=True` to it. This is super useful in cases where you want to log the exception context, but don't need to be at a high logging level. Ex: logger.debug("A non-critical exception occurred", exc_info=True)