First of all, you really should specify the mode you want Perl to open your file with. So:
open LOG, "<", $logfile or die "Cannot open $logfile for read: $!";
Secondly, the reason you're getting multiple buttons is because as you go over each line in your log file, you're printing out either a red button, a yellow button or whatever the previous value of $button was.
Do you want coloured buttons for every line in your file? Or do you want one just for the last line? Alternately, do you want to have one button representing the biggest problem? As in, if there was something that signalled a "red" button and a "yellow" button that you only get one red one?
I'm going to assume that you want the latter. So that if all the lines in the file look boring, you get 1 green button. If any of them are worth warnings, you get a yellow, and if any are red, you get a red; but in all cases you only get one button. I'm also going to assume that you only need to print the header out once, and that you will always print it.
use strict;
use warnings;
# Create some constants
my $logfile = "log.txt";
my $error = "DOWN";
my $warn = "PROBLEM";
my ($GREEN, $YELLOW, $RED) = (0, 1, 2);
my $greenbutton = "\<img src\=\'default_files/perlgreenblink\.gif'>";
my $yellowbutton = "\<img src\=\'default_files/perlyellowblink\.gif'>"
+;
my $redbutton = "\<img src\=\'default_files/perlredblink\.gif'>";
my @buttons = ($greenbutton, $yellowbutton, $redbutton);
open LOG, "<", $logfile or die "Cannot open $logfile for read :$!";
# If there aren't any log entries, it is probably green.
my $severity = $GREEN;
# Read each line and record the highest severity
while ( <LOG> ) {
# If it's red, we might as well stop looking as it's
# not going to get any better
if ( $_ =~ /$error/i ) {
$severity = $RED;
last;
}
# If it's a warning, move up to yellow
elsif ( $_ =~ /$warn/i ) {
# next if $severity > $YELLOW; # needed if no last above
$severity = $YELLOW;
}
# It's only green if it was already green.
else {
next if $severity > $GREEN;
$severity = $GREEN;
}
}
close LOG;
# Print out our button
print "<!--Content-type: text/html-->\n\n";
print $buttons[$severity], "\n";
A flaw with this approach is that as time moves on, red buttons may not longer mean anything. For example, if the log file contains data from 2 days ago, then a "DOWN" back then has probably been resolved now. As such, you may find it useful to have a look at Log::Tail to allow you to tail log events on live logs, and to record when the red and yellow events happen so that you can reduce their severity over time.
Such a program will be much more complicated than this though.
I hope this helps.
|