File: log_event_buffer.rb

package info (click to toggle)
ruby-sentry-ruby-core 5.28.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 672 kB
  • sloc: ruby: 6,118; makefile: 8; sh: 4
file content (75 lines) | stat: -rw-r--r-- 1,612 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# frozen_string_literal: true

require "sentry/threaded_periodic_worker"

module Sentry
  # LogEventBuffer buffers log events and sends them to Sentry in a single envelope.
  #
  # This is used internally by the `Sentry::Client`.
  #
  # @!visibility private
  class LogEventBuffer < ThreadedPeriodicWorker
    FLUSH_INTERVAL = 5 # seconds
    DEFAULT_MAX_EVENTS = 100

    # @!visibility private
    attr_reader :pending_events

    def initialize(configuration, client)
      super(configuration.sdk_logger, FLUSH_INTERVAL)

      @client = client
      @pending_events = []
      @max_events = configuration.max_log_events || DEFAULT_MAX_EVENTS
      @mutex = Mutex.new

      log_debug("[Logging] Initialized buffer with max_events=#{@max_events}, flush_interval=#{FLUSH_INTERVAL}s")
    end

    def start
      ensure_thread
      self
    end

    def flush
      @mutex.synchronize do
        return if empty?

        log_debug("[LogEventBuffer] flushing #{size} log events")

        send_events
      end

      log_debug("[LogEventBuffer] flushed #{size} log events")

      self
    end
    alias_method :run, :flush

    def add_event(event)
      raise ArgumentError, "expected a LogEvent, got #{event.class}" unless event.is_a?(LogEvent)

      @mutex.synchronize do
        @pending_events << event
        send_events if size >= @max_events
      end

      self
    end

    def empty?
      @pending_events.empty?
    end

    def size
      @pending_events.size
    end

    private

    def send_events
      @client.send_logs(@pending_events)
      @pending_events.clear
    end
  end
end