問題
graphqlを使ってると、model側で遅いのか?graphqlのタイプ側で遅いのか?更に階層が深いと検討がつきにくい。
解決
公式ドキュメントには丁寧な説明がないけど、
ここのブログでいい感じにログに出せるようなコードがあった。
platform_trace
で実行時間を計算してobserve
に渡してるんで、そこでログに吐くなりできる。
app_schema.rb
class MyCustomTracer < GraphQL::Tracing::PlatformTracing
self.platform_keys = {
"lex" => "graphql.lex",
"parse" => "graphql.parse",
"validate" => "graphql.validate",
"analyze_multiplex" => "graphql.analyze_multiplex",
"analyze_query" => "graphql.analyze_query",
"execute_multiplex" => "graphql.execute_multiplex",
"execute_query" => "graphql.execute_query",
"execute_query_lazy" => "ygraphql.execute_query_lazy",
"execute_field" => "graphql.execute_field",
"execute_field_lazy" => "ygraphql.execute_field_lazy",
"authorized" => "graphql.authorized",
"authorized_lazy" => "graphql.authorized_lazy",
"resolve_type" => "graphql.resolve_type",
"resolve_type_lazy" => "graphql.resolve_type_lazy",
}
def platform_trace(platform_key, key, _data, &block)
start = ::Process.clock_gettime ::Process::CLOCK_MONOTONIC
result = block.call
duration = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - start
observe(platform_key, key, duration)
result
end
def platform_field_key(type, field)
"graphql.#{type.graphql_name}.#{field.graphql_name}"
end
def platform_authorized_key(type)
"graphql.authorized.#{type.graphql_name}"
end
def platform_resolve_type_key(type)
"graphql.resolve_type.#{type.graphql_name}"
end
def observe(platform_key, key, duration)
return if key == "authorized"
Rails
.logger.debug "platform_key: #{platform_key}, key: #{key}, duration: #{(duration * 1000).round(5)} ms"
end
end
tracer(MyCustomTracer.new)
元々のコードは
def observe(platform_key, key, duration)
return if key == 'authorized'
puts "platform_key: #{platform_key}, key: #{key}, duration: #{(duration * 1000).round(5)} ms".yellow
end
となっていて.yellow
は無いとエラーになったが、たぶんこれはhttps://github.com/sickill/rainbowを入れているんだと思う。
# https://github.com/sickill/rainbow#refinement
require 'rainbow/refinement'
using Rainbow
puts "Hi!".green