onegative has asked for the wisdom of the Perl Monks concerning the following question:

G'day Monks,
I have a question is it possible to pass all STDERR into a logger function? I want to log any errors from supporting modules into my application log to be able to correlate what the application was doing when the error occurred.
Any suggestions would be greatly appreciated and thanks in advance.

Here is my logger function, the Date() function provides the timestamps for log file name and log entry. What I was hoping to do is something like this Logger(STDERR)

sub Logger() { my $message = $_[0]; if ( $message eq "" ) { return; } &Date(); $pdmgrdFile = "pdmgrd\.$LOG_NAME"; $pdmgrdLogPath = "$log$pdmgrdFile"; open(PDMGRD, ">>$pdmgrdLogPath") || die "Can't open logfile: $ +pdmgrdLogPath - $!\n"; print PDMGRD "$LOG_STAMP $message\n"; close(PDMGRD); }

Replies are listed 'Best First'.
by kennethk (Abbot) on Apr 04, 2011 at 14:56 UTC
    Sure. There are a number of ways to accomplish this, depending on your need. I usually redirect STDERR into a scalar - This is discussed in open (do a page search for redirect). This obviously won't work if you are trying to catch dies, since you'll just lose the output. This is probably not what you want if this is a long term solution.

    Another choice is redefining the __WARN__ and __DIE__ handlers. See error/warn customization for a discussion.

    There are also a number of modules on CPAN that might hit your spec. Take a look at the Log namespace, particularly Log::Log4perl.

by chrestomanci (Priest) on Apr 04, 2011 at 15:43 UTC

    Instead of writing your own logger, It might be a good idea to check out Log::Log4perl. It is much more flexible and has far more features than anything you are likely to write yourself, and by using it, you save the need to debug and maintain a component in your script.

by anonymized user 468275 (Curate) on Apr 04, 2011 at 15:18 UTC
    open STDERR, '|';
    so from here on, warnings etc become input to instead of output to the default stderr channel. and simply transfers each line of input to your desired logging routine e.g.
    #!/usr/bin/perl use lib '/home/me/perlib'; use 'mylogger'; while (<>) { mylogger::log($_); }

    One world, one people