SYNOPSIS

 # Invocation with mode helps debugging
 use Log::Report mode => 'DEBUG';

 error "oops";                # like die(), no translation
 -f $config or panic "Help!"; # alert/error/fault/info/...more

 # Provide a name-space to use translation tables.  Like Locale::TextDomain
 use Log::Report 'my-domain';
 error __x"Help!";            # __x() handles translation
 print __x"my name is {name}", name => $fullname;
 print __x'Hello World';      # SYNTAX ERROR!!  ' is alternative for ::

 # Many destinations for message in parallel possible.
 dispatcher PERL => 'default' # See Log::Report::Dispatcher: use die/warn
   , reasons => 'NOTICE-';    # this disp. 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 => 'PERL';  # stop dispatching to die/warn

 # Produce an error, long syntax (rarely used)
 report ERROR => __x('gettext string', param => $param, ...)
     if $condition;

 # When syntax=SHORT (default since 0.26)
 error __x('gettext string', param => $param, ...)
     if $condition;

 # Overrule standard behavior for single message with HASH as
 # first parameter.  Only long syntax
 use Errno qw/ENOMEM/;
 use Log::Report syntax => 'REPORT';
 report {to => 'syslog', errno => ENOMEM}
   , FAULT => __x"cannot allocate {size} bytes", size => $size;

 # Avoid messages without report level for daemons
 print __"Hello World", "\n";  # only translation, no exception

 # 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
 fault __x "cannot allocate $size bytes";  # wrong, not static

 # translation depends on count.
 print __xn("found one file", "found {_count} files", @files), "\n";

 # catch errors (implements hidden eval/die)
 try { error };
 if($@) {...}      # $@ isa Log::Report::Dispatcher::Try

 # Language translations at the IO/layer
 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
 my $msg = __x"something", _class => 'parsing,schema';
 if($msg->inClass('parsing')) ...

DESCRIPTION

Handling messages directed to users can be a hassle, certainly when the same software is used for command-line and in a graphical interfaces (you may not now how it is used), or has to cope with internationalization; this modules tries to simplify this.

Log::Report combines

You do not need to use it for all three reasons: pick what you need now, maybe extend the usage later. Read more about how and why in the DETAILS section, below. Especially, you should read about the REASON parameter.

Also, you can study this module swiftly via the article published in the German Perl $foo-magazine. English version: http://perl.overmeer.net/log-report/papers/201308-PerlMagazine-article-en.html

DETAILS

Introduction

There are three steps in this story: produce some text on a certain condition, translate it to the proper language, and deliver it in some way to a user. Texts are usually produced by commands like print, die, warn, carp, or croak, which have no way of configuring the way of delivery to the user. Therefore, they are replaced with a single new command: report (with various abbreviations)

Besides, the print/warn/die together produce only three levels of reasons to produce the message: many people manually implement more, like verbose and debug. Syslog has some extra levels as well, like critical. The REASON argument to report() replace them all.

The translations use the beautiful syntax defined by Locale::TextDomain, with some extensions (of course). The main difference is that the actual translations are delayed till the delivery step. This means that the pop-up in the graphical interface of the user will show the text in the language of the user, say Chinese, but at the same time syslog may write the English version of the text. With a little luck, translations can be avoided.

Background ideas

The following ideas are the base of this implementation:

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 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 is 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 of 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. However, 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 bother that a part fails, because it has implemented alternatives for that situation? Exception handling is quite clumsy in Perl5.

The Log::Report set of distributions let modules concentrate on the program flow, and let 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, is decided in pluggable back-ends.

The Reason for the report

Traditionally, perl has a very simple view on error reports: you either have a warning or an error. However, it would be much clearer for user's and module-using applications, when a distinction is made between various causes. For instance, a configuration error is quite different from a disk-full situation. In Log::Report, the produced reports in the code tell what is wrong. The main application defines loggers, which interpret the cause into (syslog) levels.

Defined by Log::Report are

Debugging or being verbose are run-time behaviors, and have nothing directly to do with the type of message which is produced. These two are modes which can be set on the dispatchers: one dispatcher may be more verbose that 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, 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 levels

Various frameworks used with perl programs define different labels to indicate the reason for the message to be produced.

 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

Run modes

The run-mode change which messages are passed to a dispatcher, but from a different angle than the dispatch filters; the mode changes behavioral aspects of the messages, which are described in detail in Processing the message. However, it should behave as you expect: the DEBUG mode shows more than the VERBOSE mode, and both show more than the NORMAL mode.

» 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 syntax => 'SHORT';
 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;

Now, -vv will set $mode to 2, as will --verbose 2 and --verbose=2 and --mode=ASSERT. Of course, you do not need to provide all these options to the user: make a choice.

» 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
  dispatcher FILE => 'myname', to => ...
     , accept => 'ALL';    # overrule the default 'NOTICE-' !!

  # 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 live 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, but 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.

Comparison

die/warn/Carp

A typical perl5 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 FILE, "<", "$dir/$file"
         or die "ERROR: cannot read from $dir/$f: $!";

     close FILE
         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 syntax => 'SHORT';

 # 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";

     unless(open FILE, "<", "$dir/$file")
     {   error "no permission to read from $dir/$f"
             if $!==ENOPERM;
         fault "unable to read from $dir/$f";
     }

     close FILE
         or failure "read errors in $dir/$file";
 }

A lot of things are quite visibly different, and there are a few smaller changes. There is no need for a new-line after the text of the message. When applicable (error about system problem), then the $! is added automatically.

The distinction between error and fault is a bit artificial her, just to demonstrate the difference between the two. In this case, I want to express very explicitly that the user made an error by passing the name of a directory in which a file is not readable. In the common case, the user is not to blame and we can use fault.

A CPAN module like Log::Message is an object oriented version of the standard Perl functions, and as such not really contributing to abstraction.

Log::Dispatch and Log::Log4perl

The two major logging frameworks for Perl are Log::Dispatch and Log::Log4perl; both provide a pluggable logging interface.

Both frameworks do not have (gettext or maketext) language translation support, which has various consequences. When you wish for to report in some other language, it must be translated before the logging function is called. This may mean that an error message is produced in Chinese, and therefore also ends-up in the syslog file in Chinese. When this is not your language, you have a problem.

Log::Report translates only in the back-end, which means that the user may get the message in Chinese, but you get your report in your beloved Dutch. When no dispatcher needs to report the message, then no time is lost in translating.

With both logging frameworks, you use terminology comparable to syslog: the module programmer determines the seriousness of the error message, not the application which integrates multiple modules. This is the way perl programs usually work, but 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. Read the excellent documentation of Locale::Textdomain. Only the tried access via $__ and %__ are not supported.

The main difference with these modules is the moment when the translation takes place. In Locale::TextDomain, an __x() will result in an immediate translation request via gettext(). Log::Report's version of __x() will only capture 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 stringify into the translated text.