TExcelTAD
Home › Perl › Mini Project: Log Report

Mini Project: Log Report

In this project you will build a log report generator, the kind of script Perl was invented for. It reads an application log, parses every line with a regular expression, skips garbage, aggregates the data in hashes, and prints a formatted daily report with statistics and alerts.

It brings together much of the course: named captures and /x, hashes of arrays, map/grep/sort, List::Util, sprintf, here-docs and the __DATA__ section.

The log looks like this. Each line has a timestamp, a level, a service name, a message and a response time in milliseconds:

text
2024-05-01T09:17:20 WARN  api     slow query on /orders ms=950
2024-05-01T09:41:07 ERROR db      connection refused ms=3000

Because the playground has no files, every step keeps the log in a __DATA__ section. In a real script you would read it with while (my $line = <>) from a file named on the command line.

Step 1: Parse one line

Start with a single function that turns a line into a hash reference, or returns nothing for a line it doesn't understand. The /x modifier lets us lay out the pattern with spaces, and named captures give every field a name. %+ holds all the named captures, so { %+ } copies them into a new anonymous hash.

perl · try it yourself
use strict;
use warnings;

sub parse_line {
    my ($line) = @_;
    return unless $line =~ m{
        ^ (?<date>\d{4}-\d\d-\d\d) T (?<hour>\d\d) : \d\d : \d\d \s+
          (?<level>INFO|WARN|ERROR) \s+
          (?<service>\w+) \s+
          (?<message>.*?) \s+
          ms=(?<ms>\d+) $
    }x;
    return { %+ };
}

my $sample = "2024-05-01T09:17:20 WARN  api     slow query on /orders ms=950";
my $entry = parse_line($sample);
print "$_ => $entry->{$_}\n" for sort keys %$entry;

my $bad = parse_line("corrupted line ###");
print "Bad line parsed? ", (defined $bad ? "yes" : "no"), "\n";
date => 2024-05-01
hour => 09
level => WARN
message => slow query on /orders
ms => 950
service => api
Bad line parsed? no

Returning an empty list with a bare return for malformed lines lets callers write if (my $e = parse_line($line)).

Step 2: Read the whole log

Now loop over the __DATA__ lines, keep the entries that parse, and count the ones that don't. A first, simple aggregation counts entries per level:

perl · try it yourself
use strict;
use warnings;

sub parse_line {
    my ($line) = @_;
    return unless $line =~ m{
        ^ (?<date>\d{4}-\d\d-\d\d) T (?<hour>\d\d) : \d\d : \d\d \s+
          (?<level>INFO|WARN|ERROR) \s+
          (?<service>\w+) \s+
          (?<message>.*?) \s+
          ms=(?<ms>\d+) $
    }x;
    return { %+ };
}

my (@entries, $skipped);
while (my $line = <DATA>) {
    chomp $line;
    next if $line =~ /^\s*$/;
    if (my $e = parse_line($line)) {
        push @entries, $e;
    } else {
        $skipped++;
    }
}

my %by_level;
$by_level{ $_->{level} }++ for @entries;

printf "Parsed %d entries, skipped %d\n", scalar(@entries), $skipped // 0;
printf "%-5s %d\n", $_, $by_level{$_} for sort keys %by_level;

__DATA__
2024-05-01T09:02:11 INFO  auth    login ok user=ana ms=120
2024-05-01T09:05:43 INFO  api     GET /orders ms=85
2024-05-01T09:17:20 WARN  api     slow query on /orders ms=950
2024-05-01T09:41:07 ERROR db      connection refused ms=3000
2024-05-01T10:03:55 INFO  auth    login ok user=ben ms=110
corrupted line ### 
2024-05-01T10:12:30 INFO  api     GET /products ms=60
2024-05-01T10:30:02 ERROR api     upstream timeout ms=5000
2024-05-01T10:44:19 INFO  api     GET /orders ms=95
2024-05-01T11:08:41 WARN  auth    password retry user=cleo ms=140
2024-05-01T11:15:00 ERROR db      connection refused ms=3000
2024-05-01T11:59:59 INFO  api     GET /health ms=5
Parsed 11 entries, skipped 1
ERROR 3
INFO  6
WARN  2

$skipped // 0 protects against printing undef when the log is perfectly clean.

Step 3: Statistics per service

Next we group response times per service in a hash of arrays, using autovivification with push @{ $times{...} }, and count errors with a second hash. The read loop is compressed into one grep/map line here: read all lines, chomp and parse each, keep the defined results.

perl · try it yourself
use strict;
use warnings;
use List::Util qw(sum max);

sub parse_line {
    my ($line) = @_;
    return unless $line =~ m{
        ^ (?<date>\d{4}-\d\d-\d\d) T (?<hour>\d\d) : \d\d : \d\d \s+
          (?<level>INFO|WARN|ERROR) \s+
          (?<service>\w+) \s+
          (?<message>.*?) \s+
          ms=(?<ms>\d+) $
    }x;
    return { %+ };
}

my @entries = grep { defined } map { chomp; parse_line($_) } <DATA>;

# Errors per service
my %errors;
$errors{ $_->{service} }++ for grep { $_->{level} eq 'ERROR' } @entries;

# Response times per service
my %times;
push @{ $times{ $_->{service} } }, $_->{ms} for @entries;

for my $svc (sort keys %times) {
    my @ms = @{ $times{$svc} };
    printf "%-5s requests=%d avg=%.1fms max=%dms errors=%d\n",
        $svc, scalar(@ms), sum(@ms) / @ms, max(@ms), $errors{$svc} // 0;
}

__DATA__
2024-05-01T09:02:11 INFO  auth    login ok user=ana ms=120
2024-05-01T09:05:43 INFO  api     GET /orders ms=85
2024-05-01T09:17:20 WARN  api     slow query on /orders ms=950
2024-05-01T09:41:07 ERROR db      connection refused ms=3000
2024-05-01T10:03:55 INFO  auth    login ok user=ben ms=110
corrupted line ### 
2024-05-01T10:12:30 INFO  api     GET /products ms=60
2024-05-01T10:30:02 ERROR api     upstream timeout ms=5000
2024-05-01T10:44:19 INFO  api     GET /orders ms=95
2024-05-01T11:08:41 WARN  auth    password retry user=cleo ms=140
2024-05-01T11:15:00 ERROR db      connection refused ms=3000
2024-05-01T11:59:59 INFO  api     GET /health ms=5
api   requests=6 avg=1032.5ms max=5000ms errors=1
auth  requests=3 avg=123.3ms max=140ms errors=0
db    requests=2 avg=3000.0ms max=3000ms errors=2

sum(@ms) / @ms divides by the array in scalar context, which is its length.

Step 4: Activity per hour

A hash of hashes keyed by hour and level gives a timeline. A text "bar chart" made with the x repetition operator shows the mix of levels at a glance:

perl · try it yourself
use strict;
use warnings;

sub parse_line {
    my ($line) = @_;
    return unless $line =~ m{
        ^ (?<date>\d{4}-\d\d-\d\d) T (?<hour>\d\d) : \d\d : \d\d \s+
          (?<level>INFO|WARN|ERROR) \s+
          (?<service>\w+) \s+
          (?<message>.*?) \s+
          ms=(?<ms>\d+) $
    }x;
    return { %+ };
}

my @entries = grep { defined } map { chomp; parse_line($_) } <DATA>;

my %per_hour;
$per_hour{ $_->{hour} }{ $_->{level} }++ for @entries;

print "Hour  Total  Activity\n";
for my $hour (sort keys %per_hour) {
    my $levels = $per_hour{$hour};
    my $total = 0;
    $total += $_ for values %$levels;
    my $bar = ("#" x ($levels->{INFO} // 0)) . ("!" x ($levels->{WARN} // 0)) . ("X" x ($levels->{ERROR} // 0));
    printf "%s:00 %5d  %s\n", $hour, $total, $bar;
}
print "Legend: # info, ! warning, X error\n";

__DATA__
2024-05-01T09:02:11 INFO  auth    login ok user=ana ms=120
2024-05-01T09:05:43 INFO  api     GET /orders ms=85
2024-05-01T09:17:20 WARN  api     slow query on /orders ms=950
2024-05-01T09:41:07 ERROR db      connection refused ms=3000
2024-05-01T10:03:55 INFO  auth    login ok user=ben ms=110
corrupted line ### 
2024-05-01T10:12:30 INFO  api     GET /products ms=60
2024-05-01T10:30:02 ERROR api     upstream timeout ms=5000
2024-05-01T10:44:19 INFO  api     GET /orders ms=95
2024-05-01T11:08:41 WARN  auth    password retry user=cleo ms=140
2024-05-01T11:15:00 ERROR db      connection refused ms=3000
2024-05-01T11:59:59 INFO  api     GET /health ms=5
Hour  Total  Activity
09:00     4  ##!X
10:00     4  ###X
11:00     3  #!X
Legend: # info, ! warning, X error

Step 5: The complete report

Finally, put it all together with a small configuration hash, a percentile helper, a here-doc template and alerting. This is the complete program:

perl · try it yourself
use strict;
use warnings;
use List::Util qw(sum max);
use POSIX qw(ceil);

my %config = (slow_ms => 900, error_alert => 2, top_n => 2);

sub parse_line {
    my ($line) = @_;
    return unless $line =~ m{
        ^ (?<date>\d{4}-\d\d-\d\d) T (?<hour>\d\d) : \d\d : \d\d \s+
          (?<level>INFO|WARN|ERROR) \s+
          (?<service>\w+) \s+
          (?<message>.*?) \s+
          ms=(?<ms>\d+) $
    }x;
    return { %+ };
}

sub percentile {
    my ($p, @values) = @_;
    my @sorted = sort { $a <=> $b } @values;
    return $sorted[ ceil($p / 100 * @sorted) - 1 ];
}

# ---- read and parse ----
my (@entries, $skipped);
while (my $line = <DATA>) {
    chomp $line;
    if (my $e = parse_line($line)) { push @entries, $e } else { $skipped++ }
}

# ---- aggregate ----
my (%level, %errors, %times, %error_msgs);
for my $e (@entries) {
    $level{ $e->{level} }++;
    push @{ $times{ $e->{service} } }, $e->{ms};
    next unless $e->{level} eq 'ERROR';
    $errors{ $e->{service} }++;
    $error_msgs{ $e->{message} }++;
}
my @all_ms = map { $_->{ms} } @entries;
my @slow   = grep { $_->{ms} >= $config{slow_ms} } @entries;
my @common = (sort { $error_msgs{$b} <=> $error_msgs{$a} || $a cmp $b } keys %error_msgs)[0 .. $config{top_n} - 1];

# ---- report ----
my $date = $entries[0]{date};
my $levels = join ", ", map { "$_ $level{$_}" } sort keys %level;
my $services = join "", map {
    my @ms = @{ $times{$_} };
    sprintf "  %-5s %3d req  avg %7.1f ms  max %5d ms  errors %d\n",
        $_, scalar(@ms), sum(@ms) / @ms, max(@ms), $errors{$_} // 0;
} sort keys %times;

print <<~"REPORT";
    ===== Daily log report: $date =====
    Entries: @{[ scalar @entries ]} (skipped $skipped malformed)
    Levels:  $levels

    Services:
    $services
    Response time: median @{[ percentile(50, @all_ms) ]} ms, p95 @{[ percentile(95, @all_ms) ]} ms
    Slow requests (>= $config{slow_ms} ms): @{[ scalar @slow ]}
    REPORT

print "Most common errors:\n";
printf "  %dx %s\n", $error_msgs{$_}, $_ for grep { defined } @common;

my @alerts = grep { ($errors{$_} // 0) >= $config{error_alert} } sort keys %errors;
print "ALERT: $_ had $errors{$_} errors\n" for @alerts;
print "No alerts.\n" unless @alerts;

__DATA__
2024-05-01T09:02:11 INFO  auth    login ok user=ana ms=120
2024-05-01T09:05:43 INFO  api     GET /orders ms=85
2024-05-01T09:17:20 WARN  api     slow query on /orders ms=950
2024-05-01T09:41:07 ERROR db      connection refused ms=3000
2024-05-01T10:03:55 INFO  auth    login ok user=ben ms=110
corrupted line ### 
2024-05-01T10:12:30 INFO  api     GET /products ms=60
2024-05-01T10:30:02 ERROR api     upstream timeout ms=5000
2024-05-01T10:44:19 INFO  api     GET /orders ms=95
2024-05-01T11:08:41 WARN  auth    password retry user=cleo ms=140
2024-05-01T11:15:00 ERROR db      connection refused ms=3000
2024-05-01T11:59:59 INFO  api     GET /health ms=5
===== Daily log report: 2024-05-01 =====
Entries: 11 (skipped 1 malformed)
Levels:  ERROR 3, INFO 6, WARN 2

Services:
  api     6 req  avg  1032.5 ms  max  5000 ms  errors 1
  auth    3 req  avg   123.3 ms  max   140 ms  errors 0
  db      2 req  avg  3000.0 ms  max  3000 ms  errors 2

Response time: median 120 ms, p95 5000 ms
Slow requests (>= 900 ms): 4
Most common errors:
  2x connection refused
  1x upstream timeout
ALERT: db had 2 errors

How the pieces work:

  • percentile sorts the values numerically and picks the element at position ceil(p/100 * n), the "nearest rank" method. With 11 values, the median is the 6th smallest (120 ms) and p95 is the 11th, the maximum.
  • The services section is built as one string with map + sprintf and then interpolated into the here-doc. The <<~ form strips the indentation of the template lines but not that of interpolated text.
  • @{[ ... ]} evaluates an expression inside the here-doc, such as scalar @entries.
  • Error messages are counted in %error_msgs and sorted by count, then alphabetically, for a stable "top N" list.
  • %config keeps all thresholds in one place, so tuning the report doesn't require touching the logic.

Ideas to extend it

  1. Read real files: replace <DATA> with <> and run perl logreport.pl app.log.
  2. Add command-line options with Getopt::Long (--slow-ms=500 --top=5).
  3. Output JSON with JSON::PP->new->canonical->pretty for other tools to consume.
  4. Track error streaks: alert when the same service fails twice within one hour.
  5. Turn the parser into a LogEntry class with methods like is_error and is_slow.

Test yourself

Why does parse_line use a bare return; for lines that don't match?

  1. It is required by /x
  2. It returns an empty list / undef, so if (my $e = parse_line(...)) is false
  3. It stops the program
  4. It returns 0

What does push @{ $times{$svc} }, $ms; do when $times{$svc} doesn't exist yet?

  1. Dies with an error
  2. Autovivifies a new array reference for that key and pushes onto it
  3. Does nothing
  4. Overwrites the hash

Inside a here-doc, how can you insert the result of scalar @entries?

  1. $scalar(@entries)
  2. @{[ scalar @entries ]}
  3. {scalar @entries}
  4. It is impossible