Skip to content

Instantly share code, notes, and snippets.

@nkwhr
Last active August 29, 2015 14:14
Show Gist options
  • Save nkwhr/49cc13fb4dd237bf75de to your computer and use it in GitHub Desktop.
Save nkwhr/49cc13fb4dd237bf75de to your computer and use it in GitHub Desktop.
Custom Logger Example on Rails
# lib/activity_logger.rb
class ActivityLogger < Logger
def format_message(severity, timestamp, progname, msg)
base_log = {
timestamp: timestamp,
severity: severity
}
base_log.merge(msg).to_json + "\n"
end
end
logfile = File.open("#{Rails.root}/log/activity.log", 'a')
logfile.sync = true
ACTIVITY_LOGGER = ActivityLogger.new(logfile)
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :log_activity
private
def log_activity
ACTIVITY_LOGGER.info(
session_id: session.id,
user_id: session[:id],
status: response.status,
remote_ip: request.remote_ip,
method: request.method,
path: request.path,
query_string: request.query_string,
url: request.url,
user_agent: request.user_agent,
body: request.body
)
end
end
# config/initializers/autoloads.rb
require './lib/activity_logger'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment