4

I'm planning to use Log4Perl in my modules for logging.

My code structure goes like this

I have Start.PL which validates some parameters. I have several modules (PM) file which are interlinked (used across these PL and PM files)

I have a Logger.PM in which I have a method InitiateLogger() which creates the log object

 $log    = Log::Log4perl->get_logger("MyLog");

I call this method Logger::InitiateLogger(); in the Start.pl

Here are my questions

  1. How can I use the same $log across the modules (PM files)
  2. Do I need to use same package name for this?

Would be nice if someone clarifies me these points.

slm
  • 15,396
  • 12
  • 109
  • 124
KK99
  • 1,971
  • 7
  • 31
  • 64

3 Answers3

4

You may declare $log as a package variable with our and use the instance wherever you need, using its verbose fully qualified name:

Package::Name::$log->info( 'test' );

In place of fully qualified name you can use an alias after a typeglob assignment:

#!/usr/bin/env perl

package Package::Name;

use strict;
use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init( $ERROR );
our $log = get_logger();

package main;

use v5.12;
use strict;

*log = $Package::Name::log;
say $log;

which yields:

Log::Log4perl::Logger=HASH(0x230ff20)

In your case, the fully qualified name of logger object in Start.pl is $main::log. You can make an alias in every package where the logger is needed with *log = $main::log.

Marco De Lellis
  • 1,169
  • 6
  • 10
4

Actually, the way Log4perl works (it's a singleton), get_logger() will return the exact same object wherever in your program it's called from

use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init( $ERROR );

print Log::Log4perl->get_logger("MyLog"), "\n";

package Some::Other::Package;

print Log::Log4perl->get_logger("MyLog"), "\n";

This prints (for example):

Log::Log4perl::Logger=HASH(0x15a9d48)
Log::Log4perl::Logger=HASH(0x15a9d48)

So if you want to use the same $log across all your modules, you could just call get_logger("MyLog") in each of those modules.

But a better way, if you want to be able to turn logging on or off in one particular module, might be to just call get_logger() without arguments. That will return you a logger tied to the current package name, so you could turn that package's logger on or off in your config file.

Kevin G.
  • 1,424
  • 1
  • 13
  • 22
0

Use global variables like,

$main::log = Log::Log4perl->get_logger("MyLog");

So you can access the variable $main::log anywhere across the modules. Because it will be maintained in the namespace.

slm
  • 15,396
  • 12
  • 109
  • 124
karthi_ms
  • 5,568
  • 11
  • 38
  • 39