# Copyright (c) 2015 Sqreen. All Rights Reserved. # Please refer to our terms for more information: https://www.sqreen.io/terms.html require 'sqreen/performance_notifications' module Sqreen module PerformanceNotifications # Log performances on the console class NewRelic @subid = nil @level = 0 class << self def timings v = SharedStorage.get(:log_performance_nr_timings) if v.nil? v = [] self.timings = v end v end def timings=(value) SharedStorage.set(:log_performance_nr_timings, value) end def log(event, start, finish, _meta) timings << [event, start, finish] end def enabled? !@subid.nil? end def report(hash) if ::NewRelic::Agent.respond_to?(:add_custom_attributes) return ::NewRelic::Agent.add_custom_attributes(hash) end ::NewRelic::Agent.add_custom_parameters(:user_id => @user.id) end def next_request return unless enabled? if @level == 1 overhead = timings.map do |_evt, start, finish| (finish - start) * 1000 end.inject(0, &:+) report('sqreen_time' => overhead) else output = timings.map do |evt, start, finish| [evt.split('/')[1], (finish - start) * 1000] end total = 0 count = 0 rules = output.inject({}) do |acc, (e, t)| tt, cc = (acc[e] || [0, 0]) acc[e] = [tt + t, cc + 1] total += t count += 1 acc end attrs = rules.inject('sqreen_time' => total, 'sqreen_count' => count) do |acc, (rule, values)| acc["sqreen_#{rule}_time"] = values[0] acc["sqreen_#{rule}_count"] = values[1] acc end report(attrs) end self.timings = [] end def enable(level = 0) return unless @subid.nil? return unless defined?(::NewRelic::Agent) return unless ::NewRelic::Agent.respond_to?(:add_custom_attributes) || ::NewRelic::Agent.respond_to?(:add_custom_parameters) return unless level > 0 @level = level Sqreen.log.debug('Enabling New Relic reporting') @subid = Sqreen::PerformanceNotifications.subscribe(&method(:log)) end def disable return if @subid.nil? Sqreen::PerformanceNotifications.unsubscribe(@subid) @subid = nil @level = 0 end end end end end