Log::Handler - Log messages to one or more outputs.
use Log::Handler; my $log = Log::Handler->new(); $log->add(file => { filename => 'file.log', maxlevel => 'debug', minlevel => 'warn', newline => 1, }); $log->alert("foo bar");
This module is just a simple object oriented log handler and very easy to use. It's possible to define a log level for your programs and control the amount of informations that will be logged to one or more outputs.
As I re-designed the Log::Handler it was my wish to support the old style from version 0.38. The one exception is that the option redirect_to_stderr doesn't exist any more. In all other cases you can use all things from 0.38.
redirect_to_stderr
Since version 0.38_01 the method add() is totaly new. With this method you can add logger objects as much as you wish, each with its own level range and different other options. As example you can add a logger for the levels 0-4 (emergency-warning) and another logger for the levels 4-7 (warning-debug).
add()
The main logic of Log::Handler is moved to Log::Handler::Logger. The Log::Handler just manage all logger objects and forward messages to it if the current log handler would log.
There are different output logger available:
Log::Handler::Logger::File Log::Handler::Logger::Email Log::Handler::Logger::Forward
Placeholders are now available for the prefix in printf() style. The old style of <--LEVEL--> is deprecated and you should use %L instead. In addition a postfix option is available now. Take a look to the documentation of prefix and postfix.
printf()
%L
postfix
prefix
Now it's possible to load the configuration from a file. Take a look into the documentation for Log::Handler::Config.
The methods close(), get_prefix() and set_prefix() are not available any more.
close()
get_prefix()
set_prefix()
rewrite_to_stderr.
rewrite_to_stderr
The method trace() writes caller() informations to all logger by default. It's possible to disable this by set the option trace to 0.
trace()
caller()
trace
Extensions and changes are planed. I hope I have enough time to implement my ideas as soon as possible!
Call new() to create a new log handler object.
new()
my $log = Log::Handler->new();
Call add() to add a new logger.
There are different ways to add a new logger object to the handler. In the following example I show you one simple way:
use Log::Handler; use Log::Handler::Logger::File; # the logger options (how to handle the file) my %logger_options = ( timeformat => '%Y/%m/%d %H:%M:%S', newline => 1, prefix => '%T [%L] %S: ', postfix => '', maxlevel => 'debug', minlevel => 'emergency', die_on_errors => 1, trace => 1, debug => 0, debug_mode => 2, debug_skip => 0, ); # the options for the file my %file_options = ( filename => 'file.log', filelock => 1, fileopen => 1, reopen => 1, mode => 'append', autoflush => 1, permissions => '0660', utf8 => 1, ); # we creating the objects my $log = Log::Handler->new(); my $file = Log::Handler::Logger::File->new( \%file_options ); # now we add the file object to the handler and the logger options $log->add( $file => \%logger_options );
But it can be simplier! You can pass all options for the logger and for the file in one step. You just need to tell the handler what do you want to add.
use Log::Handler; my %all_options = (%logger_options, %file_options); $log->add( file => \%all_options );
Take a look to the examples section for more informations.
Further examples:
$log->add( email => \%all_options ); $log->add( forward => \%all_options );
There are eigth log level methods (thirteen with shortcuts):
debug() is the highest and emergency() or emerg() is the lowest log level. You can define the log level with the options maxlevel and minlevel.
debug()
emergency()
emerg()
maxlevel
minlevel
The methods note(), warn(), err(), crit() and emerg() are just shortcuts.
note()
warn()
err()
crit()
Example:
If you set the option maxlevel to warning and minlevel to emergency then the levels emergency, alert, critical, error and warning will be logged.
warning
emergency
The call of a log level method is very simple:
$log->info("Hello World! How are you?");
Or maybe:
$log->info("Hello World!", "How are you?");
Both calls would log
Feb 01 12:56:31 [INFO] Hello World! How are you?
These thirteen methods could be very useful if you want to kwow if the current log level would output the message. All methods returns TRUE if the current set of minlevel and maxlevel would log the message and FALSE if not. Example:
$log->debug(Dumper(\%hash));
This example would dump the hash in any case and pass it to the log handler, but that is not that what we really want!
if ( $log->is_debug ) { $log->debug(Dumper(\%hash)); }
Now we dump the hash only if the current log level would log it.
The methods is_note(), is_warn(), is_err(), is_crit() and is_emerg() are just shortcuts.
is_note()
is_warn()
is_err()
is_crit()
is_emerg()
This are special methods that can be used for CRITICAL, ALERT and EMERGENCY messages. A lot of people like to use just DEBUG, INFO, WARN, ERROR and FATAL. For this reason I though to implement it. You just have to set minlevel to critical, alert or emergency to use it.
critical
alert
This method is a special log level and very useful if you want to log caller() informations.
In contrast to the log level methods this method forces caller() informations to all logger and you don't need to activate the debugger with the option debug. Example:
debug
my $log = Log::Handler->new(); $log->add(file => { filename => '*STDOUT' }); $log->trace("caller informations:"); Jun 05 21:20:32 [TRACE] caller informations CALL(2): package(main) filename(./log-handler-test.pl) line(22) subroutine(Log::Handler::trace) hasargs(1) CALL(1): package(Log::Handler) filename(/usr/local/share/perl/5.8.8/Log/Handler.pm) line(941) subroutine(Log::Handler::_write) hasargs(1) CALL(0): package(Log::Handler) filename(/usr/local/share/perl/5.8.8/Log/Handler.pm) line(1097) subroutine(Devel::Backtrace::new) hasargs(1) wantarray(0)
Maybe you like to forward caller() informations to all logger if an unexpected error occurs.
$SIG{__DIE__} = sub { $log->trace(@_) };
Take a look at the examples of the options debug, debug_mode and debug_skip for more informations.
debug_mode
debug_skip
Call errstr() if you want to get the last error message. This is useful with die_on_errors. If you set die_on_errors to 0 the handler wouldn't croak on failed write operations. Set die_on_errors to control it yourself.
errstr()
die_on_errors
0
use Log::Handler; my $log = Log::Handler->new(); $log->add(file => { filename => 'file.log', maxlevel => 'info', mode => 'append', die_on_errors => 0, }); $log->info("Hello World!") or die $log->errstr;
Or
unless ( $log->info("Hello World!") ) { $error_string = $log->errstr; }
The exception is that the handler croaks in any case if the call of new() or add() fails because on missing or wrong settings!
With this method it's possible to load your logger configuration from a file.
$log->config(filename => 'file.conf');
Take a look into the documentation of Log::Handler::Config for more informations.
The timeformat is used for the placeholder %T. You can set timeformat with a date and time format that will be coverted by POSIX::strftime. The default format is %b %d %H:%M:%S and looks like
timeformat
%T
POSIX::strftime
%b %d %H:%M:%S
Feb 01 12:56:31
As example the format "%Y/%m/%d %H:%M:%S" would looks like
2007/02/01 12:56:31
This helpful option appends a newline to the log message if it not exist.
0 - inactive (default) 1 - active - appends a newline to the log message if not exist
It's possible to define a prefix and postfix for each message that will be logged to the log file. The prefix will be written before and the postfix after the message. Within the prefix and postfix it's possible to use different placeholders that will be replaced.
The available placeholders are:
%L Log level %T Timestamp %P PID %H Hostname %N Newline %C Caller - filename and line number where the logger was called %p Script - the program name %t Measurement - replaced with the time since the last call of the handler
The default prefix is set to '%T [%L] '. The postfix is not defined by default.
'%T [%L] '
As example the following code
$log->alert("foo bar");
would log
Feb 01 12:56:31 [ALERT] foo bar
If you set prefix and postfix to
prefix => '%T foo %L bar ' postfix => ' (%C)'
and call
$log->info("baz");
then it would log
Feb 01 12:56:31 foo INFO bar baz (script.pl, line 40)
Traces will be added after the postfix.
With these options it's possible to set the log levels for your program. The log levels are:
7 - debug 6 - info 5 - notice, note 4 - warning, warn 3 - error, err 2 - critical, crit 1 - alert 0 - emergency, emerg
The levels note, err, crit and emerg are just shortcuts.
note
err
crit
emerg
It's possible to set the log level as a string or as number. The default setting for maxlevel is 4 and the default setting for minlevel is 0.
Example: If maxlevel is set to 4 and minlevel to 0 then the levels error, critical, alert and emergency would be logged.
You can set both to 8 or nothing if you don't want to deactivate the logger.
nothing
Set die_on_errors to 0 if you don't want that the handler croaks if normal operations fail.
0 - will not die on errors 1 - will die (e.g. croak) on errors
The exception is that the handler croaks in any case if the call of new() fails because on missing params or wrong settings.
This option is just useful if you want to forward messages with Log::Handler::Logger::Forward.
It expects a array reference with a list of placeholders:
setinfo => [ qw/%T %L %H/ ]
Then a hash is builded and the placeholders are replaced with real names as hash keys:
%L level %T timestamp %P pid %H hostname %N newline %C caller %p progname %t time
The hash will be passed as a reference to the forwarders. Here a code example:
use Log::Handler; my $log = Log::Handler->new(); $log->add(forward => { forward_to => [ \&my_func ], setinfo => [ qw/%T %L %H/ ], maxlevel => 'info', prefix => '', }); $log->info('a forwarded message'); # now the message is passed as a hash reference to my_func() sub my_func { my $params = shift; print "Timestamp: $params->{timestamp}\n"; print "Level: $params->{level}\n"; print "Hostname: $params->{hostname}\n"; print "Message: $params->{message}\n"; }
With this options it's possible to disable the tracing for a logger. By default this option is set to 1 and tracing is enabled.
You can activate a simple debugger that writes caller() informations for each log level that would logged. The debugger is logging all defined values except hints and bitmask. Set debug to 1 to activate the debugger. The debugger is set to 0 by default.
hints
bitmask
There are two debug modes: line(1) and block(2) mode. The default mode is 1.
The block mode looks like this:
use strict; use warnings; use Log::Handler; my $log = Log::Handler->new() $log->add(file => { filename => '*STDOUT', maxlevel => 'debug', debug => 1, debug_mode => 1 }); sub test1 { $log->debug() } sub test2 { &test1; } &test2;
Output:
Apr 26 12:54:11 [DEBUG] CALL(4): package(main) filename(./trace.pl) line(15) subroutine(main::test2) hasargs(0) CALL(3): package(main) filename(./trace.pl) line(13) subroutine(main::test1) hasargs(0) CALL(2): package(main) filename(./trace.pl) line(12) subroutine(Log::Handler::__ANON__) hasargs(1) CALL(1): package(Log::Handler) filename(/usr/local/share/perl/5.8.8/Log/Handler.pm) line(713) subroutine(Log::Handler::_write) hasargs(1) CALL(0): package(Log::Handler) filename(/usr/local/share/perl/5.8.8/Log/Handler.pm) line(1022) subroutine(Devel::Backtrace::new) hasargs(1) wantarray(0)
The same code example but the debugger in block mode would looks like this:
debug_mode => 2
Apr 26 12:52:17 [DEBUG] CALL(4): package main filename ./trace.pl line 15 subroutine main::test2 hasargs 0 CALL(3): package main filename ./trace.pl line 13 subroutine main::test1 hasargs 0 CALL(2): package main filename ./trace.pl line 12 subroutine Log::Handler::__ANON__ hasargs 1 CALL(1): package Log::Handler filename /usr/local/share/perl/5.8.8/Log/Handler.pm line 681 subroutine Log::Handler::_write hasargs 1 CALL(0): package Log::Handler filename /usr/local/share/perl/5.8.8/Log/Handler.pm line 990 subroutine Devel::Backtrace::new hasargs 1 wantarray 0
This option let skip the caller() informations the count of debug_skip.
debug_skip => 2 Apr 26 12:55:07 [DEBUG] CALL(2): package(main) filename(./trace.pl) line(16) subroutine(main::test2) hasargs(0) CALL(1): package(main) filename(./trace.pl) line(14) subroutine(main::test1) hasargs(0) CALL(0): package(main) filename(./trace.pl) line(13) subroutine(Log::Handler::__ANON__) hasargs(1)
use Log::Handler; my $log = Log::Handler->new(); $log->add(file => { filename => 'file1.log', mode => 'append', newline => 1, maxlevel => 7, minlevel => 0 }); $log->debug("this is a debug message"); $log->info("this is a info message"); $log->notice("this is a notice"); $log->note("this is a notice as well"); $log->warning("this is a warning"); $log->warn("this is a warning as well"); $log->error("this is a error message"); $log->err("this is a error message as well"); $log->critical("this is a critical message"); $log->crit("this is a critical message as well"); $log->alert("this is a alert message"); $log->emergency("this is a emergency message"); $log->emerg("this is a emergency message as well");
Would log
Feb 01 12:56:31 [DEBUG] this is a debug message Feb 01 12:56:31 [INFO] this is a info message Feb 01 12:56:31 [NOTICE] this is a notice Feb 01 12:56:31 [NOTICE] this is a notice as well Feb 01 12:56:31 [WARNING] this is a warning Feb 01 12:56:31 [WARNING] this is a warning Feb 01 12:56:31 [ERROR] this is a error message Feb 01 12:56:31 [ERROR] this is a error message as well Feb 01 12:56:31 [CRITICAL] this is a critical message Feb 01 12:56:31 [CRITICAL] this is a critial message as well Feb 01 12:56:31 [ALERT] this is a alert message Feb 01 12:56:31 [EMERGENCY] this is a emergency message Feb 01 12:56:31 [EMERGENCY] this is a emergency message as well
use Log::Handler; # create the log handler object my $log = Log::Handler->new; $log->add(file => { filename => 'debug.log', mode => 'append', maxlevel => 7, minlevel => 7, trace => 1, }); $log->add(file => { filename => 'common.log', mode => 'append', maxlevel => 6, minlevel => 5, trace => 0, }); $log->add(file => { filename => 'error.log', mode => 'append', maxlevel => 4, minlevel => 0, trace => 1, }); # log to debug.log $log->debug("this is a debug message"); # log to common.log $log->info("this is a info message"); $log->notice("this is a notice"); $log->note("this is a notice as well"); # log to error.log $log->warning("this is a warning"); $log->warn("this is a warning as well"); $log->error("this is a error message"); $log->err("this is a error message as well"); $log->critical("this is a critical message"); $log->crit("this is a critical message as well"); $log->alert("this is a alert message"); $log->emergency("this is a emergency message"); $log->emerg("this is a emergency message as well"); # force caller() informations just to error.log and debug.log $log->trace("this message goes to all log files");
use Log::Handler; my $log = Log::Handler->new(); $log->add(file => { filename => '/var/run/pid-file1', mode => 'trunc', maxlevel => 5, minlevel => 5, prefix => '%P', timeformat => '' }); $log->note();
Would truncate /var/run/pid-file1 and write just the pid to the logfile.
use Log::Handler; my $log = Log::Handler->new(); $log->add(file => { filename => "${progname}.log", mode => 'append', maxlevel => 6, newline => 1, prefix => "%H[%P] [%L] %S: " }); $log->info("Hello World!"); $log->warning("There is something wrong!");
Would log:
Feb 01 12:56:31 hostname[8923] [INFO] progname: Hello world Feb 01 12:56:31 hostname[8923] [WARNING] progname: There is something wrong!
use Log::Handler; use Data::Dumper; my $log = Log::Handler->new(); $log->add(file => { filename => 'file1.log', mode => 'append', maxlevel => 4, }); my %hash = (foo => 1, bar => 2); $log->debug("\n".Dumper(\%hash)) if $log->is_debug();
Would NOT dump %hash to the $log object!
Do you want write further extensions? There are just some requirements!
Logger objects should provide a new() and a write() method.
write()
Config plugins should provide a get_config() routine.
get_config()
Take a look into the source or write me a mail if you have questions.
Prerequisites for all modules:
Carp Config::General Devel::Backtrace Fcntl Net::SMTP Params::Validate POSIX Time::HiRes Sys::Hostname UNIVERSAL::require
Just for the test suite:
File::Spec Test::More
No exports.
Please report all bugs to <jschulz.cpan(at)bloonix.de>.
Jonny Schulz <jschulz.cpan(at)bloonix.de>.
Do you have any questions or ideas?
MAIL: <jschulz.cpan(at)bloonix.de>
IRC: irc.perl.org#perl
If you send me a mail then add Log::Handler into the subject.
* Log::Handler::Logger::DBI * Log::Handler::Logger::Socket
Copyright (C) 2007 by Jonny Schulz. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
To install Log::Handler, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Log::Handler
CPAN shell
perl -MCPAN -e shell install Log::Handler
For more information on module installation, please visit the detailed CPAN module installation guide.