How can I use Log4Perl for modules in Perl?

I plan to use Log4Perl in my logging modules.

My code structure is like this

I have a Start.PL that checks some parameters. I have several module files (PM) that are interconnected (used in these PL and PM files)

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

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

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

Here are my questions

  • How can I use the same $ log through modules (PM files)
  • Do I need to use the same package name for this?

It would be nice if someone clarified these points to me.

+4
source share
3 answers

You can declare $log as a package variable with our and use the instance wherever you need using its detailed full name:

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

Instead of the full name, you can use an alias after assigning the type glob:

 #!/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 gives:

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

In your case, the full name of the log object in Start.pl $main::log . You can create an alias in every package where you need a logger with *log = $main::log .

+4
source

Actually, the way Log4perl works (it is singleton), get_logger () will return the same object, wherever you call it 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"; 

Prints (for example):

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

So, if you want to use the same $ log for all your modules, you can simply call get_logger ("MyLog") in each of these modules.

But the best way, if you want to enable or disable logging in one specific module, may be to simply call get_logger () with no arguments. This will return a registrar bound to the current package name so that you can enable or disable this packet recorder in your configuration file.

+4
source

Use global type variables

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

This way you can access the $ main :: log variable anywhere in the modules. Because it will be saved in the namespace.

0
source

All Articles