Dear wise Monks, I'm not sure if what I'm doing is bad practice or not (or just terrible code, please me gentle). I created a Log object singleton to use throughout a number of modules which interact. Is it ok to store the Log object inside other objects so that the Log objects logging methods can be utilized? Here's the code (stripped down). In package DoStuff I call the Log objects log routine.
package Log; my $singleton; sub new{ my ($class,$logpath) = @_; unless ( ref $singleton eq 'Log' ) { $singleton = {}; bless( $singleton, $class ); $singleton->create_path($logpath); } return $singleton; } sub create_path{ my ($self,$logpath) = @_; my $logfile = $logpath . 'yyyymmdd' . '.txt'; $self->{'log'} = $logfile; return; } sub get_log_instance { $singleton ||= (shift)->new(); } sub log { my $self = shift; my $error_msg = shift; my $logfile = $self->{'log'}; my $handle; open ( $handle, '>>', $logfile ) or die "Can't open $logfile: $!"; print {$handle} "ERROR: $error_msg\n"; close $handle; return; } 1; package DoStuff; use Log; sub new { my $class = shift; my $log_obj = Log->get_log_instance(); my $self = bless {}, $class; # Store log object. Is this OK to do? $self->{'log_obj'} = $log_obj; return $self; } sub get_log_obj { my $self = shift; return $self->{'_log_obj'}; } sub do_something { my $self = shift; ..... # Get log object and pass error msg to it's log sub routine $self->get_log_obj()->log('Error Error Error'); # Do some logging ..... return; } 1;

In reply to Singleton Log Object by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.