Skip to content

Instantly share code, notes, and snippets.

@jvrplmlmn
Created June 16, 2013 22:13
Show Gist options
  • Select an option

  • Save jvrplmlmn/5793634 to your computer and use it in GitHub Desktop.

Select an option

Save jvrplmlmn/5793634 to your computer and use it in GitHub Desktop.
Perl logger example, using a perl module
#!/usr/bin/perl
use strict;
use warnings;
use Log;
# Autoflush
$| = 1;
# Usage check
if (@ARGV != 1) {
print "Use: $0 <logname>\n";
exit;
}
# Get the logfile
my $LOG_FILE = $ARGV[0];
# Try to open the logfile
(my $res, $_) = Log->start($LOG_FILE);
if ($res) {
print "Error creating log file: $_\n";
}
# Print some stuff
for my $i (1..10){
Log->trace("Msg $i")
}
package Log;
my $filename = '';
sub start {
shift @_;
($filename) = @_;
return (-1, "Filename missing") if (!$filename);
open (F_LOG, ">>$filename") || return (-1, "Error in file $filename: $!");
my $fh = select F_LOG;
# Autoflush
# http://stackoverflow.com/questions/8804220/perl-operator-dollar-sign-pipe-plus-plus
$| = 1;
select $fh;
return 0;
}
sub trace {
shift @_;
my $text = shift @_;
@_ = localtime(time);
# http://perldoc.perl.org/functions/localtime.html
$_[5] += 1900;
$_[4]++;
my $trace = sprintf "[%02d/%02d/%d %02d:%02d:%02d] %s\n", $_[3], $_[4], $_[5], $_[2], $_[1], $_[0], $text;
print F_LOG $trace;
print $trace;
return 0;
}
END {
close F_LOG;
}
# Modules have to return a True value
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment