|
Log::Logger - OO interface to user defined logfile |
Log::Logger - OO interface to user defined logfile
use Log::Logger;
$lh = new Log::Logger;
$lh->open("/tmp/mylog");
$lh->log("Log this string");
$lh->close();
$lh = new Log::Logger "/tmp/mylog";
$lh->log_print("Log and print this string");
$lh->close();
$lh = new Log::Logger;
$lh->open_append("/tmp/mylog");
$lh->log("Append this string");
$lh->fail("Append this string and die");
# Can't close $lh, because fail exits...
Whenever writing scripts for system management, I always find myself wishing to keep a log of what I have done. But typing
print LOGHANDLE $progname . ": " . $stringToLog . "\n";
every time gets really old. Similarly, die() does not have the
facility to print to a logfile as it exits.
A long time ago, I wrote two functions, log() and fail(), to
handle this problem. I cut and pasted them everywhere. But now that
Perl does modules for object reuse, I have ported them to a module
and added features.
Log::Logger is esentially a wrapper around an IO::File object.
The open and open_append functions just call
IO::File->open()
with the appropriate arguments. The useful functionality is in the
log(), log_print(), and fail() methods. These methods make
logging what you are doing -- and printing to the user, if you like --
one line of code. eg:
# Old way
print STDOUT "$progName: Running /var/clean script...\n";
print LOGHANDLE "$progName: Running /var/clean script...\n";
# Log::Logger way
$lh->log_print("Running /var/clean script...");
And if you wish to log things, but also keep neat die() expressions,
you can. eg:
# Old way no logging
system("foo") == 0 or die "Call to foo failed"
# Old way, hackneyed logging
system("foo") == 0 or do {
print LOGHANDLE, "Call to foo failed";
die "Call to foo failed";
}
# Log::Logger way
system("foo") == 0 or $lh->fail("Call to foo failed");
Obviously, this is not a huge difference, but in a utility where you keep track of a lot of operations, it just is easier, and saves a little bit of typing. Remember, one of the fundamental qualities of a programmer is Laziness (see the Camel book).
Returns FALSE on failure.
exit() to exit the program. If RETCODE is supplied, it exits
with that return code. Otherwise, it exits with a return code of 1.
If no logfile is open, it prints to STDOUT only, and exits.
None that I know of, except maybe this documentation. Probably should
have an error checking return for <new()> with arguments like there
is on open() and open_append().
Joel Becker jlbec@ocala.cs.miami.edu
Copyright (c) 1998 Joel Becker. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Version 1.01 (8 April 1998)
log() and fail() subroutines into a proper Perl
module (this one). Much better than cut-and-paste.
|
Log::Logger - OO interface to user defined logfile |