_log_batcher.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from typing import TYPE_CHECKING
  2. from sentry_sdk._batcher import Batcher
  3. from sentry_sdk.utils import serialize_attribute
  4. from sentry_sdk.envelope import Item, PayloadRef
  5. if TYPE_CHECKING:
  6. from typing import Any
  7. from sentry_sdk._types import Log
  8. class LogBatcher(Batcher["Log"]):
  9. MAX_BEFORE_FLUSH = 100
  10. MAX_BEFORE_DROP = 1_000
  11. FLUSH_WAIT_TIME = 5.0
  12. TYPE = "log"
  13. CONTENT_TYPE = "application/vnd.sentry.items.log+json"
  14. @staticmethod
  15. def _to_transport_format(item: "Log") -> "Any":
  16. if "sentry.severity_number" not in item["attributes"]:
  17. item["attributes"]["sentry.severity_number"] = item["severity_number"]
  18. if "sentry.severity_text" not in item["attributes"]:
  19. item["attributes"]["sentry.severity_text"] = item["severity_text"]
  20. res = {
  21. "timestamp": int(item["time_unix_nano"]) / 1.0e9,
  22. "trace_id": item.get("trace_id", "00000000-0000-0000-0000-000000000000"),
  23. "span_id": item.get("span_id"),
  24. "level": str(item["severity_text"]),
  25. "body": str(item["body"]),
  26. "attributes": {
  27. k: serialize_attribute(v) for (k, v) in item["attributes"].items()
  28. },
  29. }
  30. return res
  31. def _record_lost(self, item: "Log") -> None:
  32. # Construct log envelope item without sending it to report lost bytes
  33. log_item = Item(
  34. type=self.TYPE,
  35. content_type=self.CONTENT_TYPE,
  36. headers={
  37. "item_count": 1,
  38. },
  39. payload=PayloadRef(json={"items": [self._to_transport_format(item)]}),
  40. )
  41. self._record_lost_func(
  42. reason="queue_overflow",
  43. data_category="log_item",
  44. item=log_item,
  45. quantity=1,
  46. )