Log::Handler - Log messages to one or more outputs.
use Log::Handler; my $log = Log::Handler->new(); $log->add(file => { filename => 'file.log', mode => 'append', maxlevel => 'debug', minlevel => 'warning', 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 are logged to one or more outputs.
Since version 0.40 the method add() is totaly new. With this method you can add outputs as much as you wish, each with its own level range and different other options. As example you can add a output for the levels 0-4 (emergency-warning) and another output for the levels 4-7 (warning-debug). Each output is handled as a own object.
add()
This module is used to build the output message and is just for internal usage.
There are different output modules available:
Log::Handler::Output::File Log::Handler::Output::DBI Log::Handler::Output::Email Log::Handler::Output::Forward Log::Handler::Output::Screen
You can add the outputs on different ways. Take a look to the further documentation.
Placeholders are now available for the message layout in printf() style. The old style of <--LEVEL--> is deprecated and you should use %L instead. The layout can be defined with the option message_layout. prefix is deprecated as well.
printf()
%L
message_layout
prefix
Now it's possible to load the configuration from a file. There are 3 configuration plugins available:
Config::General Config::Properties YAML
Take a look into the documentation for Log::Handler::Config.
dateformat priority message_pattern
prefix is now message_layout debug is now debug_trace
rewrite_to_stderr
add() - to add new outputs config() - to load outputs from a configuration file set_pattern() - to create your own placeholder
Please take a look to Log::Handler::Levels because the list is very long.
note() close() get_prefix() set_prefix()
trace() replaced with trace methods for each level warn() still exist but is a replacement vor carp() now
As I re-designed the Log::Handler it was my wish to support the most things from version 0.38.
my $log = Log::Handler->new(filename => 'file.log');
That still running fine because the options are passed as a file output. The exceptions that you should take a look the the kicked/changed methods and options.
Extensions and changes are planed. I hope I have enough time to implement my ideas as soon as possible! Version 0.40 will be the next full release.
There are eigth levels available:
7 debug 6 info 5 notice 4 warning 3 error, err 2 critical, crit 1 alert 0 emergency, emerg
debug is the highest and emergency is the lowest level.
debug
emergency
Call new() to create a new log handler object.
new()
my $log = Log::Handler->new();
Call add() to add a new output object.
The following options are possible for the handler:
With these options it's possible to set the log levels for your program.
Example:
maxlevel => 'error' minlevel => 'emergency' # or maxlevel => 'err' minlevel => 'emerg' # or maxlevel => 3 minlevel => 0
It's possible to set the log level as string or as number. The default setting for maxlevel is warning and the default setting for minlevel is emergency.
maxlevel
warning
minlevel
Example: If maxlevel is set to warning and minlevel to emergency then the levels warning, error, critical, alert and emergency would be logged.
error
critical
alert
You can set both to 8 or nothing if you want to disable the logging machine.
nothing
The timeformat is used for the placeholder %T. You can set timeformat with a date and time format that is converted with POSIX::strftime. The default format is "%b %d %H:%M:%S" and looks like
timeformat
%T
POSIX::strftime
Feb 01 12:56:31
As example the format "%Y/%m/%d %H:%M:%S" would looks like
2007/02/01 12:56:31
The same like timeformat. It's useful if you want to split the date and time:
$log->add(file => { filename => 'file.log', dateformat => '%Y-%m-%d', timeformat => '%H:%M:%S', message_layout => '%D %T %L %m', }); $log->error("an error here");
Would log
2007-02-01 12:56:31 ERROR an error here
This option is not used on default.
This helpful option appends a newline to the output message if a newline not exist.
0 - disable (default) 1 - enable - appends a newline to the log message if not exist
With this option you can define your own message layout with different placeholders in printf() style. The available placeholders are:
%L Log level %T Time or full timestamp (option timeformat) %D Date (option dateformat) %P PID %H Hostname %N Newline %C Caller - filename and line number %p Program name %t Time measurement - replaced with the time since the last call of the handler %m The message.
The default message layout is set to "%T [%L] %m".
As example the following code
$log->alert("foo bar");
would log
Feb 01 12:56:31 [ALERT] foo bar
If you set message_layout to
message_layout => '%T foo %L bar %m (%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 appended after the complete message.
You can create your own placeholders with the method set_pattern().
set_pattern()
Placeholders are documented in the section "PLACEHOLDER".
This option is just useful if you want to forward messages with Log::Handler::Output::Forward or insert the message with Log::Handler::Output::DBI or dump messages to the screen with Log::Handler::Output::Screen.
Possible placeholders:
%L level %T time %D date %P pid %H hostname %N newline %C caller %p progname %t mtime %m message
The option expects a array reference with a list of placeholders:
message_pattern => [ qw/%T %L %H %m/ ]
The patterns are replaced with the pattern names as hash keys and the hash is passed as reference to the output. Here a full code example:
use Log::Handler; my $log = Log::Handler->new(); $log->add(forward => { forward_to => \&my_func, message_pattern => [ qw/%T %L %H/ ], message_layout => '%m', maxlevel => 'info', }); $log->info('a forwarded message'); # now you can access it sub my_func { my $params = shift; print "Timestamp: $params->{time}\n"; print "Level: $params->{level}\n"; print "Hostname: $params->{hostname}\n"; print "Message: $params->{message}\n"; }
With this option you can set the priority of your output objects. This means that messages will be logged at first to the outputs with a higher priority. If this option is not set then the default priority begins with 10 and will be increased +1 with each output. Example...
We add a output with no priority
$log->add(file => { filename => 'file.log' });
This output gets the priority of 10. Now we add another output
This output gets the priority of 11... and so on.
Messages would be logged at first to priority 10 and then 11. Now you can add another output and set the priority to 1.
$log->add(screen => { dump => 1, priority => 1 });
Messages would be logged now at first to the screen.
Set die_on_errors to 0 if you don't want that the handler die on failed write operations.
die_on_errors
0 - will not die on errors 1 - will die (e.g. croak) on errors
If you set die_on_errors to 0 then you have to controll it yourself.
$log->info('info message') or die $log->errstr(); # or Log::Handler->errstr() # or Log::Handler::errstr() # or $Log::Handler::ERRSTR
You can activate a 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_trace to 1 to activate the debugger. The debugger is set to 0 by default.
caller()
hints
bitmask
debug_trace
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_trace => 1, debug_mode => 1 }); sub test1 { $log->warning() } sub test2 { &test1; } &test2;
Output:
Apr 26 12:54:11 [WARN] 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
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)
The method add() excepts 2 option parts; the options for the handler and for the output module you want to use - the output modules got it's own documentation for all options.
There are different ways to add a new output to the handler. The one way is that you create the output object yourself and pass it with the handler options to add().
use Log::Handler; use Log::Handler::Output::File; # the handler options - how to handle the output my %handler_options = ( timeformat => '%Y/%m/%d %H:%M:%S', newline => 1, message_layout => '%T [%L] %S: %m', maxlevel => 'debug', minlevel => 'emergency', die_on_errors => 1, debug_trace => 0, debug_mode => 2, debug_skip => 0, ); # the file options - how to handle 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 file object my $file = Log::Handler::Output::File->new( \%file_options ); # creating a new handler object my $log = Log::Handler->new(); # now we add the file object to the handler with the handler options $log->add( $file => \%handler_options );
But it can be simplier! You can merge all options and pass them to add() in one step, you just need to tell the handler what do you want to add.
# merge the options my %all_options = (%output_options, %file_options); # pass all options and say what you want to add -> a file! $log->add( file => \%all_options );
The options will be splitted intern and you don't need to split it yourself, only if you want to do it yourself.
Further examples:
$log->add( email => \%all_options ); $log->add( forward => \%all_options ); # and so on ...
Take a look to the section "EXAMPLES" for more informations.
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 - if the level INFO is active:
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_err(), is_crit() and is_emerg() are just shortcuts.
is_err()
is_crit()
is_emerg()
Fatal is a extra level 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 activate this level.
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()
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; # do something with $error_string }
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 output configuration from a file.
$log->config(filename => 'file.conf');
$log->config(config => { file => { default => { newline => 1, debug_mode => 2, die_on_errors => 0 }, error_log => { filename => 'error.log', maxlevel => 'warning', minlevel => 'emerg', priority => 1 }, common_log => { filename => 'common.log', maxlevel => 'info', minlevel => 'emerg', priority => 2 }, } });
The default section - I call it section here - can be used to define default parameters for all file outputs.
Take a look into the documentation of Log::Handler::Config for more informations.
With this option you can set your own placeholders. Example:
$log->set_pattern('%X', 'name', sub { }); # or $log->set_pattern('%X', 'name', 'value');
Then you can use this pattern in your message layout:
$log->add(forward => { filename => 'file.log', message_layout => '%X %m', });
A long time I was thinking about to implement the functionality to carp(), croak(), exit() or whatever over the logger. The one big adventage would be that the programer don't need to think about selfmade implementations and could use pre-defined methods like
carp()
croak()
exit()
$log->error_and_die() # or $log->fatal_and_croak() # or $log->info_and_exit() # and so on
The list would be very, very long to show all possibilities... but would these methods really bring an advantage? I think not! If you really want to snap all errors and warnings - maybe from a other module you use - then there is no way except you write your own die or warn handler:
$SIG{__WARN__} = sub { $log->warn(@_) } $SIG{__DIE__} = sub { $log->error(@_) }
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->warning("this is a warning"); $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");
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 [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; my $log = Log::Handler->new(); $log->add(dbi => { # database connection database => 'database', driver => 'mysql', user => 'user', password => 'password', host => '127.0.0.1', port => 3306, debug => 1, table => 'messages', columns => [ qw/level ctime cdate pid hostname caller progname mtime message/ ], values => [ qw/%level %time %date %pid %hostname %caller %progname %mtime %message/ ], persistent => 1, reconnect => 1, maxlevel => 'error', minlevel => 'emerg' }); $log->error("this error goes to the database");
use Log::Handler; my $log = Log::Handler->new(); $log->add(email => { host => 'mx.bar.example', hello => 'EHLO my.domain.example', timeout => 120, debug => 1, from => 'bar@foo.example', to => 'foo@bar.example', subject => 'your subject', buffer => 100, interval => 60, maxlevel => 'error', minlevel => 'emerg', }); $log->error($message);
use Log::Handler; my $log = Log::Handler->new(); $log->add(forward => { forward_to => \&my_func, message_pattern => [ qw/%L %T %P %H %C %p %t/ ], message_layout => '%m', maxlevel => 'info', }); $log->info('Hello World!'); sub my_func { my $params = shift; print Dumper($params); }
use Log::Handler; my $log = Log::Handler->new(); $log->add(forward => { log_to => 'STDERR', dump => 1, message_pattern => [ qw/%L %T %P %H %C %p %t/ ], message_layout => '%m', maxlevel => 'info', }); $log->info('Hello World!');
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, }); $log->add(file => { filename => 'common.log', mode => 'append', maxlevel => 6, minlevel => 5, }); $log->add(file => { filename => 'error.log', mode => 'append', maxlevel => 4, minlevel => 0, }); # 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 to error.log $log->warning("this is a warning"); $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");
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!
Start it or write me a mail if you have questions.
Prerequisites for all modules:
Carp Data::Dumper Devel::Backtrace Fcntl Net::SMTP Params::Validate POSIX Time::HiRes Sys::Hostname UNIVERSAL::require
And maybe for the config loader:
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.
Maybe; don't know
* Log::Handler::Output::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.