rails hash log formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HashFormatter | |
def parse_json(string) | |
JSON.parse(string) | |
rescue | |
nil | |
end | |
def call(severity, timestamp, progname, msg) | |
base_struct = { | |
severity: severity, | |
datetime: timestamp.strftime('%Y-%m-%dT%H:%M:%S%z'), | |
} | |
case msg | |
when ::Hash | |
base_struct.merge!(msg) | |
when ::Array | |
base_struct.merge!(msg.join(', ')) | |
when ::String | |
if (json = parse_json(msg)) | |
base_struct.merge!(json) | |
else | |
base_struct[:message] = msg | |
end | |
else | |
message = msg.respond_to?(:to_json) ? msg.to_json.to_s : msg.to_s | |
base_struct[:message] = message | |
end | |
base_struct | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment