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;
};
}
}
####
use strict;
use warnings;
use lib "/home/sho/perl/dev/";
use LogMessages;
sub do_something : _log {
print "I'm doing something.\n";
}
do_something();
####
Invalid CODE attribute: _log at ./demoLogMessages.pl line 6
BEGIN failed--compilation aborted at ./demoLogMessages.pl line 8.
####
Invalid CODE attribute: _log at demoLogMessages.pl line 27
at /usr/lib/perl5/5.8.8/attributes.pm line 65
attributes::import('attributes', 'main', 'CODE(0x926b08c)', '_log') called at demoLogMessages.pl line 27
main::BEGIN() called at demoLogMessages.pl line 29
eval {...} called at demoLogMessages.pl line 29
BEGIN failed--compilation aborted at demoLogMessages.pl line 29.
at demoLogMessages.pl line 29
Debugged program terminated. Use q to quit or R to restart,