in reply to Passing the logger's object
Here's a very quick and dirty example that I think uses parts of each technique you've shown. When new() is called on Library, we store a log as a class variable. It has a log() method that will return this log. In the case below, with Library::Foo, Library passes the log in. We could also have accessed it as $Library::log, or much more preferably $log = Library::log()->child('name');.
This way, each class has a copy of the top-level log which has had it's class name appended to the log name. Then, each sub inside of each package makes a copy of this class log object, which then in turn appends its name, so the log messages each reflect exactly where the log was used.
I've used numerous ways of doing things like this. This is but one of them.
use warnings; use strict; package Library::Foo; { my $log; sub new { my ($class, $logger) = @_; my $self = bless {}, $class; # set the class level log $log = $logger->child('Library::Foo'); # generate a local log per each sub my $log = $log->child('new'); $log->_0("creating new foo obj"); return $self; } } package Library; { use Logging::Simple; # set the class log my $log = Logging::Simple->new(name => 'Library'); sub new { my $self = bless {}, shift; # generate a child log per sub my $log = $log->child('new'); $log->_0('creating Library obj'); return $self; } sub log { # return the class level log obj return $log; } sub foo { my ($self) = @_; my $log = $log->child('foo'); $log->_0('about to crate lib::foo obj'); $self->{foo} = Library::Foo->new($self->log); } } package main; my $lib = Library->new; $lib->foo;
Output:
[2016-11-13 09:12:13.179][lvl 0][Library.new] creating Library obj [2016-11-13 09:12:13.180][lvl 0][Library.foo] about to crate lib::foo +obj [2016-11-13 09:12:13.180][lvl 0][Library.Library::Foo.new] creating ne +w foo obj
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Passing the logger's object
by v_melnik (Scribe) on Nov 13, 2016 at 20:11 UTC | |
by stevieb (Canon) on Nov 13, 2016 at 20:42 UTC |