Skip to content

Instantly share code, notes, and snippets.

Last active September 27, 2023 17:50
Show Gist options
  • Save derwiki/97acb924d62f9828d074 to your computer and use it in GitHub Desktop.
Save derwiki/97acb924d62f9828d074 to your computer and use it in GitHub Desktop.
Ruby module that you can use in a `before_action` on sensitive controllers for which you'd like a usage audit trail

Adding an audit log to your Rails app

If you have any sort of administrative interface on your web site, you can easily imagine an intruder gaining access and mucking about. How do you know the extent of the damage? Adding an audit log to your app is one quick solution. An audit log should record a few things:

  • controller entry points with parameter values
  • permanent information about the user, like user_id
  • transient information about the user, like IP and user_agent

Using the Rails framework, this is as simple as adding a before_action to your admin controllers. Here’s a basic version that I’m using in production.

require 'audit_log'
class AdminController < ApplicationController
include AuditLog
before_action :auto_log
require 'geoip'
module AuditLog
def geoip
@@geoip ||=, '/lib/GeoIPCity.dat'))
def auto_log
rails_action = "#{ params[:controller] }##{ params[:action] }"
rails_params = params.except(:controller, :action)
details = {
:logger => 'AuditLog',
:action => rails_action,
:ip_address => request.remote_ip,
:geo_ip =>,
:user_id => current_user&.id,
:user_email => current_user&.email,
:user_name => current_user&.name,
:params => rails_params,
:user_agent => request.user_agent
} MultiJson.dump(details)
Copy link

nice idea. you could probably dump this in redis (or any other fast in-memory db).

Copy link

Be careful with sensitive information (passwords, etc.).

Copy link

rainchen commented Mar 8, 2016

this module can be defined as a controller concern, then you can move before_action :auto_log in it

Copy link

velobuff commented Mar 9, 2016

👍 for using the lonely operator

Copy link

Awesome, nice trick.

Copy link

Really helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment