NAME

Log::ger::Manual::Tutorial::200_LoggingWithLogGer - Logging with Log::ger

VERSION

version 0.040.000

DESCRIPTION

LOGGING WITH LOG::GER

As shown in the previous post, logging with Log::ger is as simple as loading Log::ger with use Log::ger and then using one of the log_trace, log_debug, log_info, log_warn, log_error, log_fatal statements. These subroutines are the logger subroutines; there is one for each level. They accept a string:

log_warn("This is a log message");

or a sprintf template and one or more arguments (so in other words, it will do sprintf if there are two or more arguments):

log_warn("User %s does not exist", $user);
log_warn("HTTP status code %d, message %s, result structure %s",
         $code, $message, $res);
log_warn("Subroutine arguments(%s)", \@_);

In sprintf mode, data structure will automatically be dumped and undef will also be shown as <undef>.

In addition to the logger subroutines, there are also the level detection routines: log_is_trace, log_is_debug, log_is_info, log_is_warn, log_is_error, log_is_fatal. They are sometimes used if you want to do some complex logging:

if (log_is_trace()) {
    require Blah;
    my $x = Blah->new(foo=>1, bar=>2);
    log_trace("Blah is %s", $x->as_string);
}

OO-STYLE

Some other logging frameworks use OO-style, where you first request a logger object then log (or detect level) by calling methods on the logger object. You can do this with Log::ger too, although I personally do not recommend this except when wanting to customize category (will be explained in later posts):

use Log::ger (); # don't import log_* and log_is_* subroutines

my $log = Log::ger->get_logger;
$log->trace("blah");
if ($log->is_trace) {
    ...
}

The logger methods are named according to the level names (so there is no log_ prefix as in the subroutine version). The level detection methods are named is_LEVEL, e.g. is_trace, is_debug, and so on.

Why do I prefer procedural style? First, it's shorter to type and you can omit the parentheses:

log_warn "blah";
$log->warn("blah");

It's more convenient to convert a print or printf statement to logging statement, or vice versa.

Second, if you use subroutine form it's possible to use Log::ger::Plugin::OptAway to remove logging statements completely during run-time.

AUTHOR

perlancar <perlancar@cpan.org>

COPYRIGHT AND LICENSE

This software is copyright (c) 2022, 2020, 2019, 2018, 2017 by perlancar <perlancar@cpan.org>.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.