in reply to Re: Best practice for handling subroutines that are conditionally loaded?
in thread Best practice for handling subroutines that are conditionally loaded?
This is the 5 minute mess I just came up with:
Which is used like so:package Log::Maybe { use strict; use warnings; use parent 'Exporter'; our %EXPORT_TAGS = ( all => [ our @EXPORT = qw[info debug debugf $ +LOG_LEVEL] ] ); # Don't do this... our $LOG_LEVEL = $ENV{LOG_MAYBE}; + # 0: off, 1: debug, 2: info use Data::Dump qw[]; use Carp; $Carp::CarpLevel = 1; sub info { return 2 unless @_; return unless $LOG_LEVEL >= 2; Carp::cluck join ' ', map { ref $_ ? Data::Dump::dump($_) : $_ + } @_; } sub debug { return 1 unless @_; return unless $LOG_LEVEL >= 1; Carp::cluck '[' . localtime . '] ' . join ' ', map { ref $_ ? +Data::Dump::dump($_) : $_ } @_; } sub debugf { return 1 unless @_; return unless $LOG_LEVEL >= 1; Carp::cluck '[' . localtime . '] ' . sprintf shift, map { ref +$_ ? Data::Dump::dump($_) : $_ } @_; } }; 1;
use strict; use warnings; use lib './lib'; use Log::Maybe; # uses $ENV var $LOG_LEVEL = debug; # enable/change log leve +l info('oh, yeah, baby!'); # prints only if log lev +el is info debug('hi'); # prints if log level is + debug or info debug( 'wow', \%ENV ); # dumps non-scalars debugf( 'name: %s, age: %d', 'Jack', 23 ); # dumpf takes a sprintf +form $LOG_LEVEL = 0; # disable logging at run +time debug('nothing is logged'); # what it says on the ti +n
I was feeling clever so the debug function gives you a stack trace. info and debug can also be used to return values used by $LOG_LEVEL. This is simple enough but something like Log::Any would be a wise choice here.
Edit: Added debugf as an example of things you could do.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: Best practice for handling subroutines that are conditionally loaded? (AI generated code)
by LanX (Saint) on Mar 08, 2024 at 17:22 UTC | |
by nysus (Parson) on Mar 08, 2024 at 18:05 UTC | |
by LanX (Saint) on Mar 08, 2024 at 18:31 UTC |