Tell Me a Story Mommy
Logging Tells a Story
- They allow programmers and sysadmins to examine and recreate events that caused application or system errors.
- Log messages often go hand in hand with defensive coding.
- Especially for error messages, provide enough context (variable values) so that each log message can stand alone and give some clue as to why the input data/arguments caused problems.
#!/usr/bin/perl
package HashFromFile;
# Used for testing and debugging
use Object;
sub make {
&LOG->info("Entering make()");
my ($class, %args) = @_;
# The text file that provides the input for the hash we're going to create
my $file = $args{filename} || undef;
if (defined $file) {
&LOG->debug("Using file: '$file' as data source");
}
else {
&LOG->logdie("Exiting because no file was specified");
}
# Init hash reference that will be populated with data read from $file
my $hash = {};
# Open readonly
open(FH, "< $file")
or &LOG->logdie("Could not open file '$file': $!");
while (my $line = <FH>) {
if ($line =~ /^\s+$/) {
&LOG->debug("Current line was empty, skipping to next line");
next;
}
else {
&LOG->debug("Current line has data: $line");
}
chomp($line);
if ($line !~ /:/) {
&LOG->warn("Current line does not contain required delimiter ':'");
}
# Split each line into a list by the ':' character, only the words
# around the first encountered ':' are used
my ($key, $value) = split(/:/, $line);
&LOG->debug("Adding new entry to hash, key: $key - value: $value");
$hash->{$key} = $value;
}
close(FH);
if (&LOG->is_debug()) {
&LOG->debug(
"Hash before return is: " . Object->as_string(obj => $hash)
);
}
&LOG->info("Exiting make()");
return $hash;
}
1;