Class: ApiHitLogger::CsvLogger

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

Class Method Summary collapse

Class Method Details

.log(request:, status:, start_time:, end_time:, error: nil) ⇒ Object



6
7
8
9
10
11
12
13
14
15
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/csv_logger.rb', line 6

def self.log(request:, status:, start_time:, end_time:, error: nil)
  date = Time.now.utc.strftime("%Y-%m-%d")
  file_path = File.join(Rails.root.to_s, "log", "api_hit_logs_#{date}.csv")
  FileUtils.mkdir_p(File.dirname(file_path))

  duration = "#{(end_time - start_time).round(3)}s"
  timestamp = Time.now.utc

  ip_address = request.ip
  ip_address = '127.0.0.1' if ip_address == '::1'

  # Safely extract parameters
  params_json = begin
    if request.form_data?
      request.POST.to_json
    else
      request.body.rewind
      JSON.parse(request.body.read).to_json rescue "{}"
    end
  rescue
    "{}"
  ensure
    request.body.rewind
  end

  headers = [
    "id", "method", "path", "ip_address", "params",
    "status", "start_time", "end_time", "duration", "error",
    "created_at", "updated_at"
  ]

  unless File.exist?(file_path)
    CSV.open(file_path, "w") { |csv| csv << headers }
  end

  id = next_id(file_path)

  CSV.open(file_path, "a") do |csv|
    csv << [
      id,
      request.request_method,
      request.path,
      ip_address,
      params_json,
      status,
      start_time,
      end_time,
      duration,
      error,
      timestamp,
      timestamp
    ]
  end
end

.next_id(file_path) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/csv_logger.rb', line 61

def self.next_id(file_path)
  return 1 unless File.exist?(file_path)

  lines = File.readlines(file_path)
              .map(&:strip)
              .reject(&:empty?)

  return 1 if lines.size <= 1

  begin
    last_id = lines.last.split(",").first.to_i
    last_id + 1
  rescue StandardError
    1
  end
end