package Logger; $VERSION = 1.00; use strict; use vars qw( $AUTOLOAD ); use Data::Dumper; use Carp; { #Encapsulated class data my %_log_attr = # DEFAULT ACCESSIBILITY ( _name => ['DEFAULT', 'read/write'], _handle => [undef, 'read'] ); #is a specirfied object attribute accessible in a given mode sub _accessible { my ($self, $attr, $mode) = @_; $_log_attr{$attr}[1] =~ /$mode/ } # Classwide default value for a specified object attributes sub _default_for { my ($self, $attr) = @_; $_log_attr{$attr}[2]; } # list of names of all specified object attributes sub _standard_keys { keys %_log_attr; } # return datestamp sub _date { my @date=localtime; ++$date[4]; if (length($date[3])eq 1 ) {$date[3]='0'.$date[3]}; if (length($date[4])eq 1 ) {$date[4]='0'.$date[4]}; $date[5]=$date[5]+1900; return($date[3].$date[4].$date[5],"$date[3]-$date[4]-$date[5]"); } # return timestamp sub _time { my @time=localtime; ++$time[4]; if (length($time[2])eq 1 ) {$time[2]='0'.$time[2]}; if (length($time[1])eq 1 ) {$time[1]='0'.$time[1]}; return($time[2].$time[1].$time[0],"$time[2]:$time[1]:$time[0]"); } } sub new { my ($caller, %arg) = @_; my $caller_is_obj = ref($caller); my $class = $caller_is_obj || $caller; my $self = bless {}, $class; foreach my $attrname ($self->_standard_keys() ) { my ($argname) = ($attrname =~ /^_(.*)/); if (exists $arg{$argname}) { $self->{$attrname} = $arg{$argname} ; } elsif ($caller_is_obj) { $self->{$attrname} = $caller->{$argname}; } else { $self->{$attrname} = $self->_default_for($attrname) } } $self->{_handle}=&prepare_file($self); return $self; } sub prepare_file { my $self = shift; if ($self->{_name}) { if ($self->{_name} =~ /^[\w\.]+$/) { my @ds = $self->_date(); my $name = '>>'.$self->{_name}.'.'.$ds[0].'.log'; local*LOGFILE; open(LOGFILE, $name) || carp "Unable to open file: $!"; return *LOGFILE; } else { carp "You may only use alphanumerics, dot <.> and underscore <_> in names.\n"; return undef; } } } sub log { my ($self, $location, $message) = @_; if ($self->{_handle}) { print {$self->{_handle}} $self->_date().' '.$self->_time().", $$, $location, $message\n"; } else { carp "Must call logger->new(name=>'') before writing log.\n"; } } 1