File: log_subscriber.rb

package info (click to toggle)
ruby-graphql-client 0.26.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 264 kB
  • sloc: ruby: 2,077; makefile: 4
file content (52 lines) | stat: -rw-r--r-- 1,497 bytes parent folder | download
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
# frozen_string_literal: true
require "active_support/log_subscriber"

module GraphQL
  class Client
    # Public: Logger for "*.graphql" notification events.
    #
    # Logs GraphQL queries to Rails logger.
    #
    #   UsersController::ShowQuery QUERY (123ms)
    #   UsersController::UpdateMutation MUTATION (456ms)
    #
    # Enable GraphQL Client query logging.
    #
    #   require "graphql/client/log_subscriber"
    #   GraphQL::Client::LogSubscriber.attach_to :graphql
    #
    class LogSubscriber < ActiveSupport::LogSubscriber
      SHOULD_USE_KWARGS = private_instance_methods.include?(:mode_from)

      def query(event)
        logger.info do
          name = event.payload[:operation_name].gsub("__", "::")
          type = event.payload[:operation_type].upcase

          if SHOULD_USE_KWARGS
            color("#{name} #{type} (#{event.duration.round(1)}ms)", nil, bold: true)
          else
            color("#{name} #{type} (#{event.duration.round(1)}ms)", nil, true)
          end
        end

        logger.debug do
          event.payload[:document].to_query_string
        end
      end

      def error(event)
        logger.error do
          name = event.payload[:operation_name].gsub("__", "::")
          message = event.payload[:message]

          if SHOULD_USE_KWARGS
            color("#{name} ERROR: #{message}", nil, bold: true)
          else
            color("#{name} ERROR: #{message}", nil, true)
          end
        end
      end
    end
  end
end