Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Log4Perl across modules in Perl?

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.

like image 764
KK99 Avatar asked Feb 22 '23 21:02

KK99


1 Answers

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.

like image 132
Marco De Lellis Avatar answered Feb 28 '23 20:02

Marco De Lellis