Skip to content

Instantly share code, notes, and snippets.

@knowuh
Created March 8, 2012 21:10
Show Gist options
  • Save knowuh/2003471 to your computer and use it in GitHub Desktop.
Save knowuh/2003471 to your computer and use it in GitHub Desktop.
Parses rails logs, and tries to 'guess' the current user for various requests
@loginfile = "rites.log"
#
# Parses rails logs, and tries to 'guess' the current user for various requests based on
# context (file position) and IP address. Its probably wrong quite often.
# assumes that some of the rails logs lines match this general format:
#
# Processing SessionsController#create (for 158.123.187.120 at 2012-03-02 15:46:33) [POST]
# Parameters: {"action"=>"create", "controller"=>"sessions", "login"=>"cdibiasio", "password"=>"[FILTERED]"}
# Failed login for 'cdibiasio' from 158.123.187.120 at Fri Mar 02 20:46:33 UTC 2012
# Rendering template within layouts/application
@rgx_ip_and_timestamp = /(\d+\.\d+\.\d+\.\d+) at (\d{4}-\d{2}-\d{2} \d{2}:\d{2}\:\d{2})/
@rgx_login = /"login"=>"([^"]*)"/
# looking for this particular route:
@rgx_report = /\/portal\/(offerings|learners)\/(.\d+)\/report/
lines = File.read(@loginfile)
index = 0
@records = []
@users = {}
@users_by_ip = {}
ip_address = nil
login = nil
record_type = nil
date = nil
lines.each do |line|
m = @rgx_ip_and_timestamp.match(line)
if m
ip_address = m[1]
date = m[2]
next
end
login = @users_by_ip[ip_address]
m = @rgx_login.match(line)
if m
login = m[1]
@users[login] ||= {:ip_addresses => [], :dates => []}
@users[login][:ip_addresses].push(ip_address).uniq!
@users[login][:dates].push(date).uniq!
@users_by_ip[ip_address] = login
@records.push({
:record_type => "login",
:login => login,
:ip_address => ip_address,
:date => date,
:id => "(none)"
})
next
end
m = @rgx_report.match(line)
if m
@records.push({
:record_type => "report_#{m[1]}",
:login => login,
:ip_address => ip_address,
:date => date,
:id => m[2]
})
next
end
end
@records.each do |record|
puts "#{record[:date]}, #{record[:record_type]}, #{record[:login]}, #{record[:ip_address]}, #{record[:id]}"
end
# sorted_users = @users.keys.sort
# sorted_users.each do |user|
# puts "#{user}, #{@users[user][:dates].size}, #{@users[user][:dates].first}, #{@users[user][:dates].last}"
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment