As the old adage goes, “You can’t manage what you don’t measure.” While I’ve always used Google Analytics on all my sites, I find it a pain to log in to the site to just see some basic information like page views. It allows you to set up reports that get mailed to you every day, but these are PDFs and basically screen shots of the site. Better, but I just want to see some basic stats for my sites in an email message every morning.
Thankfully, there’s an API for Google Analytics. And if there’s an API there are more than one Ruby libraries for accessing it: garb and gattica. I chose gattica because it looked simpler.
In a few minutes, I had the perfect little script written. Here’s the meat of it:
metrics = ['pageviews']
ga = Gattica.new({:email => 'bbbbbb@gmail.com', :password => 'xxxxxxxx'})
ga.accounts.each do |account|
ga.profile_id = account.profile_id
daydata = ga.get({:start_date => yesterday, :end_date => today, :metrics => metrics})
weekdata = ga.get({:start_date => week, :end_date => today, :metrics => metrics})
monthdata = ga.get({:start_date => month, :end_date => today, :metrics => metrics})
data[account.title] = { :day => daydata.points.first.metrics.first[:pageviews],
:week => weekdata.points.first.metrics.first[:pageviews],
:month => monthdata.points.first.metrics.first[:pageviews] }
end
rows = ""
data.keys.sort.each do |site|
puts "#{site}:\t#{data[site][:day]}, #{data[site][:week]}, #{data[site][:month]}"
rows << "<tr><td><b>#{site}</b></td><td>#{data[site][:day]}</td><td>#{data[site][:week]}</td><td>#{data[site][:month]}</td></tr>\n"
end
message = <<MESSAGE_END
From: Robot <info@xxxxxxxx.com>
To: Somebody <somebody@yyyyyyyyy.com>
MIME-Version: 1.0
Content-type: text/html
Subject: Analytics
Site analytics
<table cellpadding="10" cellspacing="0" border="1">
<tr><th>site</th><th>day</th><th>week</th><th>month</th></tr>
#{rows}
</table>
MESSAGE_END
pipe = open("|/usr/sbin/sendmail -t", "w")
pipe.write(message)
pipe.close
I added a cron job and now every morning I get the report I wanted.