Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
rails hash log formatter
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