Class: Herbert::AppLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/herbert/AppLogger.rb

Overview

Full-fledged request & response logger with several storage providers (console, mongo, cache)

Class Method Summary collapse

Class Method Details

.log(request, response) ⇒ Object

Creates log message and passes it to stograge provider



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/herbert/AppLogger.rb', line 21

def self.log(request, response)
  log = {
    "request"=> {
      "path"=> request.path,
      "method"=> request.request_method,
      "xhr" => request.xhr?,
      "postData"=> request.POST,
      "query"=> request.GET,
      "headers"=> {},
      "body"=> {
        "isJson"=> request.json?,
        "value"=> request.json? ? request.body : request.body_raw
      },
      "client"=> {
        "ip"=> request.ip,
        "hostname"=> request.host,
        "referer"=> request.referer
      }
    },
    "response"=> {
      "code"=> response.status,
      "headers"=> response.headers,
      "body"=> {
        "isJson"=> response.json?,
        "value"=> response.body
      },
    },
    "meta"=> {
      "dateTime"=> Time.new,
      "processingTime"=> response.app.timer_elapsed.round(3),
      "port" => request.port
    }
  }

  # Extract the headers
  request.env.keys.each do |key|
    if key =~ /^HTTP_/ then
      log['request']['headers'][key.gsub(/^HTTP_/,'')] = request.env[key]
    end
  end
  # do not log bodies from GET/DELETE/HEAD
  log["request"].delete("body") if %{GET DELETE HEAD}.include?(log["request"]["method"])
  # If an error has occured, add it
  log["response"]["error"] = request.env['sinatra.error'].to_hash if request.env['sinatra.error']
  id = @@provider.save(log)
  response['X-RequestId'] = id.to_s if @@provider.respond_to?(:id) && response.app.settings.append_log_id
end

.providerObject

Provider getter



7
8
9
# File 'lib/herbert/AppLogger.rb', line 7

def self.provider
  @@provider
end

.provider=(prov) ⇒ Object

Provider setter



12
13
14
# File 'lib/herbert/AppLogger.rb', line 12

def self.provider=(prov)
  @@provider = prov
end