Skip to content

Instantly share code, notes, and snippets.

@stevenocchipinti
Created May 14, 2015 14:14
Show Gist options
  • Save stevenocchipinti/460bf7ccb28e305e66d7 to your computer and use it in GitHub Desktop.
Save stevenocchipinti/460bf7ccb28e305e66d7 to your computer and use it in GitHub Desktop.
Logging in JSON with Ruby/Rails
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: "abc@def.com",
# )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment