Created
May 14, 2015 14:14
-
-
Save stevenocchipinti/460bf7ccb28e305e66d7 to your computer and use it in GitHub Desktop.
Logging in JSON with Ruby/Rails
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
require 'logger' | |
require 'time' | |
require 'json' | |
require 'forwardable' | |
# A simple subclass that writes JSON logs | |
class JsonLogger < Logger | |
def format_message(severity, timestamp, progname, msg) | |
msg = {message: msg} unless msg.is_a? Hash | |
log = {timestamp: timestamp.iso8601, severity: severity}.merge(msg) | |
"#{log.to_json}\n" | |
end | |
end | |
# An example AuditLogger for a Rails app | |
class AuditLogger | |
extend SingleForwardable | |
@logger = JsonLogger.new "#{Rails.root}/log/audit.log" | |
delegate [:debug, :info, :warn, :error, :fatal] => :@logger | |
end | |
# Example usage: | |
# AuditLogger.info( | |
# event: "UserSignedUp", | |
# user: "[email protected]", | |
# ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment