I'm trying to come up with a neat way to log messages from my script. I'm logging messages to any of several destinations - stdout, a file, or a text widget, and currently I do this by calling multiple functions (one of which is included below), which isn't very clean. I'm also prioritising ($LOG_LEVEL) each message, and the other functions also support a $PrintFormal boolean, to switch on/off the timestamp output in some cases.
use constant DEBUG => 0; # Log levels use constant INFO => 1; use constant NORMAL => 2; use constant WARN => 3; use constant ERROR => 4; my @LOG_LEVEL_NAME = ('DEBUG', 'INFO', 'NORMAL', 'WARN', 'ERROR'); my $LOG_LEVEL = DEBUG; sub LogMsg { my $level = shift; unless ($level >= $LOG_LEVEL) {return} my ($sec, $min, $hour, $day, $mon, $year) = localtime; $LogCounter++; if (open LOG, ">> $LOGFILE") { printf LOG "%04d.%02d.%02d %02d:%02d:%02d.%d: ", $year+1900, $mon+1, $day, $hour, $min, $sec, $LogCounter; print LOG "$$: $Display: $LOG_LEVEL_NAME[$level]: @_\n"; close LOG; } } LogMsg INFO, "Starting chooser mode...";

What I'd like to do is combine my three functions into one, and seeing as how the function gets used quite a lot, I want it's usage to be as straight-forward as possible. I'm figuring this would probably work with a bit of binary arithmetic:

use constant FILE => 0b0001; use constant STDOUT => 0b0010; use constant GUI => 0b0100; LogMsg FILE|STDOUT, "Message";

But before I go ahead and implement this, I wanted to ask if anyone has any tips, or can point me to some existing code? Is there already a standard way of doing this? Ideally, I'd also like to be able to select a priority and formatting for each of the destinations!


In reply to Logging messages - is there a better way? by matt.tovey

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.