eaiovnaovbqoebvqoeavibavo PKsjZk* ApacheLog.pmnu[package Log::Dispatch::ApacheLog; { $Log::Dispatch::ApacheLog::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch::Output; use base qw( Log::Dispatch::Output ); use Params::Validate qw(validate); Params::Validate::validation_options( allow_extra => 1 ); BEGIN { if ( $ENV{MOD_PERL} && $ENV{MOD_PERL} =~ /2\./ ) { require Apache2::Log; } else { require Apache::Log; } } sub new { my $proto = shift; my $class = ref $proto || $proto; my %p = validate( @_, { apache => { can => 'log' } } ); my $self = bless {}, $class; $self->_basic_init(%p); $self->{apache_log} = $p{apache}->log; return $self; } { my %methods = ( emergency => 'emerg', critical => 'crit', warning => 'warn', ); sub log_message { my $self = shift; my %p = @_; my $level = $self->_level_as_name( $p{level} ); my $method = $methods{$level} || $level; $self->{apache_log}->$method( $p{message} ); } } 1; # ABSTRACT: Object for logging to Apache::Log objects __END__ =pod =head1 NAME Log::Dispatch::ApacheLog - Object for logging to Apache::Log objects =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $log = Log::Dispatch->new( outputs => [ [ 'ApacheLog', apache => $r ], ], ); $log->emerg('Kaboom'); =head1 DESCRIPTION This module allows you to pass messages to Apache's log object, represented by the L class. =head1 CONSTRUCTOR The constructor takes the following parameters in addition to the standard parameters documented in L: =over 4 =item * apache ($) An object of either the L or L classes. Required. =back =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZx%iiEmail/MailSendmail.pmnu[package Log::Dispatch::Email::MailSendmail; { $Log::Dispatch::Email::MailSendmail::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch::Email; use base qw( Log::Dispatch::Email ); use Mail::Sendmail (); sub send_email { my $self = shift; my %p = @_; my %mail = ( To => ( join ',', @{ $self->{to} } ), Subject => $self->{subject}, Message => $p{message}, # Mail::Sendmail insists on having this parameter. From => $self->{from} || 'LogDispatch@foo.bar', ); local $?; unless ( Mail::Sendmail::sendmail(%mail) ) { warn "Error sending mail: $Mail::Sendmail::error"; } } 1; # ABSTRACT: Subclass of Log::Dispatch::Email that uses the Mail::Sendmail module __END__ =pod =head1 NAME Log::Dispatch::Email::MailSendmail - Subclass of Log::Dispatch::Email that uses the Mail::Sendmail module =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $log = Log::Dispatch->new( outputs => [ [ 'Email::MailSendmail', min_level => 'emerg', to => [qw( foo@example.com bar@example.org )], subject => 'Big error!' ] ], ); $log->emerg("Something bad is happening"); =head1 DESCRIPTION This is a subclass of L that implements the send_email method using the L module. =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZ@Email/MIMELite.pmnu[package Log::Dispatch::Email::MIMELite; { $Log::Dispatch::Email::MIMELite::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch::Email; use base qw( Log::Dispatch::Email ); use MIME::Lite; sub send_email { my $self = shift; my %p = @_; my %mail = ( To => ( join ',', @{ $self->{to} } ), Subject => $self->{subject}, Type => 'TEXT', Data => $p{message}, ); $mail{From} = $self->{from} if defined $self->{from}; local $?; unless ( MIME::Lite->new(%mail)->send ) { warn "Error sending mail with MIME::Lite"; } } 1; # ABSTRACT: Subclass of Log::Dispatch::Email that uses the MIME::Lite module __END__ =pod =head1 NAME Log::Dispatch::Email::MIMELite - Subclass of Log::Dispatch::Email that uses the MIME::Lite module =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $log = Log::Dispatch->new( outputs => [ [ 'Email::MIMELite', min_level => 'emerg', to => [qw( foo@example.com bar@example.org )], subject => 'Big error!' ] ], ); $log->emerg("Something bad is happening"); =head1 DESCRIPTION This is a subclass of L that implements the send_email method using the L module. =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZ0 0 Email/MailSender.pmnu[package Log::Dispatch::Email::MailSender; { $Log::Dispatch::Email::MailSender::VERSION = '2.41'; } # By: Joseph Annino # (c) 2002 # Licensed under the same terms as Perl # use strict; use warnings; use Log::Dispatch::Email; use base qw( Log::Dispatch::Email ); use Mail::Sender (); sub new { my $proto = shift; my $class = ref $proto || $proto; my %p = @_; my $smtp = delete $p{smtp} || 'localhost'; my $port = delete $p{port} || '25'; my $self = $class->SUPER::new(%p); $self->{smtp} = $smtp; $self->{port} = $port; return $self; } sub send_email { my $self = shift; my %p = @_; local $?; eval { my $sender = Mail::Sender->new( { from => $self->{from} || 'LogDispatch@foo.bar', replyto => $self->{from} || 'LogDispatch@foo.bar', to => ( join ',', @{ $self->{to} } ), subject => $self->{subject}, smtp => $self->{smtp}, port => $self->{port}, } ); die "Error sending mail ($sender): $Mail::Sender::Error" unless ref $sender; ref $sender->MailMsg( { msg => $p{message} } ) or die "Error sending mail: $Mail::Sender::Error"; }; warn $@ if $@; } 1; # ABSTRACT: Subclass of Log::Dispatch::Email that uses the Mail::Sender module __END__ =pod =head1 NAME Log::Dispatch::Email::MailSender - Subclass of Log::Dispatch::Email that uses the Mail::Sender module =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $log = Log::Dispatch->new( outputs => [ [ 'Email::MailSender', min_level => 'emerg', to => [qw( foo@example.com bar@example.org )], subject => 'Big error!' ] ], ); $log->emerg("Something bad is happening"); =head1 DESCRIPTION This is a subclass of L that implements the send_email method using the L module. =head1 CONSTRUCTOR The constructor takes the following parameters in addition to the parameters documented in L and L: =over 4 =item * smtp ($) The smtp server to connect to. This defaults to "localhost". =item * port ($) The port to use when connecting. This defaults to 25. =back =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZCaCCEmail/MailSend.pmnu[package Log::Dispatch::Email::MailSend; { $Log::Dispatch::Email::MailSend::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch::Email; use base qw( Log::Dispatch::Email ); use Mail::Send; sub send_email { my $self = shift; my %p = @_; my $msg = Mail::Send->new; $msg->to( join ',', @{ $self->{to} } ); $msg->subject( $self->{subject} ); # Does this ever work for this module? $msg->set( 'From', $self->{from} ) if $self->{from}; local $?; eval { my $fh = $msg->open or die "Cannot open handle to mail program"; $fh->print( $p{message} ) or die "Cannot print message to mail program handle"; $fh->close or die "Cannot close handle to mail program"; }; warn $@ if $@; } 1; # ABSTRACT: Subclass of Log::Dispatch::Email that uses the Mail::Send module __END__ =pod =head1 NAME Log::Dispatch::Email::MailSend - Subclass of Log::Dispatch::Email that uses the Mail::Send module =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $log = Log::Dispatch->new( outputs => [ [ 'Email::MailSend', min_level => 'emerg', to => [qw( foo@example.com bar@example.org )], subject => 'Big error!' ] ], ); $log->emerg("Something bad is happening"); =head1 DESCRIPTION This is a subclass of L that implements the send_email method using the L module. =head1 CHANGING HOW MAIL IS SENT Since L is a subclass of L, you can change how mail is sent from this module by simply Cing L in your code before mail is sent. For example, to send mail via smtp, you could do: use Mail::Mailer 'smtp', Server => 'foo.example.com'; For more details, see the L docs. =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZu`BBEmail.pmnu[package Log::Dispatch::Email; { $Log::Dispatch::Email::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch::Output; use base qw( Log::Dispatch::Output ); use Params::Validate qw(validate SCALAR ARRAYREF BOOLEAN); Params::Validate::validation_options( allow_extra => 1 ); # need to untaint this value my ($program) = $0 =~ /(.+)/; sub new { my $proto = shift; my $class = ref $proto || $proto; my %p = validate( @_, { subject => { type => SCALAR, default => "$program: log email" }, to => { type => SCALAR | ARRAYREF }, from => { type => SCALAR, optional => 1 }, buffered => { type => BOOLEAN, default => 1 }, } ); my $self = bless {}, $class; $self->_basic_init(%p); $self->{subject} = $p{subject} || "$0: log email"; $self->{to} = ref $p{to} ? $p{to} : [ $p{to} ]; $self->{from} = $p{from}; # Default to buffered for obvious reasons! $self->{buffered} = $p{buffered}; $self->{buffer} = [] if $self->{buffered}; return $self; } sub log_message { my $self = shift; my %p = @_; if ( $self->{buffered} ) { push @{ $self->{buffer} }, $p{message}; } else { $self->send_email(@_); } } sub send_email { my $self = shift; my $class = ref $self; die "The send_email method must be overridden in the $class subclass"; } sub flush { my $self = shift; if ( $self->{buffered} && @{ $self->{buffer} } ) { my $message = join '', @{ $self->{buffer} }; $self->send_email( message => $message ); $self->{buffer} = []; } } sub DESTROY { my $self = shift; $self->flush; } 1; # ABSTRACT: Base class for objects that send log messages via email __END__ =pod =head1 NAME Log::Dispatch::Email - Base class for objects that send log messages via email =head1 VERSION version 2.41 =head1 SYNOPSIS package Log::Dispatch::Email::MySender; use Log::Dispatch::Email; use base qw( Log::Dispatch::Email ); sub send_email { my $self = shift; my %p = @_; # Send email somehow. Message is in $p{message} } =head1 DESCRIPTION This module should be used as a base class to implement Log::Dispatch::* objects that send their log messages via email. Implementing a subclass simply requires the code shown in the L with a real implementation of the C method. =head1 CONSTRUCTOR The constructor takes the following parameters in addition to the standard parameters documented in L: =over 4 =item * subject ($) The subject of the email messages which are sent. Defaults to "$0: log email" =item * to ($ or \@) Either a string or a list reference of strings containing email addresses. Required. =item * from ($) A string containing an email address. This is optional and may not work with all mail sending methods. =item * buffered (0 or 1) This determines whether the object sends one email per message it is given or whether it stores them up and sends them all at once. The default is to buffer messages. =back =head1 METHODS =over 4 =item * send_email(%p) This is the method that must be subclassed. For now the only parameter in the hash is 'message'. =item * flush If the object is buffered, then this method will call the C method to send the contents of the buffer and then clear the buffer. =item * DESTROY On destruction, the object will call C to send any pending email. =back =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZK0HH Syslog.pmnu[package Log::Dispatch::Syslog; { $Log::Dispatch::Syslog::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch::Output; use base qw( Log::Dispatch::Output ); use Params::Validate qw(validate ARRAYREF SCALAR); Params::Validate::validation_options( allow_extra => 1 ); use Sys::Syslog 0.25 (); sub new { my $proto = shift; my $class = ref $proto || $proto; my %p = @_; my $self = bless {}, $class; $self->_basic_init(%p); $self->_init(%p); return $self; } my ($Ident) = $0 =~ /(.+)/; sub _init { my $self = shift; my %p = validate( @_, { ident => { type => SCALAR, default => $Ident }, logopt => { type => SCALAR, default => '' }, facility => { type => SCALAR, default => 'user' }, socket => { type => SCALAR | ARRAYREF, default => undef }, } ); $self->{ident} = $p{ident}; $self->{logopt} = $p{logopt}; $self->{facility} = $p{facility}; $self->{socket} = $p{socket}; $self->{priorities} = [ 'DEBUG', 'INFO', 'NOTICE', 'WARNING', 'ERR', 'CRIT', 'ALERT', 'EMERG' ]; Sys::Syslog::setlogsock( ref $self->{socket} ? @{ $self->{socket} } : $self->{socket} ) if defined $self->{socket}; } sub log_message { my $self = shift; my %p = @_; my $pri = $self->_level_as_number( $p{level} ); eval { Sys::Syslog::openlog( $self->{ident}, $self->{logopt}, $self->{facility} ); Sys::Syslog::syslog( $self->{priorities}[$pri], $p{message} ); Sys::Syslog::closelog; }; warn $@ if $@ and $^W; } 1; # ABSTRACT: Object for logging to system log. __END__ =pod =head1 NAME Log::Dispatch::Syslog - Object for logging to system log. =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $log = Log::Dispatch->new( outputs => [ [ 'Syslog', min_level => 'info', ident => 'Yadda yadda' ] ] ); $log->emerg("Time to die."); =head1 DESCRIPTION This module provides a simple object for sending messages to the system log (via UNIX syslog calls). Note that logging may fail if you try to pass UTF-8 characters in the log message. If logging fails and warnings are enabled, the error message will be output using Perl's C. =head1 CONSTRUCTOR The constructor takes the following parameters in addition to the standard parameters documented in L: =over 4 =item * ident ($) This string will be prepended to all messages in the system log. Defaults to $0. =item * logopt ($) A string containing the log options (separated by any separator you like). See the openlog(3) and Sys::Syslog docs for more details. Defaults to ''. =item * facility ($) Specifies what type of program is doing the logging to the system log. Valid options are 'auth', 'authpriv', 'cron', 'daemon', 'kern', 'local0' through 'local7', 'mail', 'news', 'syslog', 'user', 'uucp'. Defaults to 'user' =item * socket ($ or \@) Tells what type of socket to use for sending syslog messages. Valid options are listed in C. If you don't provide this, then we let C simply pick one that works, which is the preferred option, as it makes your code more portable. If you pass an array reference, it is dereferenced and passed to C. =back =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZM55 Screen.pmnu[package Log::Dispatch::Screen; { $Log::Dispatch::Screen::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch::Output; use base qw( Log::Dispatch::Output ); use Params::Validate qw(validate BOOLEAN); Params::Validate::validation_options( allow_extra => 1 ); sub new { my $proto = shift; my $class = ref $proto || $proto; my %p = validate( @_, { stderr => { type => BOOLEAN, default => 1 }, } ); my $self = bless {}, $class; $self->_basic_init(%p); $self->{stderr} = exists $p{stderr} ? $p{stderr} : 1; return $self; } sub log_message { my $self = shift; my %p = @_; if ( $self->{stderr} ) { print STDERR $p{message}; } else { print STDOUT $p{message}; } } 1; # ABSTRACT: Object for logging to the screen __END__ =pod =head1 NAME Log::Dispatch::Screen - Object for logging to the screen =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $log = Log::Dispatch->new( outputs => [ [ 'Screen', min_level => 'debug', stderr => 1, newline => 1 ] ], ); $log->alert("I'm searching the city for sci-fi wasabi"); =head1 DESCRIPTION This module provides an object for logging to the screen (really STDOUT or STDERR). Note that a newline will I be added automatically at the end of a message by default. To do that, pass C 1>. =head1 CONSTRUCTOR The constructor takes the following parameters in addition to the standard parameters documented in L: =over 4 =item * stderr (0 or 1) Indicates whether or not logging information should go to STDERR. If false, logging information is printed to STDOUT instead. This defaults to true. =back =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZoFile/Locked.pmnu[package Log::Dispatch::File::Locked; { $Log::Dispatch::File::Locked::VERSION = '2.41'; } use strict; use warnings; use base qw( Log::Dispatch::File ); use Fcntl qw(:DEFAULT :flock); sub _open_file { my $self = shift; $self->SUPER::_open_file(); my $fh = $self->{fh}; flock( $fh, LOCK_EX ) or die "Cannot lock '$self->{filename}' for writing: $!"; # just in case there was an append while we waited for the lock seek( $fh, 0, 2 ) or die "Cannot seek to end of '$self->{filename}': $!"; } 1; # ABSTRACT: Subclass of Log::Dispatch::File to facilitate locking __END__ =pod =head1 NAME Log::Dispatch::File::Locked - Subclass of Log::Dispatch::File to facilitate locking =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $log = Log::Dispatch->new( outputs => [ [ 'File::Locked', min_level => 'info', filename => 'Somefile.log', mode => '>>', newline => 1 ] ], ); $log->emerg("I've fallen and I can't get up"); =head1 DESCRIPTION This module acts exactly like L except that it obtains an exclusive lock on the file while opening it. =head1 CAVEATS B Use very carefully in multi-process environments. Because the lock is obtained at file open time, not at write time, you may experience deadlocks in your system. You can partially work around this by using the C option, which causes the file to be re-opened every time a log message is written. Alternatively, the C option does atomic writes, which may mean that you don't need locking at all. See L) for details on these options. =head1 SEE ALSO L =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZ~jCccCode.pmnu[package Log::Dispatch::Code; { $Log::Dispatch::Code::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch::Output; use base qw( Log::Dispatch::Output ); use Params::Validate qw(validate CODEREF); Params::Validate::validation_options( allow_extra => 1 ); sub new { my $proto = shift; my $class = ref $proto || $proto; my %p = validate( @_, { code => CODEREF } ); my $self = bless {}, $class; $self->_basic_init(%p); $self->{code} = $p{code}; return $self; } sub log_message { my $self = shift; my %p = @_; delete $p{name}; $self->{code}->(%p); } 1; # ABSTRACT: Object for logging to a subroutine reference __END__ =pod =head1 NAME Log::Dispatch::Code - Object for logging to a subroutine reference =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $log = Log::Dispatch->new( outputs => [ [ 'Code', min_level => 'emerg', code => \&_log_it, ], ] ); sub _log_it { my %p = @_; warn $p{message}; } =head1 DESCRIPTION This module supplies a simple object for logging to a subroutine reference. =head1 CONSTRUCTOR The constructor takes the following parameters in addition to the standard parameters documented in L: =over 4 =item * code ($) The subroutine reference. =back =head1 HOW IT WORKS The subroutine you provide will be called with a hash of named arguments. The two arguments are: =over 4 =item * level The log level of the message. This will be a string like "info" or "error". =item * message The message being logged. =back =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZ"X55 Handle.pmnu[package Log::Dispatch::Handle; { $Log::Dispatch::Handle::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch::Output; use base qw( Log::Dispatch::Output ); use Params::Validate qw(validate SCALAR ARRAYREF BOOLEAN); Params::Validate::validation_options( allow_extra => 1 ); sub new { my $proto = shift; my $class = ref $proto || $proto; my %p = validate( @_, { handle => { can => 'print' } } ); my $self = bless {}, $class; $self->_basic_init(%p); $self->{handle} = $p{handle}; return $self; } sub log_message { my $self = shift; my %p = @_; $self->{handle}->print( $p{message} ) or die "Cannot write to handle: $!"; } 1; # ABSTRACT: Object for logging to IO::Handle classes __END__ =pod =head1 NAME Log::Dispatch::Handle - Object for logging to IO::Handle classes =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $log = Log::Dispatch->new( outputs => [ [ 'Handle', min_level => 'emerg', handle => $io_socket_object, ], ] ); $log->emerg('I am the Lizard King!'); =head1 DESCRIPTION This module supplies a very simple object for logging to some sort of handle object. Basically, anything that implements a C method can be passed the object constructor and it should work. =head1 CONSTRUCTOR The constructor takes the following parameters in addition to the standard parameters documented in L: =over 4 =item * handle ($) The handle object. This object must implement a C method. =back =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZg*mBase.pmnu[package Log::Dispatch::Base; { $Log::Dispatch::Base::VERSION = '2.41'; } use strict; use warnings; sub _get_callbacks { shift; my %p = @_; return unless exists $p{callbacks}; return @{ $p{callbacks} } if ref $p{callbacks} eq 'ARRAY'; return $p{callbacks} if ref $p{callbacks} eq 'CODE'; return; } sub _apply_callbacks { my $self = shift; my %p = @_; my $msg = delete $p{message}; foreach my $cb ( @{ $self->{callbacks} } ) { $msg = $cb->( message => $msg, %p ); } return $msg; } sub add_callback { my $self = shift; my $value = shift; Carp::carp("given value $value is not a valid callback") unless ref $value eq 'CODE'; $self->{callbacks} ||= []; push @{ $self->{callbacks} }, $value; return; } 1; # ABSTRACT: Code shared by dispatch and output objects. __END__ =pod =head1 NAME Log::Dispatch::Base - Code shared by dispatch and output objects. =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch::Base; ... @ISA = qw(Log::Dispatch::Base); =head1 DESCRIPTION Unless you are me, you probably don't need to know what this class does. =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZiX1ee FileRotate.pmnu[package Log::Dispatch::FileRotate; require 5.005; use strict; use Log::Dispatch::Output; use base qw( Log::Dispatch::Output ); use Log::Dispatch::File; # We are a wrapper around Log::Dispatch::File use Date::Manip; # For time based recurring rotations use File::Spec; # For file-names use Params::Validate qw(validate SCALAR BOOLEAN); Params::Validate::validation_options( allow_extra => 1 ); use vars qw[ $VERSION ]; $VERSION = sprintf "%d.%02d", q$Revision: 1.19 $ =~ /: (\d+)\.(\d+)/; sub new { my $proto = shift; my $class = ref $proto || $proto; my %p = @_; my $self = bless {}, $class; $self->{'debug'} = 0; $self->_basic_init(%p); $self->{'LDF'} = Log::Dispatch::File->new(%p); # Our log $self->{'timer'} = sub { time() } unless defined $self->{'timer'}; # Keep a copy of interesting stuff as well $self->{params} = \%p; # Turn ON/OFF debugging as required $p{'DEBUG'} ? $self->debug(1) : $self->debug(0); # Size defaults to 10meg in all failure modes, hopefully my $ten_meg = 1024*1024*10; my $two_gig = 1024*1024*1024*2; my $size = $ten_meg; $size = $p{size} if defined $p{size}; $size = $ten_meg unless $size =~ /^\d+$/ && $size < $two_gig && $size > 0; $self->{size} = $size; # Max number of files defaults to 1. No limit enforced here. Only # positive whole numbers allowed $self->{max} = $p{max}; $self->{max} = 1 unless defined $self->{max} && $self->{max} =~ /^\d+$/ && $self->{max} > 0 ; # Get a name for our Lock file my $name = $self->{params}->{filename}; my ($vol, $dir, $f) = File::Spec->splitpath($name); $dir = '.' unless $dir; $f = $name unless $f; my $lockfile = File::Spec->catpath($vol, $dir, ".".$f.".LCK"); warn "Lock file is $lockfile\n" if $self->{'debug'}; $self->{'lf'} = $lockfile; # Have we been called with a time based rotation pattern then setup # timebased stuff. TZ is important and must match current TZ or all # bets are off! if(defined $p{'TZ'}) { Date_Init("TZ=".$p{'TZ'}); # EADT or EAST when not in daylight savings } if(defined $p{'DatePattern'}) { $self->setDatePattern($p{'DatePattern'}); } # Flag this as first creation point $self->{'new'} = 1; return $self; } ########################################################################### # # Subroutine setDatePattern # # Args: a single string or ArrayRef of strings # # Rtns: Nothing # # Description: # Set a recurrance for file rotation. We accept Date::Manip # recurrances and the log4j/DailyRollingFileAppender patterns # # Date:Manip => # 0:0:0:0:5:30:0 every 5 hours and 30 minutes # 0:0:0:2*12:30:0 every 2 days at 12:30 (each day) # 3*1:0:2:12:0:0 every 3 years on Jan 2 at noon # # DailyRollingFileAppender => # yyyy-MM # yyyy-ww # yyyy-MM-dd # yyyy-MM-dd-a # yyyy-MM-dd-HH # yyyy-MM-dd-HH-MM # # To specify multiple recurances in a single string seperate them with a # comma: yyyy-MM-dd,0:0:0:2*12:30:0 # sub setDatePattern { my $self = shift; # My object my($arg) = shift; local($_); # Don't crap on $_ my @pats = (); my %lookup = ( # Y:M:W:D:H:M:S 'yyyy-mm' => '0:1*0:1:0:0:0', # Every Month 'yyyy-ww' => '0:0:1*0:0:0:0', # Every week 'yyyy-dd' => '0:0:0:1*0:0:0', # Every day 'yyyy-mm-dd' => '0:0:0:1*0:0:0', # Every day 'yyyy-dd-a' => '0:0:0:1*12:0:0', # Every day 12noon 'yyyy-mm-dd-a' => '0:0:0:1*12:0:0', # Every day 12noon 'yyyy-dd-hh' => '0:0:0:0:1*0:0', # Every hour 'yyyy-mm-dd-hh' => '0:0:0:0:1*0:0', # Every hour 'yyyy-dd-hh-mm' => '0:0:0:0:0:1*0', # Every minute 'yyyy-mm-dd-hh-mm' => '0:0:0:0:0:1*0', # Every minute ); # Convert arg to array if( ref($arg) eq 'ARRAY' ) { @pats = @$arg; } elsif( !ref($arg) ) { $arg =~ s/\s+//go; @pats = split(/;/,$arg); } else { die "Bad reference type argument ".ref($arg); } # Handle (possibly multiple) recurrances foreach my $pat (@pats) { # Convert any log4j patterns across if($pat =~ /^yyyy/i) # Then log4j style { $pat = lc($pat); # Use lowercase lookup # Default to daily on bad pattern unless(grep($pat eq $_,keys %lookup)) { warn "Bad Rotation pattern ($pat) using yyyy-dd\n"; $pat = 'yyyy-dd'; } $pat = $lookup{$pat}; } my $abs = $self->_get_next_occurance($pat); warn "Adding [dates,pat] =>[$abs,$pat]\n" if $self->{debug}; my $ref = [$abs, $pat]; push(@{$self->{'recurrance'}}, $ref); } } sub log_message { my $self = shift; my %p = @_; my $max_size = $self->{size}; my $numfiles = $self->{max}; my $name = $self->{params}->{filename}; my $fh = $self->{LDF}->{fh}; # Prime our time based data outside the critical code area my ($in_time_mode,$time_to_rotate) = $self->time_to_rotate(); # Handle critical code for logging. No changes if someone else is in if( !$self->lfhlock_test() ) { warn "$$ waiting on lock\n" if $self->{debug}; unless($self->lfhlock()) { warn "$$ failed to get lock. returning\n" if $self->{debug}; return; } warn "$$ got lock after wait\n" if $self->{debug}; } my $size = (stat($fh))[7]; # Stat the handle to get real size my $inode = (stat($fh))[1]; # get real inode my $finode = (stat($name))[1]; # Stat the name for comparision warn localtime()." $$ s=$size, i=$inode, f=". (defined $finode ? $finode : "undef") . ", n=$name\n" if $self->{debug}; # If finode and inode are the same then nobody has done a rename # under us and we can continue. Otherwise just close and reopen. # Time mode overrides Size mode if(!defined($finode) || $inode != $finode) { # Oops someone moved things on us. So just reopen our log delete $self->{LDF}; # Should get rid of current LDF $self->{LDF} = Log::Dispatch::File->new(%{$self->{params}}); # Our log warn localtime()." $$ Someone else rotated: normal log\n" if $self->{debug}; $self->logit($p{message}); } elsif($in_time_mode && !$time_to_rotate) { warn localtime()." $$ In time mode: normal log\n" if $self->{debug}; $self->logit($p{message}); } elsif(!$in_time_mode && defined($size) && $size < $max_size ) { warn localtime()." $$ In size mode: normal log\n" if $self->{debug}; $self->logit($p{message}); } # Need to rotate elsif(($in_time_mode && $time_to_rotate) || (!$in_time_mode && $size) ) { # Shut down the log delete $self->{LDF}; # Should get rid of current LDF my $idx = $numfiles -1; warn localtime() . " $$ Rotating\n" if $self->{debug}; while($idx >= 0) { if($idx <= 0) { warn "$$ rename $name $name.1\n" if $self->{debug}; rename($name, "$name.1"); } else { warn "$$ rename $name.$idx $name.".($idx+1)."\n" if $self->{debug}; rename("$name.$idx", "$name.".($idx+1)); } $idx--; } warn localtime() . " $$ Rotating Done\n" if $self->{debug}; # reopen the logfile for writing. $self->{LDF} = Log::Dispatch::File->new(%{$self->{params}}); # Our log # Write it out warn localtime()." $$ rotated: normal log\n" if $self->{debug}; $self->logit($p{message}); } #else size is zero :-} just don't do anything! $self->lfhunlock(); } sub DESTROY { my $self = shift; if ( $self->{LDF} ) { delete $self->{LDF}; # Should get rid of current LDF } # Clean up locks close $self->{lfh} if $self->{lfh}; unlink $self->{lf} if -f $self->{lf}; } sub logit { my $self = $_[0]; $self->lock(); $self->{LDF}->log_message(message => $_[1]); $self->unlock(); return; } ########################################################################### # # Subroutine time_to_rotate # # Args: none # # Rtns: (1,n) if we are in time mode and its time to rotate # n defines the number of timers that expired # (1,0) if we are in time mode but not ready to rotate # (0,0) otherwise # # Description: # time_to_rotate - update internal clocks and return status as # defined above # # If we have just been created then the first recurrance is an indication # to check against the log file. # # # my ($in_time_mode,$time_to_rotate) = $self->time_to_rotate(); sub time_to_rotate { my $self = shift; # My object my $mode = defined($self->{'recurrance'}); my $rotate = 0; if($mode) { # Then do some checking and update ourselves if we think we need # to rotate. Wether we rotate or not is up to our caller. We # assume they know what they are doing! # Only stat the log file here if we are in our first invocation. my $ftime = 0; if($self->{'new'}) { # Last time the log file was changed $ftime = (stat($self->{LDF}{fh}))[9]; # In Date::Manip format # $ftime = ParseDate(scalar(localtime($ftime))); } # Check need for rotation. Loop through our recurrances looking # for expiration times. Any we find that have expired we update. my $tm = $self->{timer}->(); my @recur = @{$self->{'recurrance'}}; @{$self->{'recurrance'}} = (); for my $rec (@recur) { my ($abs,$pat) = @$rec; # Extra checking unless(defined $abs && $abs) { warn "Bad time found for recurrance pattern $pat: $abs\n"; next; } my $dorotate = 0; # If this is first time through if($self->{'new'}) { # If it needs a rotate then flag it if($ftime <= $abs) { # Then we need to rotate warn "Need rotate file($ftime) <= $abs\n" if $self->{debug}; $rotate++; $dorotate++; # Just for debugging } # Move to next occurance regardless warn "Dropping initial occurance($abs)\n" if $self->{debug}; $abs = $self->_get_next_occurance($pat); unless(defined $abs && $abs) { warn "Next occurance is null for $pat\n"; $abs = 0; } } # Elsif it is time to rotate #elsif(Date_Cmp($abs,$tm) <= 0) elsif($abs <= $tm) { # Then we need to rotate warn "Need rotate $abs <= $tm\n" if $self->{debug}; $abs = $self->_get_next_occurance($pat); unless(defined $abs && $abs) { warn "Next occurance is null for $pat\n"; $abs = 0; } $rotate++; $dorotate++; # Just for debugging } push(@{$self->{'recurrance'}},[$abs,$pat]) if $abs; warn "time_to_rotate(mode,rotate,next) => ($mode,$dorotate,$abs)\n" if $self->{debug}; } } $self->{'new'} = 0; # No longer brand-spankers warn "time_to_rotate(mode,rotate) => ($mode,$rotate)\n" if $self->{debug}; return wantarray ? ($mode,$rotate) : $rotate; } ########################################################################### # # Subroutine _gen_occurance # # Args: Date::Manip occurance pattern # # Rtns: array of dates for next few events # # If asked we will return an inital occurance that is before the current # time. This can be used to see if we need to rotate on start up. We are # often called by CGI (short lived) proggies :-( # sub _gen_occurance { my $self = shift; # My object my $pat = shift; # Do we return an initial occurance before the current time? my $initial = shift || 0; my $range = ''; my $base = 'now'; # default to calcs based on the current time if($pat =~ /^0:0:0:0:0/) # Small recurrance less than 1 hour { $range = "4 hours later"; $base = "1 hours ago" if $initial; } elsif($pat =~ /^0:0:0:0/) # recurrance less than 1 day { $range = "4 days later"; $base = "1 days ago" if $initial; } elsif($pat =~ /^0:0:0:/) # recurrance less than 1 week { $range = "4 weeks later"; $base = "1 weeks ago" if $initial; } elsif($pat =~ /^0:0:/) # recurrance less than 1 month { $range = "4 months later"; $base = "1 months ago" if $initial; } elsif($pat =~ /^0:/) # recurrance less than 1 year { $range = "24 months later"; $base = "24 months ago" if $initial; } else # years { my($yrs) = $pat =~ m/^(\d+):/; $yrs = 1 unless $yrs; my $months = $yrs * 4 * 12; $range = "$months months later"; $base = "$months months ago" if $initial; } # The next date must start at least 1 second away from now other wise # we may rotate for every message we recieve with in this second :-( my $start = DateCalc($base,"+ 1 second"); warn "ParseRecur($pat,$base,$start,$range);\n" if $self->{debug}; my @dates = ParseRecur($pat,$base,$start,$range); # Just in case we have a bad parse or our assumptions are wrong. # We default to days unless(scalar @dates >= 2) { warn "Failed to parse ($pat). Going daily\n"; @dates = ParseRecur('0:0:0:1*0:0:0',"now","now","1 months later"); if($initial) { @dates = ParseRecur('0:0:0:1*0:0:0',"2 days ago","2 days ago","1 months later"); } } # Convert the dates to seconds since the epoch so we can use # numerical comparision instead of textual my @epochs = (); my @a = ('%Y','%m','%d','%H','%M','%S'); foreach(@dates) { my($y,$m,$d,$h,$mn,$s) = Date::Manip::UnixDate($_, @a); my $e = Date_SecsSince1970GMT($m,$d,$y,$h,$mn,$s); if( $self->{debug} ) { warn "Date to epochs ($_) => ($e)\n"; } push @epochs, $e; } # Clean out all but the one previous to now if we are doing an # initial occurance my $now = time(); if($initial) { my $before = ''; while(@epochs && ( $epochs[0] <= $now) ) { $before = shift(@epochs); #warn "Shifting $before\n"; } #warn "Unshifting $before\n"; unshift(@epochs,$before) if $before; } else { # Clean out dates that occur before now, being careful not to loop # forever (thanks James). shift(@epochs) while @epochs && ( $epochs[0] <= $now); } if($self->{debug}) { warn "Recurrances are at: ".join("\n\t", @dates),"\n"; } warn "No recurrances found! Probably a timezone issue!\n" unless @dates; return @epochs; } ########################################################################### # # Subroutine _get_next_occurance # # Args: Date::Manip occurance pattern # # Rtns: date # # We don't want to call Date::Manip::ParseRecur too often as it is very # expensive. So, we cache what is returned from _gen_occurance(). sub _get_next_occurance { my $self = shift; # My object my $pat = shift; # (ms) Throw out expired occurances my $now = $self->{timer}->(); if(defined $self->{'dates'}{$pat}) { while( @{$self->{'dates'}{$pat}} ) { last if $self->{'dates'}{$pat}->[0] >= $now; shift @{$self->{'dates'}{$pat}}; } } # If this is first time then generate some new ones including one # before our time to test against the log file if(!defined $self->{'dates'}{$pat}) { @{$self->{'dates'}{$pat}} = $self->_gen_occurance($pat,1); } # Elsif close to the end of what we have elsif( scalar(@{$self->{'dates'}{$pat}}) < 2) { @{$self->{'dates'}{$pat}} = $self->_gen_occurance($pat); } return( shift(@{$self->{'dates'}{$pat}}) ); } # Lock and unlock routines. For when we need to write a message. use Fcntl ':flock'; # import LOCK_* constants sub lock { my $self = shift; flock($self->{LDF}->{fh},LOCK_EX); # Make sure we are at the EOF seek($self->{LDF}->{fh}, 0, 2); warn localtime() ." $$ Locked\n" if $self->{debug}; return; } sub unlock { my $self = shift; flock($self->{LDF}->{fh},LOCK_UN); warn localtime() . " $$ unLocked\n" if $self->{debug}; } # Lock and unlock routines. For when we need to roll the logs. # # Note: On May 1, Dan Waldheim's good news was: # I discovered something interesting about forked processes and locking. # If the parent "open"s the filehandle and then forks, exclusive locks # don't work properly between the parent and children. Anyone can grab a # lock while someone else thinks they have it. To work properly the # "open" has to be done within each process. # # Thanks Dan sub lfhlock_test { my $self = shift; if (open(LFH, ">>$self->{lf}")) { $self->{lfh} = *LFH; if (flock($self->{lfh}, LOCK_EX | LOCK_NB)) { warn "$$ got lock on Lock File ".$self->{lfh}."\n" if $self->{debug}; return 1; } } else { $self->{lfh} = 0; warn "$$ couldn't get lock on Lock File\n" if $self->{debug}; return 0; } } sub lfhlock { my $self = shift; if (!$self->{lfh}) { if (!open(LFH, ">>$self->{lf}")) { return 0; } $self->{lfh} = *LFH; } flock($self->{lfh},LOCK_EX); } sub lfhunlock { my $self = shift; if($self->{lfh}) { flock($self->{lfh},LOCK_UN); close $self->{lfh}; $self->{lfh} = 0; } } sub debug { $_[0]->{'debug'} = $_[1]; } __END__ =head1 NAME Log::Dispatch::FileRotate - Log to files that archive/rotate themselves =head1 SYNOPSIS use Log::Dispatch::FileRotate; my $file = Log::Dispatch::FileRotate->new( name => 'file1', min_level => 'info', filename => 'Somefile.log', mode => 'append' , size => 10, max => 6, ); # or for a time based rotation my $file = Log::Dispatch::FileRotate->new( name => 'file1', min_level => 'info', filename => 'Somefile.log', mode => 'append' , TZ => 'AEDT', DatePattern => 'yyyy-dd-HH', ); $file->log( level => 'info', message => "your comment\n" ); =head1 DESCRIPTION This module provides a simple object for logging to files under the Log::Dispatch::* system, and automatically rotating them according to different constraints. This is basically a Log::Dispatch::File wrapper with additions. To that end the arguments name, min_level, filename and mode behave the same as Log::Dispatch::File. So see its man page (perldoc Log::Dispatch::File) The arguments size and max specify the maximum size and maximum number of log files created. The size defaults to 10M and the max number of files defaults to 1. If DatePattern is not defined then we default to working in size mode. That is, use size values for deciding when to rotate. Once DatePattern is defined FileRotate will move into time mode. Once this happens file rotation ignores size constraints and uses the defined date pattern constraints. If you setup a config file using Log::Log4perl::init_and_watch() or the like, you can switch between modes just by commenting out the DatePattern line. When using DatePattern make sure TZ is defined correctly and that the TZ you use is understood by Date::Manip. We use Date::Manip to generate our recurrences. Bad TZ equals bad recurrences equals surprises! Read the Date::Manip man page for more details on TZ. DatePattern will default to a daily rotate if your entered pattern is incorrect. You will also get a warning message. If you have multiple writers that were started at different times you will find each writer will try to rotate the log file at a recurrence calculated from its start time. To sync all the writers just use a config file and update it after starting your last writer. This will cause Log::Dispatch::FileRotate->new() to be called by each of the writers close to the same time, and if your recurrences aren't too close together all should sync up just nicely. I initially aasumed a long runinng process but it seems people are using this module as part of short running CGI programs. So, now we look at the last modified time stamp of the log file and compare it to a previous occurance of a DatePattern, on startup only. If the file stat shows the mtime to be earlier than the previous recurrance then I rotate the log file. We handle multiple writers using flock(). =head1 DatePattern As I said earlier we use Date::Manip for generating our recurrence events. This means we can understand Date::Manip's recurrence patterns and the normal log4j DatePatterns. We don't use DatePattern to define the extension of the log file though. DatePattern can therefore take forms like: Date::Manip style 0:0:0:0:5:30:0 every 5 hours and 30 minutes 0:0:0:2*12:30:0 every 2 days at 12:30 (each day) 3*1:0:2:12:0:0 every 3 years on Jan 2 at noon DailyRollingFileAppender log4j style yyyy-MM every month yyyy-ww every week yyyy-MM-dd every day yyyy-MM-dd-a every day at noon yyyy-MM-dd-HH every hour yyyy-MM-dd-HH-MM every minute To specify multiple recurrences in a single string separate them with a semicolon: yyyy-MM-dd; 0:0:0:2*12:30:0 This says we want to rotate every day AND every 2 days at 12:30. Put in as many as you like. A complete description of Date::Manip recurrences is beyond us here except to quote (from the man page): A recur description is a string of the format Y:M:W:D:H:MN:S . Exactly one of the colons may optionally be replaced by an asterisk, or an asterisk may be prepended to the string. Any value "N" to the left of the asterisk refers to the "Nth" one. Any value to the right of the asterisk refers to a value as it appears on a calendar/clock. Values to the right can be listed a single values, ranges (2 numbers separated by a dash "-"), or a comma separated list of values or ranges. In a few cases, negative values are appropriate. This is best illustrated by example. 0:0:2:1:0:0:0 every 2 weeks and 1 day 0:0:0:0:5:30:0 every 5 hours and 30 minutes 0:0:0:2*12:30:0 every 2 days at 12:30 (each day) 3*1:0:2:12:0:0 every 3 years on Jan 2 at noon 0:1*0:2:12,14:0:0 2nd of every month at 12:00 and 14:00 1:0:0*45:0:0:0 45th day of every year 0:1*4:2:0:0:0 4th tuesday (day 2) of every month 0:1*-1:2:0:0:0 last tuesday of every month 0:1:0*-2:0:0:0 2nd to last day of every month =head1 METHODS =over 4 =item * new(%p) This method takes a hash of parameters. The following options are valid: =item -- name ($) The name of the object (not the filename!). Required. =item -- size ($) The maxium (or close to) size the log file can grow too. =item -- max ($) The maxium number of log files to create. =item -- TZ ($) The TimeZone time based calculations should be done in. This should match Date::Manip's concept of timezones and of course your machines timezone. =item -- DatePattern ($) The DatePattern as defined above. =item -- min_level ($) The minimum logging level this object will accept. See the Log::Dispatch documentation for more information. Required. =item -- max_level ($) The maximum logging level this obejct will accept. See the Log::Dispatch documentation for more information. This is not required. By default the maximum is the highest possible level (which means functionally that the object has no maximum). =item -- filename ($) The filename to be opened for writing. This is the base name. Rotated log files will be renamed filename.1 thru to filename.C. Where max is the paramater defined above. =item -- mode ($) The mode the file should be opened with. Valid options are 'write', '>', 'append', '>>', or the relevant constants from Fcntl. The default is 'write'. =item -- autoflush ($) Whether or not the file should be autoflushed. This defaults to true. =item -- callbacks( \& or [ \&, \&, ... ] ) This parameter may be a single subroutine reference or an array reference of subroutine references. These callbacks will be called in the order they are given and passed a hash containing the following keys: ( message => $log_message, level => $log_level ) The callbacks are expected to modify the message and then return a single scalar containing that modified message. These callbacks will be called when either the C or C methods are called and will only be applied to a given message once. =item -- DEBUG ($) Turn on lots of warning messages to STDERR about what this module is doing if set to 1. Really only useful to me. =item * log_message( message => $ ) Sends a message to the appropriate output. Generally this shouldn't be called directly but should be called through the C method (in Log::Dispatch::Output). =item * setDatePattern( $ or [ $, $, ... ] ) Set a new suite of recurrances for file rotation. You can pass in a single string or a reference to an array of strings. Multiple recurrences can also be define within a single string by seperating them with a semi-colon (;) See the discussion above regarding the setDatePattern paramater for more details. =back =head1 TODO compression, signal based rotates, proper test suite Could possibly use Logfile::Rotate as well/instead. =head1 AUTHOR Mark Pfeiffer, inspired by Dave Rolsky's, , code :-) Kevin Goess suggested multiple writers should be supported. He also conned me into doing the time based stuff. Thanks Kevin! :-) Thanks also to Dan Waldheim for helping with some of the locking issues in a forked environment. And thanks to Stephen Gordon for his more portable code on lockfile naming. =cut =head1 Copyright Copyright 2005-2006, Mark Pfeiffer This code may be copied only under the terms of the Artistic License, or GPL License which may be found in the Perl 5 source kit. Use 'perldoc perlartistic' to see the Artistic License. Use 'perldoc perlgpl' to see the GNU General Public License. Complete documentation for Perl, including FAQ lists, should be found on this system using `man perl' or `perldoc perl'. If you have access to the Internet, point your browser at http://www.perl.org/, the Perl Home Page. =cut PKsjZG-..Null.pmnu[package Log::Dispatch::Null; { $Log::Dispatch::Null::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch::Output; use base qw( Log::Dispatch::Output ); sub new { my $proto = shift; my $class = ref $proto || $proto; my $self = bless {}, $class; $self->_basic_init(@_); return $self; } sub log_message { } 1; # ABSTRACT: Object that accepts messages and does nothing __END__ =pod =head1 NAME Log::Dispatch::Null - Object that accepts messages and does nothing =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $null = Log::Dispatch->new( outputs => [ [ 'Null', min_level => 'debug' ] ] ); $null->emerg( "I've fallen and I can't get up" ); =head1 DESCRIPTION This class provides a null logging object. Messages can be sent to the object but it does nothing with them. =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZ( Output.pmnu[package Log::Dispatch::Output; { $Log::Dispatch::Output::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch; use base qw( Log::Dispatch::Base ); use Params::Validate qw(validate SCALAR ARRAYREF CODEREF BOOLEAN); Params::Validate::validation_options( allow_extra => 1 ); use Carp (); my $level_names = [qw( debug info notice warning error critical alert emergency )]; my $ln = 0; my $level_numbers = { ( map { $_ => $ln++ } @{$level_names} ), warn => 3, err => 4, crit => 5, emerg => 7 }; sub new { my $proto = shift; my $class = ref $proto || $proto; die "The new method must be overridden in the $class subclass"; } sub log { my $self = shift; my %p = validate( @_, { level => { type => SCALAR }, message => { type => SCALAR }, } ); return unless $self->_should_log( $p{level} ); $p{message} = $self->_apply_callbacks(%p) if $self->{callbacks}; $self->log_message(%p); } sub _basic_init { my $self = shift; my %p = validate( @_, { name => { type => SCALAR, optional => 1 }, min_level => { type => SCALAR, required => 1 }, max_level => { type => SCALAR, optional => 1 }, callbacks => { type => ARRAYREF | CODEREF, optional => 1 }, newline => { type => BOOLEAN, optional => 1 }, } ); $self->{level_names} = $level_names; $self->{level_numbers} = $level_numbers; $self->{name} = $p{name} || $self->_unique_name(); $self->{min_level} = $self->_level_as_number( $p{min_level} ); die "Invalid level specified for min_level" unless defined $self->{min_level}; # Either use the parameter supplied or just the highest possible level. $self->{max_level} = ( exists $p{max_level} ? $self->_level_as_number( $p{max_level} ) : $#{ $self->{level_names} } ); die "Invalid level specified for max_level" unless defined $self->{max_level}; my @cb = $self->_get_callbacks(%p); $self->{callbacks} = \@cb if @cb; if ( $p{newline} ) { push @{ $self->{callbacks} }, \&_add_newline_callback; } } sub name { my $self = shift; return $self->{name}; } sub min_level { my $self = shift; return $self->{level_names}[ $self->{min_level} ]; } sub max_level { my $self = shift; return $self->{level_names}[ $self->{max_level} ]; } sub accepted_levels { my $self = shift; return @{ $self->{level_names} } [ $self->{min_level} .. $self->{max_level} ]; } sub _should_log { my $self = shift; my $msg_level = $self->_level_as_number(shift); return ( ( $msg_level >= $self->{min_level} ) && ( $msg_level <= $self->{max_level} ) ); } sub _level_as_number { my $self = shift; my $level = shift; unless ( defined $level ) { Carp::croak "undefined value provided for log level"; } return $level if $level =~ /^\d$/; unless ( Log::Dispatch->level_is_valid($level) ) { Carp::croak "$level is not a valid Log::Dispatch log level"; } return $self->{level_numbers}{$level}; } sub _level_as_name { my $self = shift; my $level = shift; unless ( defined $level ) { Carp::croak "undefined value provided for log level"; } return $level unless $level =~ /^\d$/; return $self->{level_names}[$level]; } my $_unique_name_counter = 0; sub _unique_name { my $self = shift; return '_anon_' . $_unique_name_counter++; } sub _add_newline_callback { my %p = @_; return $p{message} . "\n"; } 1; # ABSTRACT: Base class for all Log::Dispatch::* objects __END__ =pod =head1 NAME Log::Dispatch::Output - Base class for all Log::Dispatch::* objects =head1 VERSION version 2.41 =head1 SYNOPSIS package Log::Dispatch::MySubclass; use Log::Dispatch::Output; use base qw( Log::Dispatch::Output ); sub new { my $proto = shift; my $class = ref $proto || $proto; my %p = @_; my $self = bless {}, $class; $self->_basic_init(%p); # Do more if you like return $self; } sub log_message { my $self = shift; my %p = @_; # Do something with message in $p{message} } 1; =head1 DESCRIPTION This module is the base class from which all Log::Dispatch::* objects should be derived. =head1 CONSTRUCTOR The constructor, C, must be overridden in a subclass. See L for a description of the common parameters accepted by this constructor. =head1 METHODS =over 4 =item * _basic_init(%p) This should be called from a subclass's constructor. Make sure to pass the arguments in @_ to it. It sets the object's name and minimum level from the passed parameters It also sets up two other attributes which are used by other Log::Dispatch::Output methods, level_names and level_numbers. Subclasses will perform parameter validation in this method, and must also call the superclass's method. =item * name Returns the object's name. =item * min_level Returns the object's minimum log level. =item * max_level Returns the object's maximum log level. =item * accepted_levels Returns a list of the object's accepted levels (by name) from minimum to maximum. =item * log( level => $, message => $ ) Sends a message if the level is greater than or equal to the object's minimum level. This method applies any message formatting callbacks that the object may have. =item * _should_log ($) This method is called from the C method with the log level of the message to be logged as an argument. It returns a boolean value indicating whether or not the message should be logged by this particular object. The C method will not process the message if the return value is false. =item * _level_as_number ($) This method will take a log level as a string (or a number) and return the number of that log level. If not given an argument, it returns the calling object's log level instead. If it cannot determine the level then it will croak. =item * add_callback( $code ) Adds a callback (like those given during construction). It is added to the end of the list of callbacks. =back =head2 Subclassing This class should be used as the base class for all logging objects you create that you would like to work under the Log::Dispatch architecture. Subclassing is fairly trivial. For most subclasses, if you simply copy the code in the SYNOPSIS and then put some functionality into the C method then you should be all set. Please make sure to use the C<_basic_init> method as described above. The actual logging implementation should be done in a C method that you write. B!>. =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZr''File.pmnu[package Log::Dispatch::File; { $Log::Dispatch::File::VERSION = '2.41'; } use strict; use warnings; use Log::Dispatch::Output; use base qw( Log::Dispatch::Output ); use Params::Validate qw(validate SCALAR BOOLEAN); Params::Validate::validation_options( allow_extra => 1 ); use Scalar::Util qw( openhandle ); # Prevents death later on if IO::File can't export this constant. *O_APPEND = \&APPEND unless defined &O_APPEND; sub APPEND { 0 } sub new { my $proto = shift; my $class = ref $proto || $proto; my %p = @_; my $self = bless {}, $class; $self->_basic_init(%p); $self->_make_handle; return $self; } sub _basic_init { my $self = shift; $self->SUPER::_basic_init(@_); my %p = validate( @_, { filename => { type => SCALAR }, mode => { type => SCALAR, default => '>' }, binmode => { type => SCALAR, default => undef }, autoflush => { type => BOOLEAN, default => 1 }, close_after_write => { type => BOOLEAN, default => 0 }, permissions => { type => SCALAR, optional => 1 }, syswrite => { type => BOOLEAN, default => 0 }, } ); $self->{filename} = $p{filename}; $self->{binmode} = $p{binmode}; $self->{autoflush} = $p{autoflush}; $self->{close} = $p{close_after_write}; $self->{permissions} = $p{permissions}; $self->{syswrite} = $p{syswrite}; if ( $self->{close} ) { $self->{mode} = '>>'; } elsif ( exists $p{mode} && defined $p{mode} && ( $p{mode} =~ /^(?:>>|append)$/ || ( $p{mode} =~ /^\d+$/ && $p{mode} == O_APPEND() ) ) ) { $self->{mode} = '>>'; } else { $self->{mode} = '>'; } } sub _make_handle { my $self = shift; $self->_open_file() unless $self->{close}; } sub _open_file { my $self = shift; open my $fh, $self->{mode}, $self->{filename} or die "Cannot write to '$self->{filename}': $!"; if ( $self->{autoflush} ) { my $oldfh = select $fh; $| = 1; select $oldfh; } if ( $self->{permissions} && !$self->{chmodded} ) { my $current_mode = ( stat $self->{filename} )[2] & 07777; if ( $current_mode ne $self->{permissions} ) { chmod $self->{permissions}, $self->{filename} or die "Cannot chmod $self->{filename} to $self->{permissions}: $!"; } $self->{chmodded} = 1; } if ( $self->{binmode} ) { binmode $fh, $self->{binmode}; } $self->{fh} = $fh; } sub log_message { my $self = shift; my %p = @_; if ( $self->{close} ) { $self->_open_file; } my $fh = $self->{fh}; if ( $self->{syswrite} ) { defined syswrite( $fh, $p{message} ) or die "Cannot write to '$self->{filename}': $!"; } else { print $fh $p{message} or die "Cannot write to '$self->{filename}': $!"; } if ( $self->{close} ) { close $fh or die "Cannot close '$self->{filename}': $!"; } } sub DESTROY { my $self = shift; if ( $self->{fh} ) { my $fh = $self->{fh}; close $fh if openhandle($fh); } } 1; # ABSTRACT: Object for logging to files __END__ =pod =head1 NAME Log::Dispatch::File - Object for logging to files =head1 VERSION version 2.41 =head1 SYNOPSIS use Log::Dispatch; my $log = Log::Dispatch->new( outputs => [ [ 'File', min_level => 'info', filename => 'Somefile.log', mode => '>>', newline => 1 ] ], ); $log->emerg("I've fallen and I can't get up"); =head1 DESCRIPTION This module provides a simple object for logging to files under the Log::Dispatch::* system. Note that a newline will I be added automatically at the end of a message by default. To do that, pass C<< newline => 1 >>. =head1 CONSTRUCTOR The constructor takes the following parameters in addition to the standard parameters documented in L: =over 4 =item * filename ($) The filename to be opened for writing. =item * mode ($) The mode the file should be opened with. Valid options are 'write', '>', 'append', '>>', or the relevant constants from Fcntl. The default is 'write'. =item * binmode ($) A layer name to be passed to binmode, like ":encoding(UTF-8)" or ":raw". =item * close_after_write ($) Whether or not the file should be closed after each write. This defaults to false. If this is true, then the mode will always be append, so that the file is not re-written for each new message. =item * autoflush ($) Whether or not the file should be autoflushed. This defaults to true. =item * syswrite ($) Whether or not to perform the write using L(), as opposed to L(). This defaults to false. The usual caveats and warnings as documented in L apply. =item * permissions ($) If the file does not already exist, the permissions that it should be created with. Optional. The argument passed must be a valid octal value, such as 0600 or the constants available from Fcntl, like S_IRUSR|S_IWUSR. See L for more on potential traps when passing octal values around. Most importantly, remember that if you pass a string that looks like an octal value, like this: my $mode = '0644'; Then the resulting file will end up with permissions like this: --w----r-T which is probably not what you want. =back =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZb Conflicts.pmnu[package # hide from PAUSE Log::Dispatch::Conflicts; use strict; use warnings; use Dist::CheckConflicts -dist => 'Log::Dispatch', -conflicts => { 'Log::Dispatch::File::Stamped' => '0.10', }, ; 1; # ABSTRACT: Provide information on conflicts for Log::Dispatch __END__ =pod =head1 NAME Log::Dispatch::Conflicts - Provide information on conflicts for Log::Dispatch =head1 VERSION version 2.41 =head1 AUTHOR Dave Rolsky =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut PKsjZk* ApacheLog.pmnu[PKsjZx%iiEmail/MailSendmail.pmnu[PKsjZ@Email/MIMELite.pmnu[PKsjZ0 0 Email/MailSender.pmnu[PKsjZCaCCEmail/MailSend.pmnu[PKsjZu`BB(Email.pmnu[PKsjZK0HH 7Syslog.pmnu[PKsjZM55 GScreen.pmnu[PKsjZo|OFile/Locked.pmnu[PKsjZ~jCccWCode.pmnu[PKsjZ"X55 3_Handle.pmnu[PKsjZg*mfBase.pmnu[PKsjZiX1ee WlFileRotate.pmnu[PKsjZG-..jNull.pmnu[PKsjZ( Output.pmnu[PKsjZr''File.pmnu[PKsjZb l Conflicts.pmnu[PK2