Log::Report(3pm)
๐ Log::Report(3pm) ๐
okay bestie, welcome to the manual page for Log::Report โ it's user-contributed Perl documentation, section 3pm, and it's literally the moment. This module is giving main character energy for reporting problems, throwing exceptions, and doing translation support. No cap. ๐ซถ
โจ NAME โจ
Log::Report โ report a problem, with exceptions and translation support
๐งฌ INHERITANCE ๐งฌ
Log::Report is an Exporter
๐ SYNOPSIS ๐
# Invocation with 'mode' to get trace and verbose messages
use Log::Report mode => 'DEBUG';
# Usually invoked with a domain, which groups packages for translation
use Log::Report 'my-domain', %options;
# Interpolation syntax via String::Print
# First step to translations, once you need it.
print __x"my name is {name}", name => $n; # print, so no exception
print __"Hello World\n"; # no interpolation, optional translation
print __x'Hello World'; # SYNTAX ERROR: quote is alternative for ::
# Functions replacing die/warn/carp, casting exceptions but not message
# objects and no translation support.
error "oops"; # exception like die(), no translation
-f $config or panic "Help!"; # alert/error/fault/info/...more
# Combined exception, interpolation, and optional translation
error __x"Help!"; # __x() creates ::Message object
error __x('gettext msgid', param => $value, ...)
if $condition;
# Also non fatal "exceptions" find their way to dispatchers
info __x"started {pid}", pid => $$; # translatable
debug "$i was here!"; # you probably do not want to translate debug
panic "arrghhh"; # like Carp::Confess
# Many destinations for an exception message (may exist in parallel)
dispatcher PERL => 'default', # see Log::Report::Dispatcher: use die/warn
reasons => 'NOTICE-'; # this dispatcher is already present at start
dispatcher SYSLOG => 'syslog' # also send to syslog,
charset => 'iso-8859-1', # explicit character conversions
locale => 'en_US'; # overrule user's locale
dispatcher close => 'default' # stop default die/warn dispatcher
# Fill-in values, like Locale::TextDomain and gettext
# See Log::Report::Message section DETAILS
fault __x"cannot allocate {size} bytes", size => $size;
fault "cannot allocate $size bytes"; # no translation, ok
fault __x"cannot allocate $size bytes"; # not translatable, wrong
# Output (optionally with translation) depending on count
# Leading and trailing whitespace stay magically outside translation
# tables. @files in scalar context. Special parameter with _
print __xn"found one file\n", "found {_count} files", @files;
# Borrow from an other text-domain (see Log::Report::Message)
print __x(+"errors in {line}", _domain => 'global', line => $line);
# catch errors (implements hidden eval/die)
try { error };
if($@) {...} # $@ isa Log::Report::Dispatcher::Try
if(my $exception = $@->wasFatal) # ::Exception object
# Language translations at the output component
# Translation management via Log::Report::Lexicon
use POSIX::1003::Locale qw/setlocale LC_ALL/;
setlocale(LC_ALL, 'nl_NL');
info __"Hello World!"; # in Dutch, if translation table found
# Exception classes, see Log::Report::Exception
try { error __x"something", _tags => 'parsing,schema' };
if($@->wasFatal->taggedWith('parsing')) ...
๐ DESCRIPTION ๐
okay so the whole point of Log::Report is to get messages to users and logs. It combines three tasks that are, like, super closely related in one:
- logging (like
Log::Log4Perlandsyslog), and - exceptions (like
'error'and'info'), with - translations (like
"gettext"andLocale::TextDomain)
You do not need to use this module for all three reasons โ pick what you need now, maybe extend the usage later. That's the vibe. Read more about how and why in the "DETAILS" section, below. Especially, you should read about the REASON parameter. It's important, bestie. ๐
Also, you can study this module swiftly via the article published in the German Perl $foo-magazine. English version: https://perl.overmeer.net/log-report/papers/201306-PerlMagazine-article-en.html
๐ ๏ธ FUNCTIONS ๐ ๏ธ
๐ฌ Report production and configuration ๐ฌ
dispatcher( <$type, $name, %options>|<$command, @names> )
The dispatcher function controls access to dispatchers: the back-ends which process messages, do the logging. Dispatchers are global entities, addressed by a symbolic $name. Please read Log::Report::Dispatcher as well.
The Log::Report suite has its own dispatcher types, but also connects to external dispatching frameworks. Each need some (minor) conversions, especially with respect to translation of REASONS of the reports into log-levels as the back-end understands.
[1.10] When you open a dispatcher with a $name which is already in use, that existing dispatcher gets closed. Except when you have given an 'dispatcher "do-not-reopen"' earlier, in which case the first object stays alive, and the second attempt ignored. [1.11] The automatically created default dispatcher will get replaced, even when this option is given, by another dispatcher which is named 'default'.
The %options are a mixture of parameters needed for the Log::Report dispatcher wrapper and the settings of the back-end. See Log::Report::Dispatcher, the documentation for the back-end specific wrappers, and the back-ends for more details.
Implemented COMMANDs are "close", "find", "list", "disable", "enable", "mode", "filter", "needs", "active-try", and "do-not-reopen".
Most commands are followed by a LIST of dispatcher @names to be addressed. For "mode" see section "Run modes"; it requires a MODE argument before the LIST of NAMEs. Non-existing names will be ignored. When "ALL" is specified, then all existing dispatchers will get addressed. For "filter" see "Filters" in Log::Report::Dispatcher; it requires a CODE reference before the @names of the dispatchers which will have the it applied (defaults to all).
With "needs", you only provide a REASON: it will return the list of dispatchers which need to be called in case of a message with the REASON is triggered. The "active-try" [1.09] returns the closest surrounding exception catcher, a Log::Report::Dispatcher::Try object.
For both the creation as COMMANDs version of this method, all objects involved are returned as LIST, non-existing ones skipped. In SCALAR context with only one name, the one object is returned.
ยป example: play with dispatchers
dispatcher Log::Dispatcher::File => mylog =>,
accept => 'MISTAKE-', # for wrapper
locale => 'pt_BR', # other language
filename => 'logfile'; # for back-end
dispatcher close => 'mylog'; # cleanup
my $obj = dispatcher find => 'mylog';
my @obj = dispatcher 'list';
dispatcher disable => 'syslog';
dispatcher enable => 'mylog', 'syslog'; # more at a time
dispatcher mode => 'DEBUG', 'mylog';
dispatcher mode => 'DEBUG', 'ALL';
my $catcher = dispatcher 'active-try';
dispatcher 'do-not-reopen';
my @need_info = dispatcher needs => 'INFO';
if(dispatcher needs => 'INFO') ... # anyone needs INFO
# Getopt::Long integration: see Log::Report::Dispatcher::mode()
dispatcher PERL => 'default', mode => 'DEBUG', accept => 'ALL'
if $debug;
report( [\%options], $reason, $message|<$text,%params>, )
The report function is sending (for some $reason) a $message to be displayed or logged (by a dispatcher). This function is the core for error(), info() etc functions, which are nicer names for this exception throwing: better use those short names.
The optional %options are listed below. Quite differently from other functions and methods, they have to be passed in a HASH as first parameter. So not like, "oh just pass them normally", okay? Hash first. ๐
The $reason is a string like 'ERROR' (for function error()). The $message is a Log::Report::Message object (which is created with the special translation syntax like __x()).
The message may also be a plain piece of $text, or a Log::Report::Exception object. The %params can be used to influence the dispatchers, like real message objects can.
This function returns the LIST of dispatchers which accepted the $message. When empty, no back-end has accepted it so the $message was "lost". Even when no back-end needs the message, the program will still exit when there is a $reason to die().
-Option --Default
errnoโ default$! or 1is_fatalโ default<depends on reason>localeโ defaultundeflocationโ defaultundefstackโ defaultundeftoโ defaultundeferrno=> INTEGER โ When the$reasonincludes the error text (See"Run modes"), you can overrule the error code kept in$!. In other cases, the return code defaults to1(historical UNIX behavior). When the message$reason(combined with the run-mode) is severe enough to stop the program, this value as return code of the program. The use of this option itself will not trigger andie().is_fatal=> BOOLEAN โ Some logged exceptions are fatal, other aren't. The default usually is correct. However, you may want an error to be caught (usually withtry()), redispatch it to syslog, but without it killing the main program.locale=> $locale โ Use this specific$locale, in stead of the user's preference.location=> $location โ When defined, this location is used in the display. Otherwise, it is determined automatically if needed. An empty string will disable any attempt to display this line.stack=> @trace โ When defined, that data is used to display the call stack. Otherwise, it is collected viacaller()if needed.to=> $name|@names โ Sent the$messageonly to the named dispatchers. Ignore unknown@names. Still, the dispatcher needs to be enabled and accept the$reason.
ยป example: for use of report()
# long syntax example
report TRACE => "start processing now";
report INFO => '500: ' . __'Internal Server Error';
# explicit dispatcher, no translation
report {to => 'syslog'}, NOTICE => "started process $$";
notice "started process $$", _to => 'syslog'; # same
# short syntax examples
trace "start processing now";
warning __x'Disk {percent%.2f}% full', percent => $p
if $p > 97;
# error message, overruled to be printed in Brazilian
report {locale => 'pt_BR'},
WARNING => "do this at home!";
๐ซถ try(CODE, %options)
Okay so bestie, try runs your CODE and blocks every single dispatcher for as long as that code is running. Any exceptions that pop off while the CODE is going get caught until it's finished. And when there were no fatal errors, you get the result of the CODE execution handed right back to you. ๐
Once the CODE was tried, $@ is gonna hold a Log::Report::Dispatcher::Try object, and that object has all the collected messages inside it. Read that manual page to actually understand try, fr fr.
Run-time errors from Perl and dies, croaks and confesss within the program (which shouldn't appear, but you never know ๐ญ) get collected into an Log::Report::Message object, using Log::Report::Die.
The %options get passed to the constructor of the try-dispatcher, see Log::Report::Dispatcher::Try::new(). So like, you may want to add mode => 'DEBUG', or accept => 'ERROR-'. ๐
โ ๏ธ Be warned bestie that the parameter totryis aCODEreference. That means you shall not use a comma after the block when there are%optionsspecified. On the other hand, you shall use a semi-colon after the block if there are no arguments. The duality. The drama. ๐
โ ๏ธ Also be warned that the{}gets interpreted as a subroutine, which means โ for instance โ it has its own@_parameter list. The manual page ofTry::Tinylists a few more side-effects of this, iykyk.
ยป example:
my $x = try { 3/$x }; # mind the ';' !!
if($@) { # signals something went wrong
if(try {...}) { # block ended normally, returns bool
try { ... } # no comma!!
mode => 'DEBUG', accept => 'ERROR-';
try sub { ... }, # with comma, also \&function
mode => 'DEBUG', accept => 'ALL';
my $response = try { $ua->request($request) };
if(my $e = $@->wasFatal) ...
โจ Abbreviations for report() โจ
All of these functions below are just wrappers for calls to report(), and they're available when syntax is SHORT (by default, see import()). You can't specify additional options to influence the behavior of report() โ which honestly isn't usually needed anyway. ๐
alert($message)โ short forreport ALERT => $messageassert($message)โ short forreport ASSERT => $messageerror($message)โ short forreport ERROR => $messagefailure($message)โ short forreport FAILURE => $messagefault($message)โ short forreport FAULT => $messageinfo($message)โ short forreport INFO => $messagemistake($message)โ short forreport MISTAKE => $messagenotice($message)โ short forreport NOTICE => $messagepanic($message)โ short forreport PANIC => $messagetrace($message)โ short forreport TRACE => $messagewarning($message)โ short forreport WARNING => $message
๐ธ Messages (optionally translatable)
Even when you don't support translations (yet) you may still want to use message objects to level up the logging. Like, you get very powerful interpolation from String::Print. Obsessed. ๐
The language translations get initiated by a limited set of functions which contain two under-scores (__) in their name. Most of them return a Log::Report::Message object.
โ ๏ธ Be warned(1) that โ in general โ it's considered very bad practice to combine multiple translations into one message: translating may also affect the order of the translated components. Besides, when the person who translates only sees smaller parts of the text, their job becomes more complex. So:
print __"Hello" . ', ' . __"World!"; # works, but to be avoided
print __"Hello, World!"; # preferred, complete sentence
The the former case, tricks with overloading used by the Log::Report::Message objects will still make delayed translations work.
In normal situations, it's not a problem to translate interpolated values:
print __"the color is {c}", c => __"red";
โ ๏ธ Be warned(2) that using__'Hello'will produce a syntax error likeString found where operator expected at .... Can't find string terminator "'" anywhere before EOF. The first quote is the cause of the complaint, but the second one generates the error. In the early days of Perl, the single quote was used to separate package name from function name โ a role which was later replaced by a double-colon. So__'Hello'gets interpreted as__::Hello '. Then there's a trailing single quote which has no counterpart. Messy bestie. ๐
N__($msgid)
Label to indicate that the string is a text which will be translated later. The function itself does nothing. See also N__w().
This no-op function is used as label to the xgettext program to build the translation tables.
ยป example: how to use N__()
# add three msgids to the translation table
my @colors = (N__"red", N__"green", N__"blue");
my @colors = N__w "red green blue"; # same
print __ $colors[1]; # translate green
# using __(), would work as well
my @colors = (__"red", __"green", __"blue");
print $colors[1];
# however: this will always create all Log::Report::Message objects,
# where maybe only one is used.
N__n($single_msgid, $plural_msgid)
Label to indicate that the two MSGIDs are related โ the first as single, the seconds as its plural. Only used to find the text fragments to be translated. The function itself does nothing.
ยป example: how to use N__n()
my @save = N__n "save file", "save files";
my @save = (N__n "save file", "save files");
my @save = N__n("save file", "save files");
# be warned about SCALARs in prototype!
print __n @save, $nr_files; # wrong!
print __n $save[0], $save[1], @files, %vars;
N__w($string)
This extension to the Locale::TextDomain syntax is a combined qw (list of quoted words) and N__() into a list of translatable words. ๐ฆ
ยป example: of N__w()
my @colors = (N__"red", N__"green", N__"blue");
my @colors = N__w"red green blue"; # same
print __ $colors[1];
__($msgid)
This function (name is two under-score characters) will cause the $msgid to be replaced by the translations when doing the actual output. What you get back is a Log::Report::Message object, which will be used in translation later. Translating gets invoked when the object gets stringified. When you have no translation tables, the $msgid will just show up untranslated.
If you need options for Log::Report::Message::new() then use __x(); the prototype of this function does not permit parameters: it's a prefix operator!
ยป example: how to use __()
print __"Hello World"; # translated into user's language
print __'Hello World'; # syntax error!
print __('Hello World'); # ok, translated
print __"Hello", " World"; # World not translated
my $s = __"Hello World"; # creates object, not yet translated
print ref $s; # Log::Report::Message
print $s; # ok, translated
print $s->toString('fr'); # ok, forced into French
__n($msgid, $plural_msgid, $count, PAIRS)
It depends on the value of $count (and the selected language) which text will get displayed. When translations can't be performed, then $msgid will be used when $count is 1, and PLURAL_MSGSID in other cases. However, some languages have more complex schemes than English. ๐
The PAIRS are options for Log::Report::Message::new() and variables to be filled in.
ยป example: how to use __n()
print __n "one", "more", $a;
print __n("one", "more", $a), "\n";
print +(__n "one", "more", $a), "\n";
# new-lines are ignore at lookup, but printed.
print __n "one\n", "more\n", $a;
# count is in scalar context
# the value is also available as _count
print __n "found one\n", "found {_count}\n", @r;
# ARRAYs and HASHes are counted
print __n "one", "more", \@r;
__nx($msgid, $plural_msgid, $count, PAIRS)
It depends on the value of $count (and the selected language) which text will get displayed. See details in __n(). After translation, the VARIABLES will be filled-in.
The PAIRS are options for Log::Report::Message::new() and variables to be filled in.
ยป example: how to use __nx()
print __nx "one file", "{_count} files", $nr_files;
print __nx "one file", "{_count} files", @files;
local $" = ', ';
print __nx "one file: {f}", "{_count} files: {f}", @files, f => \@files;
__x($msgid, PAIRS)
Translate the $msgid and then interpolate the VARIABLES in that string. Of course, translation and interpolation is delayed as long as possible. Both OPTIONS and VARIABLES are key-value pairs.
The PAIRS are options for Log::Report::Message::new() and variables to be filled in.
ยป example: how to use __x()
This is by far the most used message constructor.
print __x"Name {person.name}", person => $person_obj;
error __x"Too many options: max 5, got {count}", count => $c;
fault __x"Cannot open file {f}", f => $input_filename;
__xn($single_msgid, $plural_msgid, $count, $paurs)
Same as __nx(), because we have no preferred order for 'x' and 'n'. โจ
๐ Messages with Context
In Log::Report, the message context (mgsctxt in the PO-files โ in the translation tables) can be used in a very powerful way. Read all about it in Log::Report::Translator::Context. ๐
The msgctxt versions of the tranditional gettext infrastructure are far less useful for Log::Report, because we can easily work with different text domains within the same program. That should avoid most of the accidental translation conflicts between components of the code.
Just for compatibility with Locale::TextDomain and completeness, the 'p' versions of above methods are supported. See examples for these functions in Locale::TextDomain. ๐
โ ๏ธ Warnings: FunctionsN__p()andN__np()seem not to be usable in reality, hence not implemented. The scriptxgettext-perlandLog::Report::Extract::PerlPPI(both in theLog::Report::Lexicondistribution) do not yet support these functions.
__np($msgctxt, $msgid, $plural, count)__npx($msgctxt, $msgid, $plural, count, PAIRS)__p($msgctxt, $msgid)__px($msgctxt, $msgid, PAIRS)
๐ Configuration
default_dispatcher_mode()
[1.46] Returns the default run mode.
The import gets called automatically when the package is compiled, bestie โ you literally don't do anything, it just โจhappensโจ. For every package in your distro except one, it's only gonna hold the name of the $domain. That's it. That's the whole job.
For that one package, though, the import list can also carry textdomain configuration %options. And those %options get used by all the packages sharing the same $domain. Here are your two alternatives, pick your fighter:
# Do not use variables in the %*config! They are not yet initialized
# when Log::Report->import is run!!!
use Log::Report 'my-domain', %config, %domain_config;
use Log::Report 'my-domain', %config;
textdomain 'my-domain', %domain_config; # vars allowed
โ ๏ธ real talk: do not use variables in the%*config! They are not yet initialized whenLog::Report->importis run. That's not a vibe, that's a bug waiting to happen. ๐ญ
The second syntax has major advantages when the configuration of the domain is only determined at run-time. It's probably also easier to understand. ๐ซถ
Go peek at Log::Report::Domain::configure() for the list of %options for the domain configuration. Over here, we're only listing the options related to the normal import behavior.
So the $level export is a plus (+) followed by a number, like +1, and it tells us which caller level we need to work at. This is used in Log::Report::Optional. Defaults to '0': my direct caller. ๐
The defaults, since I know you were gonna ask:
importโundefmessage_classโLog::Report::Messagemodeโ'NORMAL'syntaxโ'SHORT'
And now, option by option:
import=>$function|\@functionsโ [0.998] When you don't specify it, thesyntaxoption is what decides the list of@functionsbeing exported. Once you do pass this option,syntaxgets ignored and only the@functionsyou named are imported. ๐message_class=>CLASSโ [1.08] Wanna use a more powerful message object class? Say, because your messages need extra attributes? Say less. TheCLASSyou hand over must extendLog::Report::Message. ๐ฆmode=>LEVELโ This sets the default mode for all created dispatchers. You can also selectively change the output mode, like:
dispatcher PERL => 'default', mode => 3
syntax=>'REPORT'|'SHORT'|'LONG'โ TheSHORTsyntax will drop the report abbreviations (like the functionerror()) right into your name-space. Otherwise, every message has to be produced withreport()."LONG"is an alternative to"REPORT": both of them keep your namespace un-polluted by those useful abbrev functions. ๐
ยป example: of import
use Log::Report mode => 3; # '3' or 'DEBUG', no domain given
use Log::Report 'my-domain'; # in each package producing messages
use Log::Report 'my-domain', # in one package, top of distr
mode => 'VERBOSE',
syntax => 'REPORT', # report ERROR, not error()
translator => Log::Report::Translator::POT->new(
lexicon => '/home/mine/locale', # translation tables
),
native_language => 'nl_NL'; # untranslated msgs are Dutch
use Log::Report import => 'try'; # or ARRAY of functions
๐ textdomain( <[$name],$config>|<$name, 'DELETE'|'EXISTS'>|$domain ) ๐
[1.00] No CONFIGuration? Then this returns the Log::Report::Domain object which administers the $domain โ by default, the domain effective in the scope of the package.
Now for a very special case: ""DELETE"", which will remove the domain configuration. [1.20] And ""EXISTS""? That checks for existence: when it exists, it gets returned, but a domain will not be automagically created. ๐ธ
[1.20] You may also pass a pre-configured domain. Periodt.
๐ Reasons ๐
$class->needs( $reason, [$reasons] )
Returns "true" when the reporter needs any of the $reasons โ like, when any of the active dispatchers is collecting messages in the specified level. This is so handy when the processing of data for the message is relatively expensive, but is for instance only required in debug mode. ๐ฎโ๐จ
ยป example:
if(Log::Report->needs('TRACE'))
{ my @args = ...expensive calculation...;
trace "your options are: @args";
}
๐ DETAILS ๐
โจ Introduction โจ
Getting messages to users and to logs. The concept that makes this module distinct is that three strongly related tasks get merged into one simple syntax. Those three tasks:
- produce some text on a certain condition,
- translate it to the proper language, and
- deliver it in some way to a user.
Text messages in Perl are produced by commands like print, die, warn, carp, or croak. But, like... where is that output even directed to? ๐ญ Translations are hard. There's no clean exception mechanism. And on top of all that, print/warn/die together give you only three different output "levels" for a message. Think about the variation syslog offers: more than 7 levels. Tons of people manually implement their own little tricks to get extra levels, like verbose and debug flags. Log::Report gives you that variety for free, no cap. ๐
The (optional) translations use the beautiful syntax defined by Locale::TextDomain, with some of our own extensions (of course ๐
). A very important difference is that translations are delayed till the delivery step: not until a dispatcher actually writes your message into a file, sends it to syslog, or shows it on the screen. Which means the pop-up in the user's graphical interface can show the text in the user's language โ say Chinese in utf8 โ while at the same time syslog writes the latin1 English version of the same message. Iconic, honestly. ๐ฆ
๐ชถ Lightweight Log::Report::Optional
When you want to use Log::Report features as cheaply as possible, you may use Log::Report::Optional in your module. In that case, your module can use error() and "__x()" at very little cost: they will not build internal objects and support translations. It's fast, and it has few dependencies. ๐
The beauty is: when the main program that uses your module does initiate the full Log::Report functionality, then your module will also switch to full support mode. Main character energy from a tiny module, honestly. โจ
๐ง Background ideas
The following ideas are the base of this implementation:
- simplification โ Handling errors and warnings is probably the most labor-intensive task for a programmer: when programs are written correctly, up-to three-quarters of the code is related to testing, reporting, and handling (problem) conditions. Simplifying the way to create reports simplifies programming and maintenance. ๐
- multiple dispatchers โ It is not the location where the (for instance) error occurs which determines what will happen with the text; instead, the main application which uses the the complaining module has control. Messages have a reason. Based on the
reason' classification, they can get ignored, or sent to one or multiple dispatchers, likeLog::Dispatch,Log::Log4perl`, or UNIX syslog. ๐ฅ - delayed translations โ The background ideas are that of
Locale::TextDomain, based ongettext(). However, in theLog::Reportinfrastructure, translations are postponed until the text is dispatched to a screen or log-file; the same report can be sent to syslog in (for instance) English and to the user interface in Dutch. ๐ - context sensitive โ Using contexts, you can set-up how to translate or rewrite messages, to improve messages. A typical problem is whether to use gender in text (use
'his'or'her'): you can set a gender in a context, and use translation tables to pick the right one. ๐
๐ตโ๐ซ Error handling models
There are two approaches to handling errors and warnings. In the first approach, as produced by die, warn and the carp family of commands, the program handles the problem immediately, right on the location where the problem appears. In the second approach, an exception is thrown on the spot where the problem is created, and then somewhere else in the program the condition gets handled.
The implementation of exceptions in Perl5 is done with a eval-die pair: on the spot where the problem occurs, die is called. But because the execution of that routine is placed within an eval, the program as a whole will not die โ just the execution of a part of the program will seize. But hmm, what if the condition which caused the routine to die is solvable on a higher level? ๐ค Or what if the user of the code doesn't even care that a part fails, because it has implemented alternatives for that situation? Exception handling is, ngl, quite clumsy in Perl5.
The Log::Report set of distributions lets modules concentrate on the program flow, and lets the main program decide on the report handling model. The infrastructure to translate messages into multiple languages, whether to create exceptions or carp/die, to collect longer explanations with the messages, to log to mail or syslog, and so on โ all of that is decided in pluggable back-ends. Chefs kiss. ๐
๐ The Reason for the report
Traditionally, perl has a very simple view on error reports: you either have a warning or an error. But it would be so much clearer for users and module-using applications if a distinction were made between the various causes. For instance, a configuration error is a completely different beast from a disk-full situation. In Log::Report, the produced reports in the code tell you what is wrong. The main application defines loggers, which interpret the cause into (syslog) levels. ๐
Defined by Log::Report are:
trace(debug, program) โ The message will be used when some logger has debugging enabled. These messages show steps taken by the program, which are of interest to the developers and maintainers of the code, but not for end-users. ๐assert(program) โ Shows an unexpected condition, but continues to run. When you want the program to abort in such a situation, that's a job forpanic. ๐info(verbose, program) โ These messages show larger steps in the execution of the program. Experienced users of the program usually do not want to see all these intermediate steps. Most programs will display info messages (and higher) when someverboseflag is given on the command-line. ๐notice(program) โ A user may need to be aware of the program's accidental smart behavior, for instance, that it initializes a lastingDesktopdirectory in your home directory. Notices should be sparse โ we're not spamming anyone. โwarning(program) โ The program encountered some problems, but was able to work around it by smart behavior. For instance, the program does not understand a line from a log-file, but simply skips the line. ๐ซถmistake(user)
Okay so when a user does something a lil wrong, but it's the kind of wrong your program can totally fix by being smart?? That's a mistake. Like, in some config file you can fill in "yes" or "no", but the user typed "yeah". The program interprets this as "yes", producing a mistake message as warning.
And honestly?? It is SO much nicer to tell someone that he/she made a mistake than to call that an error. Manners, bestie. ๐
error(user) โ the user did something wrong and it is not automatically correctable, or your program is not willing to correct it automatically for reasons of code quality. Classic example: an unknown option flag given on the command-line. These are configuration issues, and have no useful value in$!. The program will be stopped, usually before taken off. ๐fault(system) โ the program hit a situation where it has no work-around. Like a file cannot be opened to be written. The cause of that problem can be some user error (i.e. wrong filename), or external (you accidentally removed a directory yesterday ๐). In any case, the$!($ERRNO) variable is set here.alert(system) โ some external cause disturbs the execution of the program, but the program stays alive and will try to continue operation. For instance, the connection to the database is lost. After a few attempts, the database can be reached and the program continues as if nothing happened. Cause is external, so$!is set. Usually, a system administrator needs to be informed about the problem.failure(system) โ some external cause makes it impossible for this program to continue.$!is set, and usually the system administrator wants to be informed. The program will die.
The difference with "fault" is subtle and not always clear. A fault reports an error returned by an operating system call, where the failure would report an operational problem, like a failing mount.
panic(program) โ all the report classes above are expected: some predictable situation gets encountered, and therefore a message is produced. However, programs often do some internal checking. Of course, these conditions should never be triggered, but if they doโฆ then we can only stop. ๐ญ
For instance, in an OO perl module, the base class requires all sub-classes to implement a certain method. The base class will produce a stub method which triggers a panic when called. The non-dieing version of this test is "assert".
Okay but ngl, debugging or being "verbose"?? Those are run-time behaviors, and have nothing directly to do with the type of message which is produced. Those two are modes which can be set on the dispatchers: one dispatcher may be more verbose than some other.
On purpose, we do not use the terms "die" or "fatal", because the dispatcher can be configured what to do in cause of which condition. For instance, it may decide to stop execution on warnings as well.
The terms "carp" and "croak" are avoided too, because the program cause versus user cause distinction (warn vs carp) is reflected in the use of different reasons. There is no need for "confess" and "croak" either, because the dispatcher can be configured to produce stack-trace information (for a limited sub-set of dispatchers).
โจ Report level comparison โจ
Various frameworks used with perl programs define different labels to indicate the reason for the message to be produced. So here's the whole rosรฉ-all-day lineup, side by side, no cap:
Perl5 Log::Dispatch Syslog Log4Perl Log::Report
print 0,debug debug debug trace
print 0,debug debug debug assert
print 1,info info info info
warn\n 2,notice notice info notice
warn 3,warning warn warn mistake
carp 3,warning warn warn warning
die\n 4,error err error error
die 5,critical crit fatal fault
croak 6,alert alert fatal alert
croak 7,emergency emerg fatal failure
confess 7,emergency emerg fatal panic
Spot the warn\n vs warn glow-up ๐ iconique.
๐ Run modes ๐
The run-mode changes which messages are passed to a dispatcher โ that's the verbosity. It takes a different angle than the dispatch filters: the mode changes behavioral aspects of the messages, which are described in detail in "Processing the message" in Log::Report::Dispatcher. However, it should behave as you expect: the DEBUG mode shows more than the VERBOSE mode, and both show more than the NORMAL mode. Periodt.
ยป Example: extract run mode from Getopt::Long
The GetOptions() function will count the number of "v" options on the command-line when a "+" is after the option name.
use Log::Report;
use Getopt::Long qw(:config no_ignore_case bundling);
my $mode; # defaults to NORMAL
GetOptions 'v+' => \$mode,
'verbose=i' => \$mode,
'mode=s' => \$mode
or exit 1;
dispatcher 'PERL', 'default', mode => $mode;
So now -vv will set $mode to 2, and so will --verbose 2, --verbose=2 and --mode=ASSERT. Of course, you do not need to provide all these options to the user: make a choice. Slay.
ยป Example: the mode of a dispatcher
my $mode = dispatcher(find => 'myname')->mode;
ยป Example: run-time change mode of a dispatcher
To change the running mode of the dispatcher, you can do
dispatcher mode => DEBUG => 'myname';
However, be warned that this does not change the types of messages accepted by the dispatcher! So: probably you will not receive the trace, assert, and info messages after all. So, probably you need to replace the dispatcher with a new one with the same name:
dispatcher FILE => 'myname', to => ..., mode => 'DEBUG';
This may reopen connections (depends on the actual dispatcher), which might be not what you wish to happened. In that case, you must take the following approach:
# at the start of your program, overrule the default 'NOTICE-' !!
dispatcher FILE => 'myname', to => ..., accept => 'ALL';
# now it works
dispatcher mode => DEBUG => 'myname'; # debugging on
...
dispatcher mode => NORMAL => 'myname'; # debugging off
Of course, this comes with a small overall performance penalty. ๐ธ
๐ Exceptions ๐
The simple view on life says: you're dead when you die. However, more complex situations try to revive the dead. Typically, the "die" is considered a terminating exception, but not terminating the whole program โ only some logical block. Of course, a wrapper round that block must decide what to do with these emerging problems.
Java-like languages do not "die" but throw exceptions which contain the information about what went wrong. Perl modules like "Exception::Class" simulate this. It's a hassle to create exception class objects for each emerging problem, and the same amount of work to walk through all the options. ๐ฎโ๐จ
Log::Report follows a simpler scheme. Fatal messages will "die", which is caught with "eval", just the Perl way (used invisible to you). However, the wrapper gets its hands on the message as the user has specified it: untranslated, with all unprocessed parameters still at hand.
try { fault __x "cannot open file {file}", file => $fn };
if($@) # is Log::Report::Dispatcher::Try
{ my $cause = $@->wasFatal; # is Log::Report::Exception
$cause->throw if $cause->message->msgid =~ m/ open /;
# all other problems ignored
}
See Log::Report::Dispatcher::Try and Log::Report::Exception.
๐ Interpolation via formats ๐
Interpolation via formats is optional.
In shown examples, you see "__x()" everywhere. Using that function is required when you wish to use translations (later in your project), but also has many other benefits. The functions "__x" and friends create a Log::Report::Message object. Iconic behaviour fr fr.
Continue reading:
- "Why use format strings?" in
Log::Report::Message - "Messages with plural forms" in
Log::Report::Message - "Interpolation with String::Print" in
Log::Report::Message - "Automatic parameters" in
Log::Report::Message
๐ฆ Translation ๐ฆ
Translating is optional. (Everything's optional, that's the vibe โจ)
Distribution Log::Report::Lexicon handles translations. It will help you manage all __x() (and friends) format strings in GNU's PO file format (https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html)
With Log::Report::Template, you can use Log::Report with translations in various website template systems.
Then, Dancer2::Plugin::LogReport brings Log::Report with exceptions and translations to the Dancer2 web framework. Queen behavior honestly ๐
โญ Compared to other solutions in Perl โญ
Some notes on differences between the Log::Report approach and other Perl concepts. Grab a snack bestie, we're comparing.
die/warn/Carp
Perl's built-in exception system is very primitive: "die" and "warn". Most programming languages provide a much more detailed exception mechanism.
A typical perl program can look like this:
my $dir = '/etc';
File::Spec->file_name is_absolute($dir)
or die "ERROR: directory name must be absolute.\n";
-d $dir
or die "ERROR: what platform are you on?";
until(opendir DIR, $dir)
{ warn "ERROR: cannot read system directory $dir: $!";
sleep 60;
}
print "Processing directory $dir\n"
if $verbose;
while(defined(my $file = readdir DIR))
{ if($file =~ m/\.bak$/)
{ warn "WARNING: found backup file $dir/$f\n";
next;
}
die "ERROR: file $dir/$file is binary"
if $debug && -B "$dir/$file";
print "DEBUG: processing file $dir/$file\n"
if $debug;
open my $fh, "<:encoding(UTF-8)", "$dir/$file"
or die "ERROR: cannot read from $dir/$f: $!";
$fh->close
or croak "ERROR: read errors in $dir/$file: $!";
}
Where "die", "warn", and "print" are used for various tasks. With "Log::Report", you would write
use Log::Report;
# can be left-out when there is no debug/verbose
dispatcher PERL => 'default', mode => 'DEBUG';
my $dir = '/etc';
File::Spec->file_name is_absolute($dir)
or mistake "directory name must be absolute";
-d $dir
or panic "what platform are you on?";
until(opendir DIR, $dir)
{ alert "cannot read system directory $dir";
sleep 60;
}
info "Processing directory $dir";
while(defined(my $file = readdir DIR))
{ if($file =~ m/\.bak$/)
{ notice "found backup file $dir/$f";
next;
}
assert "file $dir/$file is binary"
if -B "$dir/$file";
trace "processing file $dir/$file";
Ngl, a lot is <pink>visibly different</pink> here, and there's a handful of smaller glow-ups too. You don't need a newline after the text of the message (the old way made you type `\n` and it was giving 2010 energy, no cap). And when it applies โ like when it's an error about a system problem โ then `$!` gets added <mint>automatically</mint>. Bestie, that's the whole point. โจ
## ๐ Log::Dispatch and Log::Log4perl
The two big logging frameworks for Perl are `Log::Dispatch` and `Log::Log4perl`; both of them give you a pluggable logging interface. Iconic. Respect.
But here's the tea: both frameworks <red>do not have (gettext or maketext) language translation support</red>, and that has a whole bunch of consequences. The moment you want to report something in another language, it must be translated **before** the logging function is called. Which means an error message can get produced in Chinese, and therefore also ends up in the syslog file in Chinese. And if Chinese is not your languageโฆ <red>you have a problem</red>. ๐ญ
`Log::Report` translates only in the <purple>back-end</purple>, which means the user may get the message in Chinese, but **you** get your report in your beloved Dutch. And when no dispatcher needs to report the message at all, then no time is lost translating. Efficiency queen. ๐
With both logging frameworks, you use terminology comparable to syslog: the <hotpink>module programmer</hotpink> determines the seriousness of the error message, not the application which integrates multiple modules. This is the way perl programs usually work โ but it's often the cause for inconsequent user interaction. ๐คทโ๏ธ
## ๐ Locale::gettext and Locate::TextDomain
Both on GNU gettext based implementations can be used as translation frameworks. `Locale::TextDomain` syntax is supported, with quite some extensions. Go read the excellent documentation of `Locale::TextDomain` โ it's giving scholarly but make it cute. ๐ The only thing not supported is the tried access via `$__` and `%__`.
The main difference with these modules is <yellow>the moment when the translation takes place</yellow>. In `Locale::TextDomain`, an `__x()` will result in an immediate translation request via `gettext()`. `Log::Report`'s version of `__x()` will only <italic>capture</italic> what needs to be translated in an object. When the object is used in a print statement, only then the translation will take place. This is needed to offer ways to send different translations of the message to different destinations. ๐ฆ
To be able to postpone translation, objects are returned which <mint>stringify into the translated text</mint>. Main character behaviour, honestly.
---
## ๐ฉบ DIAGNOSTICS
Every single one of these, bestie. Deep breaths. ๐
- **`Error: a message object is reported with more parameters.`** โ cast by `report()`
- **`Error: even length parameter list for __x at $where`** โ cast by `__x()`
- **`Error: message_class $class does not extend $base`** โ cast by `import()`
- **`Error: no domain for configuration options in $fn line $line`** โ cast by `import()`
- **`Error: odd length parameter list with '$msg'.`** โ cast by `report()`
- **`Error: odd length parameter list with object '$msg'.`** โ cast by `report()`
- **`Error: only one dispatcher name accepted in SCALAR context.`** โ cast by `dispatcher()`. In SCALAR context, only one dispatcher name accepted. The `dispatcher()` method returns the `Log::Report::Dispatcher` objects which it has accessed. When multiple names where given, it wishes to return a LIST of objects, not the count of them.
- **`Error: syntax flag must be either SHORT or REPORT, not '$flag' in $fn line $line`** โ cast by `import()`
- **`Error: textdomain '$domain' for translator not defined`** โ cast by `import()`
- **`Error: the 'filter' sub-command needs a CODE reference.`** โ cast by `dispatcher()`
- **`Error: the 'needs' sub-command parameter '$need' is not a reason.`** โ cast by `dispatcher()`
- **`Error: token '$token' not recognized as reason.`** โ cast by `report()`
- **`Error: translator must be a $pkg object for $domain`** โ cast by `import()`
---
## ๐ SEE ALSO
This module is part of <purple>Log-Report version 1.46</purple>, built on <purple>June 16, 2026</purple>.
Website: `http://perl.overmeer.net/CPAN/` โ go lurk, it's worth it. ๐ธ
---
## ๐ LICENSE
For contributors see file `ChangeLog`.
This software is copyright (c) <yellow>2007-2026 by Mark Overmeer</yellow>. ๐
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Fr fr, that's the real deal. ๐ซถ
---
And that's a wrap on the whole page, bestie!! You just read `Log::Report(3pm)` in full โ from `perl v5.40.1`, dated `2026-07-05`. Genuinely iconic of you to make it all the way to the bottom. Go forth and report your errors with <rainbow>main character energy</rainbow>, translate at the back-end only, and remember: no dispatcher, no wasted translation time. Slay. ๐
โจ๐
๐ฆ where this page comes from
- ubuntu stonking: liblog-report-perl 1.46-1 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms