Module: BrainzLab::Instrumentation::DalliInstrumentation

Defined in:
lib/brainzlab/instrumentation/dalli.rb

Constant Summary collapse

TRACKED_COMMANDS =
%w[get set add replace delete incr decr cas get_multi set_multi].freeze

Class Method Summary collapse

Class Method Details

.extract_key(args) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
# File 'lib/brainzlab/instrumentation/dalli.rb', line 95

def self.extract_key(args)
  key = args.first
  case key
  when String
    key.length > 50 ? "#{key[0..47]}..." : key
  when Array
    "[#{key.size} keys]"
  else
    key.to_s[0..50]
  end
end

.install!Object



9
10
11
12
13
14
15
# File 'lib/brainzlab/instrumentation/dalli.rb', line 9

def install!
  return unless defined?(::Dalli::Client)

  install_client_instrumentation!

  BrainzLab.debug_log('[Instrumentation] Dalli/Memcached instrumentation installed')
end

.track_command(command, args) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/brainzlab/instrumentation/dalli.rb', line 37

def self.track_command(command, args)
  started_at = Time.now

  begin
    result = yield
    track_success(command, args, started_at, result)
    result
  rescue StandardError => e
    track_error(command, args, started_at, e)
    raise
  end
end

.track_error(command, args, started_at, error) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/brainzlab/instrumentation/dalli.rb', line 79

def self.track_error(command, args, started_at, error)
  ((Time.now - started_at) * 1000).round(2)
  key = extract_key(args)

  BrainzLab::Reflex.add_breadcrumb(
    "Memcached #{command.upcase} failed: #{error.message}",
    category: 'cache',
    level: :error,
    data: { command: command, key: key, error: error.class.name }
  )

  return unless BrainzLab.configuration.flux_effectively_enabled?

  BrainzLab::Flux.increment('memcached.errors', tags: { command: command })
end

.track_success(command, args, started_at, result) ⇒ Object



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
76
77
# File 'lib/brainzlab/instrumentation/dalli.rb', line 50

def self.track_success(command, args, started_at, result)
  duration_ms = ((Time.now - started_at) * 1000).round(2)
  key = extract_key(args)

  # Add breadcrumb
  BrainzLab::Reflex.add_breadcrumb(
    "Memcached #{command.upcase}",
    category: 'cache',
    level: :info,
    data: { command: command, key: key, duration_ms: duration_ms }
  )

  # Track with Flux
  return unless BrainzLab.configuration.flux_effectively_enabled?

  tags = { command: command }
  BrainzLab::Flux.distribution('memcached.duration_ms', duration_ms, tags: tags)
  BrainzLab::Flux.increment('memcached.commands', tags: tags)

  # Track cache hits/misses for get commands
  return unless command == 'get'

  if result.nil?
    BrainzLab::Flux.increment('memcached.miss', tags: tags)
  else
    BrainzLab::Flux.increment('memcached.hit', tags: tags)
  end
end