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

Is there a way to sense if Sys::Syslog's openlog() has already been called? I'm looking at the docs, and I don't see one.

I'm writing some generic verbosity/debugging stuff for all the little scripts I wind up writing, and I'd like my message handler to print warnings to syslog if my script already uses syslog. ...Maybe an example would make more sense:

if ( syslog_is_open() ) { syslog('info','This script uses syslog'); } else { print "This script does not use syslog\n"; }

So, my question is, how would you write the syslog_is_open() function used above?

Thanks!
--Pileofrogs

Replies are listed 'Best First'.
Re: Is syslog already open?
by shmem (Chancellor) on Mar 13, 2007 at 21:09 UTC
    Since openlog() croaks if it can't connect to the syslog daemon, you could just use fileno on the socket filehandle openlog() uses:
    #!/usr/bin/perl use strict; use Sys::Syslog; sub is_open { defined fileno(*Sys::Syslog::SYSLOG) } print "opened? ",is_open() ? 'yes' : 'no', "\n"; print "calling openlog()\n"; openlog("perl","ndelay","LOG_LOCAL0") or die; print "opened? ",is_open() ? 'yes' : 'no', "\n"; __END__ opened? no calling openlog() opened? yes

    If the filehandle is closed, fileno returns undef. Of course it would be nice if that were inside Sys::Syslog and the filehandle wouldn't be accessible from outside.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: Is syslog already open?
by grinder (Bishop) on Mar 13, 2007 at 20:18 UTC

    Reading the latest source, it appears that in certain circumstances, Sys::Syslog::connection_ok() might return what you want.

    Otherwise, there is a $connected variable in the package. If that means what I think it does, a patch to add a subroutine that allows one to read its contents would probably be a nice addition. I'm sure Sébastien Aperghis-Tramoni would consider it for inclusion in a future release; he's been taking good care of the module recently.

    An alternative would be to add your own scaffolding:

    BEGIN { my $is_open = 0; sub check_openlog { if (not $is_open) { openlog(...) and ++$is_open; } } sub is_open { return $is_open; } }

    Then you can call check_openlog() anywhere in the code path, and your wrapper will do the right thing: only the first call that calls openlog() and succeeds will have any effect. All other calls will have no effect. (Reminds me of a certain biological process, come to think of it).

    • another intruder with the mooring in the heart of the Perl