Sha256: 3653c974c5de5c4559cca2ebf08099c2c476c4af29b256899240b0818bc5b3bc

Contents?: true

Size: 1.85 KB

Versions: 3

Compression:

Stored size: 1.85 KB

Contents

# frozen_string_literal: true

require "opentracing"

module Labkit
  module Tracing
    # Common is a mixin for various distributed tracing instrumentation
    module Common
      def tracer
        OpenTracing.global_tracer
      end

      # Convience method for running a block with a span
      def in_tracing_span(operation_name:, tags:, child_of: nil)
        scope = tracer.start_active_span(operation_name, child_of: child_of, tags: tags)
        span = scope.span

        # Add correlation details to the span if we have them
        correlation_id = Labkit::Correlation::CorrelationId.current_id
        span.set_tag("correlation_id", correlation_id) if correlation_id

        begin
          yield span
        rescue StandardError => e
          log_exception_on_span(span, e)
          raise e
        ensure
          scope.close
        end
      end

      def postnotify_span(operation_name, start_time, end_time, tags: nil, child_of: nil, exception: nil)
        span = OpenTracing.start_span(operation_name, start_time: start_time, tags: tags, child_of: child_of)

        log_exception_on_span(span, exception) if exception

        span.finish(end_time: end_time)
      end

      def log_exception_on_span(span, exception)
        span.set_tag("error", true)
        span.log_kv(kv_tags_for_exception(exception))
      end

      def kv_tags_for_exception(exception)
        case exception
        when Exception
          {
            :"event" => "error",
            :"error.kind" => exception.class.to_s,
            :"message" => Labkit::Logging::Sanitizer.sanitize_field(exception.message),
            :"stack" => exception.backtrace&.join('\n'),
          }
        else
          { :"event" => "error", :"error.kind" => exception.class.to_s, :"error.object" => Labkit::Logging::Sanitizer.sanitize_field(exception.to_s) }
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
gitlab-labkit-0.1.2 lib/labkit/tracing/common.rb
gitlab-labkit-0.1.0.pre.1.pre.gcb57c95 lib/labkit/tracing/common.rb
gitlab-labkit-0.1.0 lib/labkit/tracing/common.rb