package LogMessages; use strict; use warnings; use Attribute::Handlers; our @ISA=qw/Exporter/; use constant DEBUG => 1; our @EXPORT=qw/ _log /; sub new{ my $invocant=shift; my $class=ref($invocant) || $invocant; my $randomFileName=rand; print "Logging execution to $randomFileName\n"; my $self={ logfile=>$randomFileName, @_ # Override the default value. }; bless($self, $class); print "Logging execution to $self->{logfile}\n"; return $self; } sub getLogTime{ my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); my @weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun); my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime(); my $year = 1900 + $yearOffset; my $time = "$hour:$minute:$second, $weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year"; return $time; } sub log_message{ my $self=shift; open(LOGFILE, ">>$self->{logfile}") or die "Cannot open logfile"; my $time=getLogTime(); print LOGFILE $time, " "; for (@_){ print LOGFILE @_; } } sub _log : ATTR(CODE) { # CODE means the attrib applies only to subroutines. my ($pkg, $sym, $code) = @_; # pkg in which the subroutine was compiled. # reference to the typeglob where its symbol lives. # reference to subroutine itself. if( DEBUG ) { my $name = *{ $sym }{NAME}; no warnings 'redefine'; # Turn off symbol redefinitions within the block. *{ $sym } = sub { log_message("Entering sub $pkg\:\:$name\n"); my @ret = $code->( @_ ); log_message("Leaving sub $pkg\:\:$name\n"); return @ret; }; } }