Class: Appydays::Loggable::HTTPartyFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/appydays/loggable/httparty_formatter.rb

Overview

Formatter that sends structred log information to HTTParty. After requiring this module, use ‘HTTParty.<method>(…, logger: semantic_logger, log_format: :appydays)` to write out a nice structured log. You can also subclass this formatter to use your own message (default to httparty_request), and modify the fields (override #fields).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger, level) ⇒ HTTPartyFormatter

Returns a new instance of HTTPartyFormatter.



15
16
17
18
19
# File 'lib/appydays/loggable/httparty_formatter.rb', line 15

def initialize(logger, level)
  @logger = logger
  @level  = level.to_sym
  @message = "httparty_request"
end

Instance Attribute Details

#levelObject

Returns the value of attribute level.



12
13
14
# File 'lib/appydays/loggable/httparty_formatter.rb', line 12

def level
  @level
end

#loggerObject

Returns the value of attribute logger.



12
13
14
# File 'lib/appydays/loggable/httparty_formatter.rb', line 12

def logger
  @logger
end

#messageObject

Returns the value of attribute message.



12
13
14
# File 'lib/appydays/loggable/httparty_formatter.rb', line 12

def message
  @message
end

#requestObject (readonly)

Returns the value of attribute request.



13
14
15
# File 'lib/appydays/loggable/httparty_formatter.rb', line 13

def request
  @request
end

#responseObject (readonly)

Returns the value of attribute response.



13
14
15
# File 'lib/appydays/loggable/httparty_formatter.rb', line 13

def response
  @response
end

Instance Method Details

#content_lengthObject



44
45
46
# File 'lib/appydays/loggable/httparty_formatter.rb', line 44

def content_length
  @content_length ||= response.respond_to?(:headers) ? response.headers["Content-Length"] : response["Content-Length"]
end

#fieldsObject



27
28
29
30
31
32
33
34
# File 'lib/appydays/loggable/httparty_formatter.rb', line 27

def fields
  return {
    "content_length" => content_length || "-",
    "http_method" => http_method,
    "path" => path,
    "response_code" => response.code,
  }
end

#format(request, response) ⇒ Object



21
22
23
24
25
# File 'lib/appydays/loggable/httparty_formatter.rb', line 21

def format(request, response)
  @request = request
  @response = response
  self.logger.public_send(self.level, self.message, **self.fields)
end

#http_methodObject



36
37
38
# File 'lib/appydays/loggable/httparty_formatter.rb', line 36

def http_method
  @http_method ||= request.http_method.name.split("::").last.upcase
end

#pathObject



40
41
42
# File 'lib/appydays/loggable/httparty_formatter.rb', line 40

def path
  @path ||= request.path.to_s
end