-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathlambda_log_formatter.rb
More file actions
65 lines (51 loc) · 1.7 KB
/
lambda_log_formatter.rb
File metadata and controls
65 lines (51 loc) · 1.7 KB
1
2
3
4
5
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
60
61
62
63
64
65
# frozen_string_literal: true
require 'json'
require 'logger'
class LogFormatter < Logger::Formatter
FORMAT = '%<sev>s, [%<datetime>s #%<process>d] %<severity>5s %<request_id>s -- %<progname>s: %<msg>s'
def call(severity, time, progname, msg)
formatted = FORMAT % {
sev: severity[0..0],
datetime: format_datetime(time),
process: $$,
severity: severity,
request_id: $_global_aws_request_id,
progname: progname,
msg: msg2str(msg)
}
"#{formatted.encode('UTF-8', invalid: :replace, undef: :replace, replace: '�')}\n"
end
end
class JsonLogFormatter < Logger::Formatter
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%6NZ'
def call(severity, time, progname, msg)
payload = {
timestamp: time.utc.strftime(DATETIME_FORMAT),
level: severity,
message: message_for(msg),
requestId: $_global_aws_request_id
}
logger_name = progname.to_s
payload[:logger] = logger_name unless logger_name.empty?
if msg.is_a?(Exception)
payload[:errorType] = msg.class.to_s
payload[:errorMessage] = msg.message
payload[:stackTrace] = msg.backtrace || []
location = location_for(msg)
payload[:location] = location unless location.nil?
end
"#{JSON.generate(payload.compact)}\n"
end
private
def message_for(msg)
return msg.message if msg.is_a?(Exception)
msg2str(msg)
end
def location_for(exception)
first_backtrace_line = exception.backtrace&.first
return nil if first_backtrace_line.nil?
matched = first_backtrace_line.match(/\A(?<file>.+):(?<line>\d+):in [`'](?<method>.+)'\z/)
return "#{matched[:file]}:#{matched[:method]}:#{matched[:line]}" if matched
first_backtrace_line
end
end