SYNOPSIS

 # Invocation with 'mode' to get trace and verbose messages
 use Log::Report mode => 'DEBUG';

 # Usually invoked with a domain, which groups packages
 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";     # (optional) translation, no interpolation
 print __x'Hello World';      # SYNTAX ERROR!!  ' is alternative for ::

 # Functions replacing die/warn/carp, casting exceptions.
 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

 # 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", _class => 'parsing,schema' };
 if($@->wasFatal->inClass('parsing')) ...

DESCRIPTION

Get messages to users and logs. Log::Report combines three tasks which are closely related in one:

You do not need to use this module 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/201306-PerlMagazine-article-en.html

DETAILS

Introduction

Getting messages to users and logs. The distincting concept of this module, is that three tasks which are strongly related are merged into one simple syntax. The three tasks:

Text messages in Perl are produced by commands like print, die, warn, carp, or croak. But where is that output directed to? Translations is hard. There is no clean exception mechanism.

Besides, the print/warn/die together produce only three different output "levels" with a message. Think of the variation syslog offers: more than 7 levels. Many people manually implement their own tricks to get additional levels, like verbose and debug flags. Log::Report offers that variety.

The (optional) translations use the beautiful syntax defined by Locale::TextDomain, with some own extensions (of course). A very important difference is that translations are delayed till the delivery step: until a dispatcher actually writes your message into a file, sends it to syslog, or shows it on the screen. This means that the pop-up in the graphical interface of the user may show the text in the language of the user --say Chinese in utf8--, but at the same time syslog may write the latin1 English version of the same message.

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

 # 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.

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.