|
| 1 | +from __future__ import absolute_import |
| 2 | +from __future__ import print_function |
| 3 | + |
| 4 | +import logging |
| 5 | + |
| 6 | +from sentry_sdk import get_current_hub, capture_event |
| 7 | +from sentry_sdk.utils import to_string, create_event, exceptions_from_error_tuple, skip_internal_frames |
| 8 | + |
| 9 | +class SentryHandler(logging.Handler, object): |
| 10 | + def emit(self, record): |
| 11 | + try: |
| 12 | + self.format(record) |
| 13 | + return self._emit(record) |
| 14 | + except Exception: |
| 15 | + get_current_hub().capture_internal_exception() |
| 16 | + |
| 17 | + def can_record(self, record): |
| 18 | + return not record.name.startswith('sentry_sdk') |
| 19 | + |
| 20 | + def _emit(self, record): |
| 21 | + if not self.can_record(record): |
| 22 | + print(to_string(record.message), file=sys.stderr) |
| 23 | + return |
| 24 | + |
| 25 | + event = create_event() |
| 26 | + |
| 27 | + # exc_info might be None or (None, None, None) |
| 28 | + if record.exc_info and all(record.exc_info): |
| 29 | + exc_type, exc_value, tb = record.exc_info |
| 30 | + event['exception'] = exceptions_from_error_tuple( |
| 31 | + exc_type, exc_value, skip_internal_frames(tb), |
| 32 | + get_current_hub().client.options['with_locals'] |
| 33 | + ) |
| 34 | + |
| 35 | + event['level'] = record.levelname.lower() |
| 36 | + event['logger'] = record.name |
| 37 | + |
| 38 | + event['logentry'] = { |
| 39 | + 'message': to_string(record.msg), |
| 40 | + 'params': record.args |
| 41 | + } |
| 42 | + |
| 43 | + capture_event(event) |
| 44 | + |
| 45 | + |
| 46 | +HANDLER = SentryHandler() |
0 commit comments