| 1 | package VUser::Log::File; | ||
| 2 | use warnings; | ||
| 3 | use strict; | ||
| 4 | |||
| 5 | # Copyright 2005 Randy Smith <perlstalker@vuser.org> | ||
| 6 | # $Id: File.pm,v 1.5 2007-07-02 20:00:14 perlstalker Exp $ | ||
| 7 | |||
| 8 | our $VERSION = "0.3.0"; | ||
| 9 | |||
| 10 | use VUser::ExtLib qw(:config); | ||
| 11 | use VUser::Log qw(:levels); | ||
| 12 | our @ISA = qw(VUser::Log); | ||
| 13 | |||
| 14 | use IO::File; | ||
| 15 | |||
| 16 | my $c_sec = 'Log File'; | ||
| 17 | |||
| 18 | my @levels = ('', 'DEBUG', 'INFO', 'NOTICE', 'WARN', | ||
| 19 | 'ERROR', 'CRIT', 'ALERT', 'EMERG'); | ||
| 20 | |||
| 21 | sub init { | ||
| 22 | my $self = shift; | ||
| 23 | my $cfg = shift; | ||
| 24 | |||
| 25 | my $log_file = strip_ws($cfg->{$c_sec}{'log file'}); | ||
| 26 | $self->add_member('log_file', $log_file); | ||
| 27 | |||
| 28 | my $use_timestamp = check_bool($cfg->{$c_sec}{'use timestamp'}); | ||
| 29 | $self->add_member('use_timestamp', $use_timestamp); | ||
| 30 | |||
| 31 | my $fh = new IO::File; | ||
| 32 | if ($fh->open(">> ".$self->log_file)) { | ||
| 33 | $fh->autoflush(1); | ||
| 34 | $self->add_member('fh', $fh); | ||
| 35 | } else { | ||
| 36 | die "Unable to open log file ".$self->log_file.": $!\n"; | ||
| 37 | } | ||
| 38 | } | ||
| 39 | |||
| 40 | sub write_msg { | ||
| 41 | my $self = shift; | ||
| 42 | my ($level, $msg) = @_; | ||
| 43 | |||
| 44 | if (not defined $level) { | ||
| 45 | $level = VUser::Log::LOG_ERR(); | ||
| 46 | } | ||
| 47 | |||
| 48 | my $out = ''; | ||
| 49 | |||
| 50 | if ($self->use_timestamp) { | ||
| 51 | my @now = localtime; | ||
| 52 | $out .= sprintf('%04d-%02d-%02d %02d:%02d:%02d ', | ||
| 53 | $now[5]+1900, | ||
| 54 | $now[4]+1, | ||
| 55 | $now[3], | ||
| 56 | $now[2], | ||
| 57 | $now[1], | ||
| 58 | $now[0]); | ||
| 59 | } | ||
| 60 | |||
| 61 | $out .= sprintf ('%s: %s ', $self->ident, $levels[$level]); | ||
| 62 | $out .= "$msg\n"; | ||
| 63 | |||
| 64 | eval { | ||
| 65 | $self->fh->print($out); | ||
| 66 | #print STDERR "Print: $out"; | ||
| 67 | }; | ||
| 68 | |||
| 69 | if ($@) { | ||
| 70 | #warn "Unable to write to logs. Retrying: $@\n"; | ||
| 71 | # There was a problem printing. Try reopening the file and try again. | ||
| 72 | $self->fh->close(); | ||
| 73 | |||
| 74 | $self->{'fh'} = IO::File->new(); | ||
| 75 | $self->fh->autoflush(1); | ||
| 76 | if ($self->{'fh'}->open('>>'.$self->log_file)) { | ||
| 77 | eval { | ||
| 78 | $self->fh->print($out); | ||
| 79 | }; | ||
| 80 | if ($@) { | ||
| 81 | # We cannot log any more | ||
| 82 | die "Unable to write logs: $@\n"; | ||
| 83 | } | ||
| 84 | } else { | ||
| 85 | die "Unable to write logs. Reopen failed: $@\n"; | ||
| 86 | } | ||
| 87 | } | ||
| 88 | } | ||
| 89 | |||
| 90 | |||
| 91 | 1; | ||
| 92 | |||
| 93 | __END__ |