|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# Copyright The OpenTelemetry Authors |
| 4 | +# |
| 5 | +# SPDX-License-Identifier: Apache-2.0 |
| 6 | + |
| 7 | +module OpenTelemetry |
| 8 | + module Instrumentation |
| 9 | + module Redis |
| 10 | + module Middlewares |
| 11 | + # Adapter for redis-client instrumentation interface |
| 12 | + module RedisClientMetrics |
| 13 | + def call(command, redis_config) |
| 14 | + return super unless (histogram = instrumentation.client_operation_duration_histogram) |
| 15 | + |
| 16 | + timed(histogram, command.first, redis_config) do |
| 17 | + super |
| 18 | + end |
| 19 | + end |
| 20 | + |
| 21 | + def call_pipelined(commands, redis_config) |
| 22 | + return super unless (histogram = instrumentation.client_operation_duration_histogram) |
| 23 | + |
| 24 | + timed(histogram, 'PIPELINE', redis_config) do |
| 25 | + super |
| 26 | + end |
| 27 | + end |
| 28 | + |
| 29 | + private |
| 30 | + |
| 31 | + def timed(histogram, operation_name, redis_config) |
| 32 | + t0 = monotonic_now |
| 33 | + |
| 34 | + yield.tap do |
| 35 | + duration = monotonic_now - t0 |
| 36 | + |
| 37 | + histogram.record(duration, attributes: metric_attributes(redis_config, operation_name)) |
| 38 | + end |
| 39 | + end |
| 40 | + |
| 41 | + def monotonic_now |
| 42 | + Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second) |
| 43 | + end |
| 44 | + |
| 45 | + def metric_attributes(redis_config, operation_name) |
| 46 | + attributes = { |
| 47 | + 'db.system' => 'redis', |
| 48 | + 'db.operation.name' => operation_name, |
| 49 | + 'net.peer.name' => redis_config.host, |
| 50 | + 'net.peer.port' => redis_config.port |
| 51 | + } |
| 52 | + |
| 53 | + attributes['db.redis.database_index'] = redis_config.db unless redis_config.db.zero? |
| 54 | + attributes['peer.service'] = instrumentation.config[:peer_service] if instrumentation.config[:peer_service] |
| 55 | + attributes.merge!(OpenTelemetry::Instrumentation::Redis.attributes) |
| 56 | + attributes |
| 57 | + end |
| 58 | + |
| 59 | + def instrumentation |
| 60 | + Redis::Instrumentation.instance |
| 61 | + end |
| 62 | + end |
| 63 | + end |
| 64 | + end |
| 65 | + end |
| 66 | +end |
0 commit comments