python-json-logger
python-json-logger copied to clipboard
how to log exception with extra?
Is this possible?
except IOError as io_msg:
log.error(f'Failed to open device data', extra={"device": log_prefix}, io_msg)
What are you trying to achieve?
If you want to provide extra data alongside the exception data, you can use log.exception(message, extras) or log.error(message, extras, exc_info=True). exc_info is available on all logging methods and tells the logging system to collect and format... exception info.
logging.exception is a convenience alias for logging.error(..., exc_info=True).
jsonlogger adds the formatted exception information as the exc_info on the generated record.
If you just want to store the exception message as an extra, add the stringification of the exception object (which is what you're actually catching) to the dict the normal way: log.error(msg, extra={..., 'error_message': str(io_msg)}).