|
| 1 | +from sentry_sdk.utils import add_global_repr_processor, safe_repr |
| 2 | +from sentry_sdk.scope import add_global_event_processor |
| 3 | +from sentry_sdk.events import iter_stacktraces |
| 4 | + |
| 5 | +from sentry_sdk.integrations import Integration |
| 6 | + |
| 7 | + |
| 8 | +class DeepVarsIntegration(Integration): |
| 9 | + identifier = "deep_vars" |
| 10 | + |
| 11 | + @staticmethod |
| 12 | + def setup_once(): |
| 13 | + add_global_repr_processor(_deep_vars_repr) |
| 14 | + add_global_event_processor(_deep_vars_processor) |
| 15 | + |
| 16 | + |
| 17 | +class DeepVar(object): |
| 18 | + __slots__ = ("obj", "fields") |
| 19 | + |
| 20 | + def __init__(self, obj, fields): |
| 21 | + self.obj = obj |
| 22 | + self.fields = fields |
| 23 | + |
| 24 | + |
| 25 | +def _deep_vars_repr(obj, hint): |
| 26 | + if type(obj) in (list, dict, str, float, bool): |
| 27 | + return NotImplemented |
| 28 | + |
| 29 | + try: |
| 30 | + return DeepVar( |
| 31 | + obj, {k: safe_repr(obj.__dict__[k]) for k in dir(obj) if k in obj.__dict__} |
| 32 | + ) |
| 33 | + except Exception: |
| 34 | + pass |
| 35 | + |
| 36 | + return NotImplemented |
| 37 | + |
| 38 | + |
| 39 | +def _deep_vars_processor(event, hint): |
| 40 | + for stacktrace in iter_stacktraces(event): |
| 41 | + _process_stacktrace(stacktrace) |
| 42 | + |
| 43 | + return event |
| 44 | + |
| 45 | + |
| 46 | +def _process_stacktrace(stacktrace): |
| 47 | + for frame in stacktrace.get("frames") or (): |
| 48 | + vars = frame.get("vars") |
| 49 | + if not vars: |
| 50 | + continue |
| 51 | + |
| 52 | + new_vars = {} |
| 53 | + |
| 54 | + for key, value in vars.items(): |
| 55 | + if isinstance(value, DeepVar): |
| 56 | + for key2, value2 in value.fields.items(): |
| 57 | + new_vars["{}.{}".format(key, key2)] = value2 |
| 58 | + new_vars[key] = safe_repr(value.obj) |
| 59 | + else: |
| 60 | + new_vars[key] = value |
| 61 | + |
| 62 | + frame["vars"] = new_vars |
0 commit comments