Skip to content

Instantly share code, notes, and snippets.

@mashiro
Last active August 29, 2015 14:10
Show Gist options
  • Save mashiro/0303ff724db08678801d to your computer and use it in GitHub Desktop.
Save mashiro/0303ff724db08678801d to your computer and use it in GitHub Desktop.
Rails のログを構造化するやつ
module MyApp
class LogSubscriber < ActiveSupport::LogSubscriber
INTERNAL_PARAMS = %w(controller action format _method only_path)
IGNORE_PAYLOAD_NAMES = ["SCHEMA", "EXPLAIN"]
class << self
attr_accessor :logger
end
def registry
Thread.current[:myapp_log_subscriber_registry] ||= {}
end
def reset_registry
reg = registry.dup
registry.clear
reg
end
def render_bind(column, value)
if column
if column.binary?
# This specifically deals with the PG adapter that casts bytea columns into a Hash.
value = value[:value] if value.is_a?(Hash)
value = value ? "<#{value.bytesize} bytes of binary data>" : "<NULL binary data>"
end
[column.name, value]
else
[nil, value]
end
end
def sql(event)
payload = event.payload
return if IGNORE_PAYLOAD_NAMES.include?(payload[:name])
query = {}
query[:sql] = payload[:sql]
query[:binds] = payload[:binds].map { |col, v| render_bind(col, v) }
query[:name] = payload[:name]
query[:duration] = event.duration
(registry[:queries] ||= []) << query
end
def process_action(event)
payload = event.payload
registry[:method] = payload[:method]
registry[:path] = payload[:path]
registry[:format] = payload[:format]
registry[:params] = payload[:params].except(*INTERNAL_PARAMS)
registry[:controller] = payload[:controller]
registry[:action] = payload[:action]
registry[:status] = payload[:status]
registry[:view_runtime] = payload[:view_runtime]
registry[:db_runtime] = payload[:db_runtime]
info reset_registry
end
def logger
MyApp::LogSubscriber.logger.presence || Rails.logger
end
end
end
MyApp::LogSubscriber.attach_to :action_controller
MyApp::LogSubscriber.attach_to :active_record
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment