summaryrefslogtreecommitdiff
path: root/lib/gitlab/correlation_id.rb
blob: 0f9bde4390eeaed8b40dee6e4b7ac70b32a25ed4 (plain)
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
# frozen_string_literal: true

module Gitlab
  module CorrelationId
    LOG_KEY = 'correlation_id'.freeze

    class << self
      def use_id(correlation_id, &blk)
        # always generate a id if null is passed
        correlation_id ||= new_id

        ids.push(correlation_id || new_id)

        begin
          yield(current_id)
        ensure
          ids.pop
        end
      end

      def current_id
        ids.last
      end

      def current_or_new_id
        current_id || new_id
      end

      private

      def ids
        Thread.current[:correlation_id] ||= []
      end

      def new_id
        SecureRandom.uuid
      end
    end
  end
end