Hi, you should use tools built for the purpose, for example Log::Any to produce log output, and a Log::Any::Adapter to consume (and display, or not) the log output. Then you can can control the output of your debugging as well as the levels at which information is displayed/saved or whatever.
In the example below I am using Log::Dispatch as an adapter to process the log output, since you indicated that you want output from different packages handled differently. You can use a simple adapter if all your log output should go to one place. I generally use Log::Dispatch by default, as logging needs typically grow over time.
MyFirst.pm :
MySecond.pm :package MyFirst; use strict; use warnings; use feature 'say'; use Log::Any qw/ $log /; sub do_this { say 'Hello from MyFirst'; $log->debug('This is a debug message'); } 1;
1203778.pl (or another package, whatever...) :package MySecond; use strict; use warnings; use feature 'say'; use Log::Any qw/ $log /; sub do_that { say 'Hello from MySecond'; $log->warn('This is a warning!'); } 1;
Output:use strict; use warnings; use feature 'say'; use lib '.'; use MyFirst; use MySecond; use Log::Any::Adapter; use Log::Any::Adapter::Dispatch; my $logger = Log::Dispatch->new( outputs => [ [ 'Screen', min_level => 'warning' ], [ 'File', min_level => 'debug', filename => 'logfile', newline +=> 1 ], ]); Log::Any::Adapter->set( { category => qr/^My/ }, 'Dispatch', dispatcher => $logger, ); MyFirst::do_this(); MySecond::do_that(); __END__
Log file:perl 1203778.pl Hello from MyFirst Hello from MySecond This is a warning!
$ cat logfile This is a debug message This is a warning!
You can easily create your own Log::Any::Adapter class, which you will need to do if you want timestamp, caller info, etc.
( For a simpler scenario, just import $log from Log::Any into your package and use use Log::Any::Adapter qw/ Stderr /; in your script, and you are done. )
Hope this helps!
In reply to Re: How to log to different outputs from different packages
by 1nickt
in thread Overriding Global Variables
by Mano_Man
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |