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'
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
= [
"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 << }
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
|