In times immemorial, logging with perl would involve writing code like this:
open(LOG, '>>', "$logfile") or die "$logfile: $!"; print LOG "$timestamp $message\n"; close(LOG);
Nowadays there are numerous modules that makes logging easier and more versatile. I’ll talk about Log::Dispatch, and the extension, Catalyst::Plugin::Log::Dispatch.
To use Log::Dispatch
my $log = Log::Dispatch->new();
$log->add(
Log::Dispatch::File->new(
name => 'file1',
min_level => 'debug',
filename => '/var/log/logfile'
)
);
$log->add(
Log::Dispatch::Screen->new(
name => 'screen',
min_level => 'warning',
)
);
$log->log( level => 'info', message => 'Nobody expects the Spanish Inquisition!' );
What that does is declaring two instances to handle logging: one to a file, and the other as standard output, each with its own rules of what gets logged. For example, the message above will be logged into a file but it won’t be printed onto the screen because the screen log only captures warnings and anything higher in level.
If you’re using catalyst and want to integrate them together then you can use Catalyst::Plugin::Log::Dispatch. It’s setup is largely identical, only it allows you to define the format that the log message will style in. For example:
MyApp->config->{ Log::Dispatch } = [
{
class => 'File',
name => 'file1',
min_level => 'debug',
filename => MyApp->path_to('debug.log'),
format => '[%p] %m %n',
},
{
class => 'Screen',
name => 'screen',
min_level => 'warning',
format => '[%p] %m %n',
},
];
...
$c->log->info( 'Nobody expects the Spanish Inquisition!' );
What gets outputted to the log will look like this:
[info] Nobody expects the Spanish Inquisition!
You can find more information for Log::Dispatch and Catalyst::Plugin::Log::Dispatch in CPAN.
