Class: Modulorails::LogsForMethodService

Inherits:
BaseService show all
Defined in:
lib/modulorails/services/logs_for_method_service.rb

Overview

A service to write formatted debug logs from a method.

Author:

  • Matthieu CIAPPARA <ciappa_m@modulotech.fr>

Instance Method Summary collapse

Methods inherited from BaseService

call, pluralize, #to_s, #to_tag

Constructor Details

#initialize(method:, message:, tags: []) ⇒ LogsForMethodService

Returns a new instance of LogsForMethodService.

Parameters:

  • method (String)

    The name of the calling method

  • message (String, #to_json)

    The body of the log.

  • tags (Array<String,#to_tag>) (defaults to: [])

    A list of tags to prefix the log.



8
9
10
11
12
13
# File 'lib/modulorails/services/logs_for_method_service.rb', line 8

def initialize(method:, message:, tags: [])
  super()
  @method  = method
  @message = message
  @tags    = tags
end

Instance Method Details

#callObject

Write a formatted debug log using given initialization parameters



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
# File 'lib/modulorails/services/logs_for_method_service.rb', line 16

def call
  ActiveSupport::Deprecation.warn(<<~MESSAGE)
    Modulorails::LogsForMethodService is deprecated and will be removed with version 2.0.
    Use Rails.logger.debug directly with objects instead.
  MESSAGE

  # Map the tags (either objects responding to #to_tag or strings) to prefix the log body
  tag_strings = @tags.map do |tag|
    tag.respond_to?(:to_tag) ? "[#{tag.to_tag}]" : "[#{tag}]"
  end

  # If the message respond_to #to_json (and is not a String), use it.
  @message = jsonify if !@message.is_a?(String) && @message.respond_to?(:to_json)

  # Join the tags
  tag_string = tag_strings.join

  # Split on newlines to avoid a log of a thousand columns and for each line, prefix the tags
  # and log it as debug.
  @message.split("\n").each do |line|
    msg = "#{tag_string}[#{@method}] #{line}"

    Rails.logger.debug(msg)
  end
end