Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mjgardner
Last active September 15, 2021 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjgardner/9d791244a724daac338aa95c723749db to your computer and use it in GitHub Desktop.
Save mjgardner/9d791244a724daac338aa95c723749db to your computer and use it in GitHub Desktop.
Short Perl script to count weekly hits to a WordPress blog
#!/usr/bin/env perl
use strict;
use warnings;
use Syntax::Construct 'operator-double-diamond';
use Regexp::Log::Common;
use DateTime::Format::HTTP;
use List::Util 1.33 'any';
use Number::Format 'format_number';
my $parser = Regexp::Log::Common->new(
format => ':extended',
capture => [qw<req ts status>],
);
my @fields = $parser->capture;
my $compiled_re = $parser->regexp;
my @skip_uri_patterns = qw<
^/+robots\.txt
[-\w]*sitemap[-\w]*\.xml
^/+wp-
/feed/?$
^/+\?rest_route=
>;
my ( %count, %week_of );
while (<<>>) {
my %log;
@log{@fields} = /$compiled_re/;
# only interested in successful or cached requests
next unless $log{status} =~ /^2/ or $log{status} == 304;
my ( $method, $uri, $protocol ) = split ' ', $log{req};
next unless $method eq 'GET';
next if any { $uri =~ $_ } @skip_uri_patterns;
my $dt = DateTime::Format::HTTP->parse_datetime( $log{ts} );
my $key = sprintf '%u-%02u', $dt->week;
$week_of{$key} ||= $dt->date; # get first date of each week
$count{$key}++;
}
printf "Week of %s: % 10s\n", $week_of{$_}, format_number( $count{$_} )
for sort keys %count;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment