Log::D...:Config(3pm)

πŸ“¦
version 1.04 Β· 5 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– Log::Dispatch::Config πŸ’–

okay bestie, welcome to Log::Dispatch::Config β€” she's from the Log::Dispatch::Config section of the User Contributed Perl Documentation (that's the 3pm manual, iykyk), and she is literally Log4j for Perl. no cap. πŸ’…


✨ NAME ✨

Log::Dispatch::Config β€” it's giving Log4j, but for Perl 🫢


🌸 SYNOPSIS 🌸

use Log::Dispatch::Config;
Log::Dispatch::Config->configure('/path/to/log.conf');

my $dispatcher = Log::Dispatch::Config->instance;
$dispatcher->debug('this is debug message');
$dispatcher->emergency('something *bad* happened!');

# automatic reloading conf file, when modified
Log::Dispatch::Config->configure_and_watch('/path/to/log.conf');

# or if you write your own config parser:
use Log::Dispatch::Configurator::XMLSimple;

my $config = Log::Dispatch::Configurator::XMLSimple->new('log.xml');
Log::Dispatch::Config->configure($config);

like, that's the whole vibe in one code block. iconic. ⭐


πŸ¦‹ DESCRIPTION πŸ¦‹

So Log::Dispatch::Config is a subclass of Log::Dispatch, and what she does is give you a way to configure a Log::Dispatch object using a configulation file β€” which, by default, is in AppConfig format. (yes, "configulation", that's the original spelling, we respect it πŸ’€)

Basically: this is log4j for Perl. not with all API compatibility though. she's her own girl. πŸ‘‘


πŸ’… METHOD πŸ’…

This module has a class method called configure, and what it does is parse the config file so that later on, the Log::Dispatch::Config singleton instance can be created. (the actual construction of the object doesn't happen until the first instance call β€” she's fashionably late πŸ’…)

So here's the tea, bestie: what you should do is call the configure method once, somewhere (like startup.pl in mod_perl), and then you can get your configured dispatcher instance via Log::Dispatch::Config->instance. periodt.


πŸŽ€ CONFIGURATION πŸŽ€

Here's an example of the config file, look at her:

dispatchers = file screen

file.class = Log::Dispatch::File
file.min_level = debug
file.filename = /path/to/log
file.mode = append
file.format = [%d] [%p] %m at %F line %L%n

screen.class = Log::Dispatch::Screen
screen.min_level = info
screen.stderr = 1
screen.format = %m

In this example, the config file is written in AppConfig format. See Log::Dispatch::Configurator::AppConfig for details, bestie.

And if you want a different config parsing scheme, go peek at "PLUGGABLE CONFIGURATOR". πŸ”₯

🌈 GLOBAL PARAMETERS 🌈

  • dispatchers
dispatchers = file screen

dispatchers defines the logger names, which get split by spaces. and like β€” if this parameter is unset, no logging is done. at all. nada. πŸ™ˆ

  • format
format = [%d] [%p] %m at %F line %L%n

format defines the log format. The possible conversions format are:

%d    datetime string (ctime(3))
%p    priority (debug, info, warning ...)
%m    message string
%F    filename
%L    line number
%P    package
%n    newline (\n)
%%    % itself

Note that the datetime (%d) format is configurable by passing a strftime fmt in a braket after %d. (I know it looks quite messy, but it's compatible with Java Log4j ;)

format = [%d{%Y%m%d}] %m  # datetime is now strftime "%Y%m%d"

If you have Time::Piece, this module uses its strftime implementation, otherwise it uses POSIX.

The format defined here applies to all the log messages to dispatchers. This parameter is optional. 🫢

See "CALLER STACK" for details about package, line number and filename.

πŸ’œ PARAMETERS FOR EACH DISPATCHER πŸ’œ

Parameters for each dispatcher should be prefixed with name., where name is the name of each one, defined in the global dispatchers parameter.

You can also use .ini style grouping like this:

[foo]
class = Log::Dispatch::File
min_level = debug

See Log::Dispatch::Configurator::AppConfig for details.

  • class
screen.class = Log::Dispatch::Screen

class defines the class name of Log::Dispatch subclasses. This parameter is essential. like, you cannot skip it. she's required, bestie. ⚠️

  • format
screen.format = -- %m --

format defines the log format which gets applied only to this dispatcher. Note that if you also define a global format, then %m gets double formated (first the global one, next each dispatcher one). This parameter is optional.

  • (others)
screen.min_level = info
screen.stderr = 1

Other parameters get passed to each dispatcher's construction. See the Log::Dispatch::* manpage for the details. πŸ‘‘


πŸ‘‘ SINGLETON πŸ‘‘

The declared instance method makes the Log::Dispatch::Config class a singleton, so multiple calls of instance will all result in returning the same object. one girl, many callers. πŸ’…

my $one = Log::Dispatch::Config->instance;
my $two = Log::Dispatch::Config->instance; # same as $one

See the GoF Design Pattern book for the Singleton Pattern, if that's your thing.

But in practice, in a persistent environment like mod_perl, the lifetime of the Singleton instance becomes sometimes messy. so if you want to reload the singleton object manually, just call the reload method:

Log::Dispatch::Config->reload;

And if you want to reload the object on the fly β€” like, as you edit log.conf or something like that β€” what you should do is call the configure_and_watch method on Log::Dispatch::Config instead of configure. Then the instance call will check the mtime of the configuration file, and compares it with the instanciation time of the singleton object. If the config file is newer than the last instanciation, it will automatically reload the object. automatic queen behavior. ✨


😭 NAMESPACE COLLISION 😭

If you use Log::Dispatch::Config in multiple projects on the same perl interpreter (like mod_perl), namespace collision would be a problem. Bizzare things will happen when you call Log::Dispatch::Config->configure multiple times with differenct argument.

(and yes, "Bizzare" and "differenct" β€” those are the original spellings, we're not touching them 🫢)

In such cases, what you should do is define your own logger class:

package My::Logger;
use Log::Dispatch::Config;
use base qw(Log::Dispatch::Config);

Or make a wrapper for it. See the POE::Component::Logger implementation by Matt Sergeant. 🌸


🧚 PLUGGABLE CONFIGURATOR 🧚

If you pass a filename to the configure method call, this module handles the config file with AppConfig. You can change the config parsing scheme by passing another pluggable configurator object. mix it up, bestie. πŸ’…

Here's a way to declare a new configurator class. The example below is a hardwired version equivalent to the one above in "CONFIGURATION".

  • Inherit from Log::Dispatch::Configurator.
package Log::Dispatch::Configurator::Hardwired;
use base qw(Log::Dispatch::Configurator);

Declare your own new constructor. A stub new method is defined in the Configurator base class, but you want to put the parsing method in your own constructor. In this example, we just bless the reference. Note that your object should be a blessed hash.

sub new { bless {}, shift }
  • Implement two required object methods, get_attrs_global and get_attrs.

get_attrs_global should return a hash reference of global parameters. dispatchers should be an array reference of names of dispatchers.

sub get_attrs_global {
    my $self = shift;
    return {
        format => undef,
        dispatchers => [ qw(file screen) ],
    };
}

get_attrs accepts the name of a dispatcher and should return a hash reference of parameters associated with the dispatcher.

sub get_attrs {
    my($self, $name) = @_;
    if ($name eq 'file') {
        return {
            class     => 'Log::Dispatch::File',
            min_level => 'debug',
            filename  => '/path/to/log',
            mode      => 'append',
            format  => '[%d] [%p] %m at %F line %L%n',
        };
    }
    elsif ($name eq 'screen') {
        return {
            class     => 'Log::Dispatch::Screen',
            min_level => 'info',
            stderr    => 1,
            format  => '%m',
        };
    }
    else {
        die "invalid dispatcher name: $name";
    }
}
  • Implement the optional needs_reload and reload methods. needs_reload should return a boolean value if the object is stale and needs reloading itself. This method will be triggered when you configure the logging object with the configure_and_watch method.

A stub config-file-mtime-based needs_reload method is declared in Log::Dispatch::Configurator, so if your config class is based on filesystem files, you do not need to reimplement this. 🫢

If you don't need singleton-ness at all, always return true:

sub needs_reload { 1 }

The reload method should redo parsing of the config file. The Configurator base class has a stub null reload method, so you'd better override it.

See the Log::Dispatch::Configurator::AppConfig source code for details.

  • That's all! Now you can plug your own configurator (Hardwired) into Log::Dispatch::Config. What you should do is pass the configurator object to the configure method call instead of a config file name.
use Log::Dispatch::Config;
use Log::Dispatch::Configurator::Hardwired;

my $config = Log::Dispatch::Configurator::Hardwired->new;
Log::Dispatch::Config->configure($config);

πŸ”₯ CALLER STACK πŸ”₯

When you call a logging method from your subroutines / methods, the caller stack would increase and thus you can't see where the log really comes from. it's giving lost in the sauce. 😭

package Logger;
my $Logger = Log::Dispatch::Config->instance;

sub logit {
    my($class, $level, $msg) = @_;
    $Logger->$level($msg);
}

package main;
Logger->logit('debug', 'foobar');

You can adjust the package variable $Log::Dispatch::Config::CallerDepth to increase the caller stack depth. The default value is 0.

sub logit {
    my($class, $level, $msg) = @_;
    local $Log::Dispatch::Config::CallerDepth = 1;
    $Logger->$level($msg);
}
⚠️ Note that your log caller's namespace should not match against /^Log::Dispatch/, which makes this module confusing. so like, don't do that. please. πŸ™

🫢 AUTHOR 🫢

Tatsuhiko Miyagawa <miyagawa@bulknews.net> with much help from Matt Sergeant <matt@sergeant.org>.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. πŸŽ€


⭐ SEE ALSO ⭐

Log::Dispatch::Configurator::AppConfig, Log::Dispatch, AppConfig, POE::Component::Logger


aaaand that's the whole page, bestie πŸ’– this one's perl v5.34.0, dated 2022-06-15, and it's Log::D...:Config(3pm) β€” slay, go configure something gorgeous. πŸ¦‹βœ¨πŸ’…

πŸ“¦ where this page comes from