Recipe 9.33 Writing Log Entries via Perl

9.33.1 Problem

You want to add information to the system log from a Perl program.

9.33.2 Solution

Use the Perl module Sys::Syslog, which implements the API described in the sidebar, The syslog API.
use Sys::Syslog qw(:DEFAULT setlogsock);
use File::Basename;
my $count = 0;
my $host = "some-machine";
openlog(basename($0), "pid", "local3");
syslog("warning", "%d connections from %s", $count, $host);
syslog("authpriv|err", "intruder alert!");
syslog("err", "can't open configuration file: %m");
closelog( );

9.33.3 Discussion

The system logger by default refuses to accept network connections (assuming you have not used the syslogd -r option). Unfortunately, the Perl module uses network connections by default, so our recipe calls setlogsock to force the use of a local socket instead. If your syslog messages seem to be disappearing into thin air, be sure to use setlogsock. Recent versions of Sys::Syslog resort to a local socket if the network connection fails, but use of setlogsock for reliable operation is a good idea, since the local socket should always work. Note that setlogsock must be explicitly imported.

Perl scripts can pass the %m format specifier to syslog to include system error messages, as an alternative to interpolating the $! variable. Be sure to use %m (or $!) only when a system error has occurred, to avoid misleading messages.

9.33.4 See Also

Sys::Syslog(3pm), syslog(3).

    Chapter 9. Testing and Monitoring