Class: SweetNotifications::LogSubscriber

Inherits:
ActiveSupport::LogSubscriber
  • Object
show all
Defined in:
lib/sweet_notifications/log_subscriber.rb

Overview

LogSubscriber with runtime calculation and improved logging

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLogSubscriber

Returns a new instance of LogSubscriber.



10
11
12
13
# File 'lib/sweet_notifications/log_subscriber.rb', line 10

def initialize
  super
  @odd = false
end

Class Method Details

.color(odd, even = nil) ⇒ Object

Set colors for logging title and duration



61
62
63
64
# File 'lib/sweet_notifications/log_subscriber.rb', line 61

def color(odd, even = nil)
  self.odd_color = odd
  self.even_color = even || odd
end

.event(command, runtime: true) {|ActiveSupport::Notifications::Event| ... } ⇒ Object

Define an event subscriber

Parameters:

  • command (Symbol)

    event name

  • runtime (Boolean) (defaults to: true)

    aggregate runtime for this event

Yields:

  • (ActiveSupport::Notifications::Event)

    handle event



71
72
73
74
75
76
# File 'lib/sweet_notifications/log_subscriber.rb', line 71

def event(command, runtime: true, &block)
  define_method command do |event|
    self.class.runtime += event.duration if runtime
    instance_exec(event, &block) if block
  end
end

.reset_runtimeObject

Reset aggregated runtime

Returns:

  • Numeric previous runtime value



54
55
56
57
58
# File 'lib/sweet_notifications/log_subscriber.rb', line 54

def reset_runtime
  rt = runtime
  self.runtime = 0
  rt
end

.runtimeObject

Fetch aggregated runtime form request specific store



47
48
49
# File 'lib/sweet_notifications/log_subscriber.rb', line 47

def runtime
  RequestStore.store["#{@name}_runtime"] || 0
end

.runtime=(value) ⇒ Object

Store aggregated runtime form request specific store



42
43
44
# File 'lib/sweet_notifications/log_subscriber.rb', line 42

def runtime=(value)
  RequestStore.store["#{@name}_runtime"] = value
end

Instance Method Details

#message(event, label, body) ⇒ String

Format a message for logging

Examples

event :test do |event|
  message(event, 'Test', 'message body')
end
# => "  Test (0.00ms)  message body"

Parameters:

  • event (ActiveSupport::Notifications::Event)

    subscribed event

  • label (String)

    label for log messages

  • body (String)

    the rest

Returns:

  • (String)

    formatted message for logging



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/sweet_notifications/log_subscriber.rb', line 28

def message(event, label, body)
  @odd = !@odd
  label_color = @odd ? odd_color : even_color

  format(
    '  %s (%.2fms)  %s',
    color(label, label_color, true),
    event.duration,
    color(body, nil, !@odd)
  )
end