Last active
August 29, 2015 14:14
-
-
Save nkwhr/49cc13fb4dd237bf75de to your computer and use it in GitHub Desktop.
Custom Logger Example on 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
# 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) |
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
# 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 |
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
# 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