Awstats Sparklines

Share on FriendFeed
Posted by marco
Mon, 16 Apr 2007 17:06:00 GMT

Today I’m playing with awstats and sparklines. The image on the right sidebar, awstats sparklines, shows the daily hits of this website for the last 28 days: the green area shows the hits above the average, the grey one shows the hits below the average.

The image is generated by the following script: you should have awstats properly configured for running it, and replace the right paths in the script; you should also install the ‘sparklines’ ruby gem. To retrieve the last 28 days of data, the script has to read two files of statistics saved by awstats, the file of the current month, and the file of the previous one. You can also download the script here: spark.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/ruby
# Copyleft MFD (http://people.equars.com/~marco/)
# License GPLv2

require 'rubygems'
require 'sparklines'
require 'date'

AWConfig = 'people'

def scale(ar)
   min, max = ar.min, ar.max
   ar.collect {|x| (x - min) / (max-min) * 100 }
end

def average(ar)
   ar.inject(0) {|sum, elem| sum += elem } / ar.length.to_f
end

datet = DateTime::now
month = datet.month < 10 ? '0' + datet.month.to_s : datet.month.to_s
year = datet.year.to_s
datetp = datet - datet.day - 1
monthp = datetp.month < 10 ? '0' + datetp.month.to_s : datetp.month.to_s
yearp = datetp.year.to_s

path="/path_to_awstats/awstats_#{AWConfig}/"
files=%W{#{path}awstats#{month}#{year}.#{AWConfig}.txt #{path}awstats#{monthp}#{yearp}.#{AWConfig}.txt}

hits=[]
files.each { |f| 
   switch=false
   File.open("#{f}").each { |line|
       if line =~ /BEGIN_DAY\s+\d+/
          switch=true
          next
       end
       switch=false if line =~ /END_DAY/
       if(switch) 
         dayhits = /\d{4}\d{2}\d{2}\s+(\d+)\s+(\d+)/.match(line)[2]
         hits << dayhits.to_f
       end
   }
}
scaled =  scale(hits[0,28])
Sparklines.plot_to_file("/path_to_images/spark_web_#{AWConfig}.png", scaled, :type => 'area',  :height =>28, :upper => average(scaled), :above_color => 'green', :step => 4)
Comments

Leave a response

Comment