4 use warnings::register;
9 use POSIX qw< strftime setlocale LC_TIME >;
10 use Socket qw< :all >;
14 *import = \&Exporter::import;
21 standard => [qw(openlog syslog closelog setlogmask)],
22 extended => [qw(setlogsock)],
26 LOG_ALERT LOG_CRIT LOG_DEBUG LOG_EMERG LOG_ERR
27 LOG_INFO LOG_NOTICE LOG_WARNING
32 LOG_AUTH LOG_AUTHPRIV LOG_CRON LOG_DAEMON LOG_FTP LOG_KERN
33 LOG_LOCAL0 LOG_LOCAL1 LOG_LOCAL2 LOG_LOCAL3 LOG_LOCAL4
34 LOG_LOCAL5 LOG_LOCAL6 LOG_LOCAL7 LOG_LPR LOG_MAIL LOG_NEWS
35 LOG_SYSLOG LOG_USER LOG_UUCP
37 # Mac OS X specific facilities
38 qw( LOG_INSTALL LOG_LAUNCHD LOG_NETINFO LOG_RAS LOG_REMOTEAUTH ),
39 # modern BSD specific facilities
40 qw( LOG_CONSOLE LOG_NTP LOG_SECURITY ),
41 # IRIX specific facilities
42 qw( LOG_AUDIT LOG_LFMT ),
46 LOG_CONS LOG_PID LOG_NDELAY LOG_NOWAIT LOG_ODELAY LOG_PERROR
51 LOG_FACMASK LOG_NFACILITIES LOG_PRIMASK
58 @{$EXPORT_TAGS{standard}},
62 @{$EXPORT_TAGS{extended}},
63 @{$EXPORT_TAGS{macros}},
68 XSLoader::load('Sys::Syslog', $VERSION);
72 push @ISA, 'DynaLoader';
73 bootstrap Sys::Syslog $VERSION;
81 use constant HAVE_GETPROTOBYNAME => $Config::Config{d_getpbyname};
82 use constant HAVE_GETPROTOBYNUMBER => $Config::Config{d_getpbynumber};
83 use constant HAVE_SETLOCALE => $Config::Config{d_setlocale};
84 use constant HAVE_IPPROTO_TCP => defined &Socket::IPPROTO_TCP ? 1 : 0;
85 use constant HAVE_IPPROTO_UDP => defined &Socket::IPPROTO_UDP ? 1 : 0;
86 use constant HAVE_TCP_NODELAY => defined &Socket::TCP_NODELAY ? 1 : 0;
88 use constant SOCKET_IPPROTO_TCP =>
89 HAVE_IPPROTO_TCP ? Socket::IPPROTO_TCP
90 : HAVE_GETPROTOBYNAME ? scalar getprotobyname("tcp")
93 use constant SOCKET_IPPROTO_UDP =>
94 HAVE_IPPROTO_UDP ? Socket::IPPROTO_UDP
95 : HAVE_GETPROTOBYNAME ? scalar getprotobyname("udp")
98 use constant SOCKET_TCP_NODELAY => HAVE_TCP_NODELAY ? Socket::TCP_NODELAY : 1;
104 use vars qw($host); # host to send syslog messages to (see notes at end)
114 use vars qw($facility);
115 my $connected = 0; # flag to indicate if we're connected or not
116 my $syslog_send; # coderef of the function used to send messages
117 my $syslog_path = undef; # syslog path for "stream" and "unix" mechanisms
118 my $syslog_xobj = undef; # if defined, holds the external object used to send messages
119 my $transmit_ok = 0; # flag to indicate if the last message was transmitted
120 my $sock_port = undef; # socket port
121 my $sock_timeout = 0; # socket timeout, see below
122 my $current_proto = undef; # current mechanism used to transmit messages
123 my $ident = ''; # identifiant prepended to each message
124 $facility = ''; # current facility
125 my $maskpri = LOG_UPTO(&LOG_DEBUG); # current log mask
137 # Default is now to first use the native mechanism, so Perl programs
138 # behave like other normal Unix programs, then try other mechanisms.
139 my @connectMethods = qw(native tcp udp unix pipe stream console);
140 if ($^O eq "freebsd" or $^O eq "linux") {
141 @connectMethods = grep { $_ ne 'udp' } @connectMethods;
144 # And on Win32 systems, we try to use the native mechanism for this
145 # platform, the events logger, available through Win32::EventLog.
147 my $verbose_if_Win32 = $^O =~ /Win32/i;
149 if (can_load_sys_syslog_win32($verbose_if_Win32)) {
150 unshift @connectMethods, 'eventlog';
154 my @defaultMethods = @connectMethods;
155 my @fallbackMethods = ();
157 # The timeout in connection_ok() was pushed up to 0.25 sec in
158 # Sys::Syslog v0.19 in order to address a heisenbug on MacOSX:
159 # http://london.pm.org/pipermail/london.pm/Week-of-Mon-20061211/005961.html
161 # However, this also had the effect of slowing this test for
162 # all other operating systems, which apparently impacted some
163 # users (cf. CPAN-RT #34753). So, in order to make everybody
164 # happy, the timeout is now zero by default on all systems
165 # except on OSX where it is set to 250 msec, and can be set
166 # with the infamous setlogsock() function.
168 # Update 2011-08: this issue is also been seen on multiprocessor
169 # Debian GNU/kFreeBSD systems. See http://bugs.debian.org/627821
170 # and https://rt.cpan.org/Ticket/Display.html?id=69997
171 # Also, lowering the delay to 1 ms, which should be enough.
173 $sock_timeout = 0.001 if $^O =~ /darwin|gnukfreebsd/;
176 # Perl 5.6.0's warnings.pm doesn't have warnings::warnif()
177 if (not defined &warnings::warnif) {
178 *warnings::warnif = sub {
179 goto &warnings::warn if warnings::enabled(__PACKAGE__)
183 # coderef for a nicer handling of errors
184 my $err_sub = $options{nofatal} ? \&warnings::warnif : \&croak;
188 # This AUTOLOAD is used to 'autoload' constants from the constant()
192 ($constname = $AUTOLOAD) =~ s/.*:://;
193 croak "Sys::Syslog::constant() not defined" if $constname eq 'constant';
194 my ($error, $val) = constant($constname);
195 croak $error if $error;
197 *$AUTOLOAD = sub { $val };
203 ($ident, my $logopt, $facility) = @_;
206 $ident ||= basename($0) || getlogin() || getpwuid($<) || 'syslog';
208 $facility ||= LOG_USER();
210 for my $opt (split /\b/, $logopt) {
211 $options{$opt} = 1 if exists $options{$opt}
214 $err_sub = delete $options{nofatal} ? \&warnings::warnif : \&croak;
215 return 1 unless $options{ndelay};
220 disconnect_log() if $connected;
221 $options{$_} = 0 for keys %options;
222 $facility = $ident = "";
228 my $oldmask = $maskpri;
229 $maskpri = shift unless $_[0] == 0;
239 check => sub { return can_load_sys_syslog_win32() },
240 err_msg => "no Win32 API available",
250 ($syslog_path) = grep { defined && length && -p && -w _ }
251 $syslog_path, &_PATH_LOG, "/dev/log";
252 return $syslog_path ? 1 : 0
254 err_msg => "path not available",
258 if (not defined $syslog_path) {
259 my @try = qw(/dev/log /dev/conslog);
260 unshift @try, &_PATH_LOG if length &_PATH_LOG;
261 ($syslog_path) = grep { -w } @try;
263 return defined $syslog_path && -w $syslog_path
265 err_msg => "could not find any writable device",
269 return 1 if defined $sock_port;
271 if (eval { local $SIG{__DIE__};
272 getservbyname('syslog','tcp') || getservbyname('syslogng','tcp')
274 $host = $syslog_path;
281 err_msg => "TCP service unavailable",
285 return 1 if defined $sock_port;
287 if (eval { local $SIG{__DIE__}; getservbyname('syslog', 'udp') }) {
288 $host = $syslog_path;
295 err_msg => "UDP service unavailable",
299 my @try = ($syslog_path, &_PATH_LOG);
300 ($syslog_path) = grep { defined && length && -w } @try;
301 return defined $syslog_path && -w $syslog_path
303 err_msg => "path not available",
311 # - old API: setlogsock($sock_type, $sock_path, $sock_timeout)
312 # - new API: setlogsock(\%options)
313 croak "setlogsock(): Invalid number of arguments"
314 unless @_ >= 1 and @_ <= 3;
316 if (my $ref = ref $_[0]) {
317 if ($ref eq "HASH") {
319 croak "setlogsock(): No argument given" unless keys %opt;
321 elsif ($ref eq "ARRAY") {
322 @opt{qw< type path timeout >} = @_;
325 croak "setlogsock(): Unexpected \L$ref\E reference"
329 @opt{qw< type path timeout >} = @_;
332 # check socket type, remove invalid ones
333 my $diag_invalid_type = "setlogsock(): Invalid type%s; must be one of "
334 . join ", ", map { "'$_'" } sort keys %mechanism;
335 croak sprintf $diag_invalid_type, "" unless defined $opt{type};
336 my @sock_types = ref $opt{type} eq "ARRAY" ? @{$opt{type}} : ($opt{type});
339 for my $sock_type (@sock_types) {
340 carp sprintf $diag_invalid_type, " '$sock_type'" and next
341 unless exists $mechanism{$sock_type};
342 push @tmp, "tcp", "udp" and next if $sock_type eq "inet";
343 push @tmp, $sock_type;
349 $syslog_path = $opt{path} if defined $opt{path};
350 $host = $opt{host} if defined $opt{host};
351 $sock_timeout = $opt{timeout} if defined $opt{timeout};
352 $sock_port = $opt{port} if defined $opt{port};
354 disconnect_log() if $connected;
356 @fallbackMethods = ();
357 @connectMethods = ();
360 # check each given mechanism and test if it can be used on the current system
361 for my $sock_type (@sock_types) {
362 if ( $mechanism{$sock_type}{check}->() ) {
363 push @connectMethods, $sock_type;
367 warnings::warnif("setlogsock(): type='$sock_type': "
368 . $mechanism{$sock_type}{err_msg});
372 # if no mechanism worked from the given ones, use the default ones
373 @connectMethods = @defaultMethods unless @connectMethods;
379 my ($priority, $mask, @args) = @_;
381 my (@words, $num, $numpri, $numfac, $sum);
383 my $fail_time = undef;
386 # if $ident is undefined, it means openlog() wasn't previously called
387 # so do it now in order to have sensible defaults
388 openlog() unless $ident;
390 local $facility = $facility; # may need to change temporarily.
392 croak "syslog: expecting argument \$priority" unless defined $priority;
393 croak "syslog: expecting argument \$format" unless defined $mask;
395 if ($priority =~ /^\d+$/) {
396 $numpri = LOG_PRI($priority);
397 $numfac = LOG_FAC($priority) << 3;
398 undef $numfac if $numfac == 0; # no facility given => use default
400 elsif ($priority =~ /^\w+/) {
401 # Allow "level" or "level|facility".
402 @words = split /\W+/, $priority, 2;
407 for my $word (@words) {
408 next if length $word == 0;
410 # Translate word to number.
414 croak "syslog: invalid level/facility: $word"
416 elsif ($num <= LOG_PRIMASK() and $word ne "kern") {
417 croak "syslog: too many levels given: $word"
422 croak "syslog: too many facilities given: $word"
424 $facility = $word if $word =~ /^[A-Za-z]/;
430 croak "syslog: invalid level/facility: $priority"
433 croak "syslog: level must be given" unless defined $numpri;
435 # don't log if priority is below mask level
436 return 0 unless LOG_MASK($numpri) & $maskpri;
438 if (not defined $numfac) { # Facility not specified in this call.
439 $facility = 'user' unless $facility;
440 $numfac = xlate($facility);
443 connect_log() unless $connected;
446 # escape percent signs for sprintf()
447 $error =~ s/%/%%/g if @args;
448 # replace %m with $error, if preceded by an even number of percent signs
449 $mask =~ s/(?<!%)((?:%%)*)%m/$1$error/g;
452 # add (or not) a newline
453 $mask .= "\n" if !$options{noeol} and rindex($mask, "\n") == -1;
454 $message = @args ? sprintf($mask, @args) : $mask;
456 if ($current_proto eq 'native') {
459 elsif ($current_proto eq 'eventlog') {
464 $whoami .= "[$$]" if $options{pid};
466 $sum = $numpri + $numfac;
469 if (HAVE_SETLOCALE) {
470 $oldlocale = setlocale(LC_TIME);
471 setlocale(LC_TIME, 'C');
474 # %e format isn't available on all systems (Win32, cf. CPAN RT #69310)
475 my $day = strftime "%e", localtime;
477 if (index($day, "%") == 0) {
478 $day = strftime "%d", localtime;
482 my $timestamp = strftime "%b $day %H:%M:%S", localtime;
483 setlocale(LC_TIME, $oldlocale) if HAVE_SETLOCALE;
485 # construct the stream that will be transmitted
486 $buf = "<$sum>$timestamp $whoami: $message";
488 # add (or not) a NUL character
489 $buf .= "\0" if !$options{nonul};
492 # handle PERROR option
493 # "native" mechanism already handles it by itself
494 if ($options{perror} and $current_proto ne 'native') {
496 $whoami .= "[$$]" if $options{pid};
497 print STDERR "$whoami: $message";
498 print STDERR "\n" if rindex($message, "\n") == -1;
501 # it's possible that we'll get an error from sending
502 # (e.g. if method is UDP and there is no UDP listener,
503 # then we'll get ECONNREFUSED on the send). So what we
504 # want to do at this point is to fallback onto a different
506 while (scalar @fallbackMethods || $syslog_send) {
507 if ($failed && (time - $fail_time) > 60) {
508 # it's been a while... maybe things have been fixed
509 @fallbackMethods = ();
511 $transmit_ok = 0; # make it look like a fresh attempt
515 if ($connected && !connection_ok()) {
516 # Something was OK, but has now broken. Remember coz we'll
517 # want to go back to what used to be OK.
518 $failed = $current_proto unless $failed;
523 connect_log() unless $connected;
524 $failed = undef if ($current_proto && $failed && $current_proto eq $failed);
527 if ($syslog_send->($buf, $numpri, $numfac)) {
531 # typically doesn't happen, since errors are rare from write().
535 # could not send, could not fallback onto a working
536 # connection method. Lose.
540 sub _syslog_send_console {
543 # The console print is a method which could block
544 # so we do it in a child process and always return success
546 if (my $pid = fork) {
548 if ($options{nowait}) {
551 if (waitpid($pid, 0) >= 0) {
554 # it's possible that the caller has other
555 # plans for SIGCHLD, so let's not interfere
560 if (open(CONS, ">/dev/console")) {
561 my $ret = print CONS $buf . "\r"; # XXX: should this be \x0A ?
562 POSIX::_exit($ret) if defined $pid;
566 POSIX::_exit(0) if defined $pid;
570 sub _syslog_send_stream {
572 # XXX: this only works if the OS stream implementation makes a write
573 # look like a putmsg() with simple header. For instance it works on
574 # Solaris 8 but not Solaris 7.
575 # To be correct, it should use a STREAMS API, but perl doesn't have one.
576 return syswrite(SYSLOG, $buf, length($buf));
579 sub _syslog_send_pipe {
581 return print SYSLOG $buf;
584 sub _syslog_send_socket {
586 return syswrite(SYSLOG, $buf, length($buf));
587 #return send(SYSLOG, $buf, 0);
590 sub _syslog_send_native {
591 my ($buf, $numpri, $numfac) = @_;
592 syslog_xs($numpri|$numfac, $buf);
599 # private function to translate names to numeric values
604 return $name+0 if $name =~ /^\s*\d+\s*$/;
606 $name = "LOG_$name" unless $name =~ /^LOG_/;
608 # ExtUtils::Constant 0.20 introduced a new way to implement
609 # constants, called ProxySubs. When it was used to generate
610 # the C code, the constant() function no longer returns the
611 # correct value. Therefore, we first try a direct call to
612 # constant(), and if the value is an error we try to call the
613 # constant by its full name.
614 my $value = constant($name);
616 if (index($value, "not a valid") >= 0) {
617 $name = "Sys::Syslog::$name";
618 $value = eval { no strict "refs"; &$name };
619 $value = $@ unless defined $value;
622 $value = -1 if index($value, "not a valid") >= 0;
624 return defined $value ? $value : -1;
630 # This function acts as a kind of front-end: it tries to connect to
631 # a syslog service using the selected methods, trying each one in the
635 @fallbackMethods = @connectMethods unless scalar @fallbackMethods;
637 if ($transmit_ok && $current_proto) {
638 # Retry what we were on, because it has worked in the past.
639 unshift(@fallbackMethods, $current_proto);
646 while ($proto = shift @fallbackMethods) {
648 my $fn = "connect_$proto";
649 $connected = &$fn(\@errs) if defined &$fn;
655 $current_proto = $proto;
656 my ($old) = select(SYSLOG); $| = 1; select($old);
658 @fallbackMethods = ();
659 $err_sub->(join "\n\t- ", "no connection to syslog available", @errs);
667 my $port = $sock_port
668 || eval { local $SIG{__DIE__}; getservbyname('syslog', 'tcp') }
669 || eval { local $SIG{__DIE__}; getservbyname('syslogng', 'tcp') };
670 if (!defined $port) {
671 push @$errs, "getservbyname failed for syslog/tcp and syslogng/tcp";
677 $addr = inet_aton($host);
679 push @$errs, "can't lookup $host";
683 $addr = INADDR_LOOPBACK;
685 $addr = sockaddr_in($port, $addr);
687 if (!socket(SYSLOG, AF_INET, SOCK_STREAM, SOCKET_IPPROTO_TCP)) {
688 push @$errs, "tcp socket: $!";
692 setsockopt(SYSLOG, SOL_SOCKET, SO_KEEPALIVE, 1);
693 setsockopt(SYSLOG, SOCKET_IPPROTO_TCP, SOCKET_TCP_NODELAY, 1);
695 if (!connect(SYSLOG, $addr)) {
696 push @$errs, "tcp connect: $!";
700 $syslog_send = \&_syslog_send_socket;
708 my $port = $sock_port
709 || eval { local $SIG{__DIE__}; getservbyname('syslog', 'udp') };
710 if (!defined $port) {
711 push @$errs, "getservbyname failed for syslog/udp";
717 $addr = inet_aton($host);
719 push @$errs, "can't lookup $host";
723 $addr = INADDR_LOOPBACK;
725 $addr = sockaddr_in($port, $addr);
727 if (!socket(SYSLOG, AF_INET, SOCK_DGRAM, SOCKET_IPPROTO_UDP)) {
728 push @$errs, "udp socket: $!";
731 if (!connect(SYSLOG, $addr)) {
732 push @$errs, "udp connect: $!";
736 # We want to check that the UDP connect worked. However the only
737 # way to do that is to send a message and see if an ICMP is returned
738 _syslog_send_socket("");
739 if (!connection_ok()) {
740 push @$errs, "udp connect: nobody listening";
744 $syslog_send = \&_syslog_send_socket;
751 # might want syslog_path to be variable based on syslog.h (if only
753 $syslog_path = '/dev/conslog' unless defined $syslog_path;
755 if (!-w $syslog_path) {
756 push @$errs, "stream $syslog_path is not writable";
762 if (!sysopen(SYSLOG, $syslog_path, Fcntl::O_WRONLY(), 0400)) {
763 push @$errs, "stream can't open $syslog_path: $!";
767 $syslog_send = \&_syslog_send_stream;
775 $syslog_path ||= &_PATH_LOG || "/dev/log";
777 if (not -w $syslog_path) {
778 push @$errs, "$syslog_path is not writable";
782 if (not open(SYSLOG, ">$syslog_path")) {
783 push @$errs, "can't write to $syslog_path: $!";
787 $syslog_send = \&_syslog_send_pipe;
795 $syslog_path ||= _PATH_LOG() if length _PATH_LOG();
797 if (not defined $syslog_path) {
798 push @$errs, "_PATH_LOG not available in syslog.h and no user-supplied socket path";
802 if (not (-S $syslog_path or -c _)) {
803 push @$errs, "$syslog_path is not a socket";
807 my $addr = sockaddr_un($syslog_path);
809 push @$errs, "can't locate $syslog_path";
812 if (!socket(SYSLOG, AF_UNIX, SOCK_STREAM, 0)) {
813 push @$errs, "unix stream socket: $!";
817 if (!connect(SYSLOG, $addr)) {
818 if (!socket(SYSLOG, AF_UNIX, SOCK_DGRAM, 0)) {
819 push @$errs, "unix dgram socket: $!";
822 if (!connect(SYSLOG, $addr)) {
823 push @$errs, "unix dgram connect: $!";
828 $syslog_send = \&_syslog_send_socket;
837 # reconstruct the numeric equivalent of the options
838 for my $opt (keys %options) {
839 $logopt += xlate($opt) if $options{$opt}
842 openlog_xs($ident, $logopt, xlate($facility));
843 $syslog_send = \&_syslog_send_native;
848 sub connect_eventlog {
851 $syslog_xobj = Sys::Syslog::Win32::_install();
852 $syslog_send = \&Sys::Syslog::Win32::_syslog_send;
857 sub connect_console {
859 if (!-w '/dev/console') {
860 push @$errs, "console is not writable";
863 $syslog_send = \&_syslog_send_console;
867 # To test if the connection is still good, we need to check if any
868 # errors are present on the connection. The errors will not be raised
869 # by a write. Instead, sockets are made readable and the next read
870 # would cause the error to be returned. Unfortunately the syslog
871 # 'protocol' never provides anything for us to read. But with
872 # judicious use of select(), we can see if it would be readable...
874 return 1 if defined $current_proto and (
875 $current_proto eq 'native' or $current_proto eq 'console'
876 or $current_proto eq 'eventlog'
880 vec($rin, fileno(SYSLOG), 1) = 1;
881 my $ret = select $rin, undef, $rin, $sock_timeout;
882 return ($ret ? 0 : 1);
887 $syslog_send = undef;
889 if (defined $current_proto and $current_proto eq 'native') {
891 unshift @fallbackMethods, $current_proto;
892 $current_proto = undef;
895 elsif (defined $current_proto and $current_proto eq 'eventlog') {
896 $syslog_xobj->Close();
897 unshift @fallbackMethods, $current_proto;
898 $current_proto = undef;
907 # Wrappers around eval() that makes sure that nobody, ever knows that
908 # we wanted to poke & test if something was here or not. This is needed
909 # because some applications are trying to be too smart, install their
910 # own __DIE__ handler, and mysteriously, things are starting to fail
911 # when they shouldn't. SpamAssassin among them.
913 sub silent_eval (&) {
914 local($SIG{__DIE__}, $SIG{__WARN__}, $@);
915 return eval { $_[0]->() }
918 sub can_load_sys_syslog_win32 {
920 local($SIG{__DIE__}, $SIG{__WARN__}, $@);
921 (my $module_path = __FILE__) =~ s:Syslog.pm$:Syslog/Win32.pm:;
922 my $loaded = eval { require $module_path } ? 1 : 0;
923 warn $@ if not $loaded and $verbose;
928 "Eighth Rule: read the documentation."
934 Sys::Syslog - Perl interface to the UNIX syslog(3) calls
938 This is the documentation of version 0.35
942 use Sys::Syslog; # all except setlogsock()
943 use Sys::Syslog qw(:standard :macros); # standard functions & macros
945 openlog($ident, $logopt, $facility); # don't forget this
946 syslog($priority, $format, @args);
947 $oldmask = setlogmask($mask_priority);
953 C<Sys::Syslog> is an interface to the UNIX C<syslog(3)> program.
954 Call C<syslog()> with a string priority and a list of C<printf()> args
955 just like C<syslog(3)>.
960 C<Sys::Syslog> exports the following C<Exporter> tags:
966 C<:standard> exports the standard C<syslog(3)> functions:
968 openlog closelog setlogmask syslog
972 C<:extended> exports the Perl specific functions for C<syslog(3)>:
978 C<:macros> exports the symbols corresponding to most of your C<syslog(3)>
979 macros and the C<LOG_UPTO()> and C<LOG_MASK()> functions.
980 See L<"CONSTANTS"> for the supported constants and their meaning.
984 By default, C<Sys::Syslog> exports the symbols from the C<:standard> tag.
991 =item B<openlog($ident, $logopt, $facility)>
994 C<$ident> is prepended to every message. C<$logopt> contains zero or
995 more of the options detailed below. C<$facility> specifies the part
996 of the system to report about, for example C<LOG_USER> or C<LOG_LOCAL0>:
997 see L<"Facilities"> for a list of well-known facilities, and your
998 C<syslog(3)> documentation for the facilities available in your system.
999 Check L<"SEE ALSO"> for useful links. Facility can be given as a string
1002 This function will croak if it can't connect to the syslog daemon.
1004 Note that C<openlog()> now takes three arguments, just like C<openlog(3)>.
1006 B<You should use C<openlog()> before calling C<syslog()>.>
1014 C<cons> - This option is ignored, since the failover mechanism will drop
1015 down to the console automatically if all other media fail.
1019 C<ndelay> - Open the connection immediately (normally, the connection is
1020 opened when the first message is logged).
1024 C<noeol> - When set to true, no end of line character (C<\n>) will be
1025 appended to the message. This can be useful for some syslog daemons.
1026 Added in C<Sys::Syslog> 0.29.
1030 C<nofatal> - When set to true, C<openlog()> and C<syslog()> will only
1031 emit warnings instead of dying if the connection to the syslog can't
1032 be established. Added in C<Sys::Syslog> 0.15.
1036 C<nonul> - When set to true, no C<NUL> character (C<\0>) will be
1037 appended to the message. This can be useful for some syslog daemons.
1038 Added in C<Sys::Syslog> 0.29.
1042 C<nowait> - Don't wait for child processes that may have been created
1043 while logging the message. (The GNU C library does not create a child
1044 process, so this option has no effect on Linux.)
1048 C<perror> - Write the message to standard error output as well to the
1049 system log. Added in C<Sys::Syslog> 0.22.
1053 C<pid> - Include PID with each message.
1059 Open the syslog with options C<ndelay> and C<pid>, and with facility C<LOCAL0>:
1061 openlog($name, "ndelay,pid", "local0");
1063 Same thing, but this time using the macro corresponding to C<LOCAL0>:
1065 openlog($name, "ndelay,pid", LOG_LOCAL0);
1068 =item B<syslog($priority, $message)>
1070 =item B<syslog($priority, $format, @args)>
1072 If C<$priority> permits, logs C<$message> or C<sprintf($format, @args)>
1073 with the addition that C<%m> in $message or C<$format> is replaced with
1074 C<"$!"> (the latest error message).
1076 C<$priority> can specify a level, or a level and a facility. Levels and
1077 facilities can be given as strings or as macros. When using the C<eventlog>
1078 mechanism, priorities C<DEBUG> and C<INFO> are mapped to event type
1079 C<informational>, C<NOTICE> and C<WARNING> to C<warning> and C<ERR> to
1080 C<EMERG> to C<error>.
1082 If you didn't use C<openlog()> before using C<syslog()>, C<syslog()> will
1083 try to guess the C<$ident> by extracting the shortest prefix of
1084 C<$format> that ends in a C<":">.
1088 # informational level
1089 syslog("info", $message);
1090 syslog(LOG_INFO, $message);
1092 # information level, Local0 facility
1093 syslog("info|local0", $message);
1094 syslog(LOG_INFO|LOG_LOCAL0, $message);
1100 C<Sys::Syslog> version v0.07 and older passed the C<$message> as the
1101 formatting string to C<sprintf()> even when no formatting arguments
1102 were provided. If the code calling C<syslog()> might execute with
1103 older versions of this module, make sure to call the function as
1104 C<syslog($priority, "%s", $message)> instead of C<syslog($priority,
1105 $message)>. This protects against hostile formatting sequences that
1106 might show up if $message contains tainted data.
1111 =item B<setlogmask($mask_priority)>
1113 Sets the log mask for the current process to C<$mask_priority> and
1114 returns the old mask. If the mask argument is 0, the current log mask
1115 is not modified. See L<"Levels"> for the list of available levels.
1116 You can use the C<LOG_UPTO()> function to allow all levels up to a
1117 given priority (but it only accept the numeric macros as arguments).
1123 setlogmask( LOG_MASK(LOG_ERR) );
1125 Log everything except informational messages:
1127 setlogmask( ~(LOG_MASK(LOG_INFO)) );
1129 Log critical messages, errors and warnings:
1131 setlogmask( LOG_MASK(LOG_CRIT)
1133 | LOG_MASK(LOG_WARNING) );
1135 Log all messages up to debug:
1137 setlogmask( LOG_UPTO(LOG_DEBUG) );
1140 =item B<setlogsock()>
1142 Sets the socket type and options to be used for the next call to C<openlog()>
1143 or C<syslog()>. Returns true on success, C<undef> on failure.
1145 Being Perl-specific, this function has evolved along time. It can currently
1146 be called as follow:
1152 C<setlogsock($sock_type)>
1156 C<setlogsock($sock_type, $stream_location)> (added in Perl 5.004_02)
1160 C<setlogsock($sock_type, $stream_location, $sock_timeout)> (added in
1161 C<Sys::Syslog> 0.25)
1165 C<setlogsock(\%options)> (added in C<Sys::Syslog> 0.28)
1169 The available options are:
1175 C<type> - equivalent to C<$sock_type>, selects the socket type (or
1176 "mechanism"). An array reference can be passed to specify several
1177 mechanisms to try, in the given order.
1181 C<path> - equivalent to C<$stream_location>, sets the stream location.
1182 Defaults to standard Unix location, or C<_PATH_LOG>.
1186 C<timeout> - equivalent to C<$sock_timeout>, sets the socket timeout
1187 in seconds. Defaults to 0 on all systems except S<Mac OS X> where it
1192 C<host> - sets the hostname to send the messages to. Defaults to
1197 C<port> - sets the TCP or UDP port to connect to. Defaults to the
1198 first standard syslog port available on the system.
1203 The available mechanisms are:
1209 C<"native"> - use the native C functions from your C<syslog(3)> library
1210 (added in C<Sys::Syslog> 0.15).
1214 C<"eventlog"> - send messages to the Win32 events logger (Win32 only;
1215 added in C<Sys::Syslog> 0.19).
1219 C<"tcp"> - connect to a TCP socket, on the C<syslog/tcp> or C<syslogng/tcp>
1220 service. See also the C<host>, C<port> and C<timeout> options.
1224 C<"udp"> - connect to a UDP socket, on the C<syslog/udp> service.
1225 See also the C<host>, C<port> and C<timeout> options.
1229 C<"inet"> - connect to an INET socket, either TCP or UDP, tried in that
1230 order. See also the C<host>, C<port> and C<timeout> options.
1234 C<"unix"> - connect to a UNIX domain socket (in some systems a character
1235 special device). The name of that socket is given by the C<path> option
1236 or, if omitted, the value returned by the C<_PATH_LOG> macro (if your
1237 system defines it), F</dev/log> or F</dev/conslog>, whichever is writable.
1241 C<"stream"> - connect to the stream indicated by the C<path> option, or,
1242 if omitted, the value returned by the C<_PATH_LOG> macro (if your system
1243 defines it), F</dev/log> or F</dev/conslog>, whichever is writable. For
1244 example Solaris and IRIX system may prefer C<"stream"> instead of C<"unix">.
1248 C<"pipe"> - connect to the named pipe indicated by the C<path> option,
1249 or, if omitted, to the value returned by the C<_PATH_LOG> macro (if your
1250 system defines it), or F</dev/log> (added in C<Sys::Syslog> 0.21).
1251 HP-UX is a system which uses such a named pipe.
1255 C<"console"> - send messages directly to the console, as for the C<"cons">
1256 option of C<openlog()>.
1260 The default is to try C<native>, C<tcp>, C<udp>, C<unix>, C<pipe>, C<stream>,
1262 Under systems with the Win32 API, C<eventlog> will be added as the first
1263 mechanism to try if C<Win32::EventLog> is available.
1265 Giving an invalid value for C<$sock_type> will C<croak>.
1269 Select the UDP socket mechanism:
1273 Send messages using the TCP socket mechanism on a custom port:
1275 setlogsock({ type => "tcp", port => 2486 });
1277 Send messages to a remote host using the TCP socket mechanism:
1279 setlogsock({ type => "tcp", host => $loghost });
1281 Try the native, UDP socket then UNIX domain socket mechanisms:
1283 setlogsock(["native", "udp", "unix"]);
1289 Now that the "native" mechanism is supported by C<Sys::Syslog> and selected
1290 by default, the use of the C<setlogsock()> function is discouraged because
1291 other mechanisms are less portable across operating systems. Authors of
1292 modules and programs that use this function, especially its cargo-cult form
1293 C<setlogsock("unix")>, are advised to remove any occurrence of it unless they
1294 specifically want to use a given mechanism (like TCP or UDP to connect to
1301 Closes the log file and returns true on success.
1306 =head1 THE RULES OF SYS::SYSLOG
1308 I<The First Rule of Sys::Syslog is:>
1309 You do not call C<setlogsock>.
1311 I<The Second Rule of Sys::Syslog is:>
1312 You B<do not> call C<setlogsock>.
1314 I<The Third Rule of Sys::Syslog is:>
1315 The program crashes, C<die>s, calls C<closelog>, the log is over.
1317 I<The Fourth Rule of Sys::Syslog is:>
1318 One facility, one priority.
1320 I<The Fifth Rule of Sys::Syslog is:>
1323 I<The Sixth Rule of Sys::Syslog is:>
1324 No C<syslog> before C<openlog>.
1326 I<The Seventh Rule of Sys::Syslog is:>
1327 Logs will go on as long as they have to.
1329 I<The Eighth, and Final Rule of Sys::Syslog is:>
1330 If this is your first use of Sys::Syslog, you must read the doc.
1337 openlog($program, 'cons,pid', 'user');
1338 syslog('info', '%s', 'this is another test');
1339 syslog('mail|warning', 'this is a better test: %d', time);
1342 syslog('debug', 'this is the last test');
1346 openlog("$program $$", 'ndelay', 'user');
1347 syslog('notice', 'fooprogram: this is really done');
1349 Example of use of C<%m>:
1352 syslog('info', 'problem was %m'); # %m == $! in syslog(3)
1354 Log to UDP port on C<$remotehost> instead of logging locally:
1356 setlogsock("udp", $remotehost);
1357 openlog($program, 'ndelay', 'user');
1358 syslog('info', 'something happened over here');
1369 C<LOG_AUDIT> - audit daemon (IRIX); falls back to C<LOG_AUTH>
1373 C<LOG_AUTH> - security/authorization messages
1377 C<LOG_AUTHPRIV> - security/authorization messages (private)
1381 C<LOG_CONSOLE> - C</dev/console> output (FreeBSD); falls back to C<LOG_USER>
1385 C<LOG_CRON> - clock daemons (B<cron> and B<at>)
1389 C<LOG_DAEMON> - system daemons without separate facility value
1393 C<LOG_FTP> - FTP daemon
1397 C<LOG_KERN> - kernel messages
1401 C<LOG_INSTALL> - installer subsystem (Mac OS X); falls back to C<LOG_USER>
1405 C<LOG_LAUNCHD> - launchd - general bootstrap daemon (Mac OS X);
1406 falls back to C<LOG_DAEMON>
1410 C<LOG_LFMT> - logalert facility; falls back to C<LOG_USER>
1414 C<LOG_LOCAL0> through C<LOG_LOCAL7> - reserved for local use
1418 C<LOG_LPR> - line printer subsystem
1422 C<LOG_MAIL> - mail subsystem
1426 C<LOG_NETINFO> - NetInfo subsystem (Mac OS X); falls back to C<LOG_DAEMON>
1430 C<LOG_NEWS> - USENET news subsystem
1434 C<LOG_NTP> - NTP subsystem (FreeBSD, NetBSD); falls back to C<LOG_DAEMON>
1438 C<LOG_RAS> - Remote Access Service (VPN / PPP) (Mac OS X);
1439 falls back to C<LOG_AUTH>
1443 C<LOG_REMOTEAUTH> - remote authentication/authorization (Mac OS X);
1444 falls back to C<LOG_AUTH>
1448 C<LOG_SECURITY> - security subsystems (firewalling, etc.) (FreeBSD);
1449 falls back to C<LOG_AUTH>
1453 C<LOG_SYSLOG> - messages generated internally by B<syslogd>
1457 C<LOG_USER> (default) - generic user-level messages
1461 C<LOG_UUCP> - UUCP subsystem
1472 C<LOG_EMERG> - system is unusable
1476 C<LOG_ALERT> - action must be taken immediately
1480 C<LOG_CRIT> - critical conditions
1484 C<LOG_ERR> - error conditions
1488 C<LOG_WARNING> - warning conditions
1492 C<LOG_NOTICE> - normal, but significant, condition
1496 C<LOG_INFO> - informational message
1500 C<LOG_DEBUG> - debug-level message
1509 =item C<Invalid argument passed to setlogsock>
1511 B<(F)> You gave C<setlogsock()> an invalid value for C<$sock_type>.
1513 =item C<eventlog passed to setlogsock, but no Win32 API available>
1515 B<(W)> You asked C<setlogsock()> to use the Win32 event logger but the
1516 operating system running the program isn't Win32 or does not provides Win32
1517 compatible facilities.
1519 =item C<no connection to syslog available>
1521 B<(F)> C<syslog()> failed to connect to the specified socket.
1523 =item C<stream passed to setlogsock, but %s is not writable>
1525 B<(W)> You asked C<setlogsock()> to use a stream socket, but the given
1526 path is not writable.
1528 =item C<stream passed to setlogsock, but could not find any device>
1530 B<(W)> You asked C<setlogsock()> to use a stream socket, but didn't
1531 provide a path, and C<Sys::Syslog> was unable to find an appropriate one.
1533 =item C<tcp passed to setlogsock, but tcp service unavailable>
1535 B<(W)> You asked C<setlogsock()> to use a TCP socket, but the service
1536 is not available on the system.
1538 =item C<syslog: expecting argument %s>
1540 B<(F)> You forgot to give C<syslog()> the indicated argument.
1542 =item C<syslog: invalid level/facility: %s>
1544 B<(F)> You specified an invalid level or facility.
1546 =item C<syslog: too many levels given: %s>
1548 B<(F)> You specified too many levels.
1550 =item C<syslog: too many facilities given: %s>
1552 B<(F)> You specified too many facilities.
1554 =item C<syslog: level must be given>
1556 B<(F)> You forgot to specify a level.
1558 =item C<udp passed to setlogsock, but udp service unavailable>
1560 B<(W)> You asked C<setlogsock()> to use a UDP socket, but the service
1561 is not available on the system.
1563 =item C<unix passed to setlogsock, but path not available>
1565 B<(W)> You asked C<setlogsock()> to use a UNIX socket, but C<Sys::Syslog>
1566 was unable to find an appropriate an appropriate device.
1573 C<Sys::Syslog> is a core module, part of the standard Perl distribution
1574 since 1990. At this time, modules as we know them didn't exist, the
1575 Perl library was a collection of F<.pl> files, and the one for sending
1576 syslog messages with was simply F<lib/syslog.pl>, included with Perl 3.0.
1577 It was converted as a module with Perl 5.0, but had a version number
1578 only starting with Perl 5.6. Here is a small table with the matching
1579 Perl and C<Sys::Syslog> versions.
1586 0.04 5.8.1, 5.8.2, 5.8.3
1587 0.05 5.8.4, 5.8.5, 5.8.6
1591 0.27 5.8.9, 5.10.1 ~ 5.14.*
1600 =head2 Other modules
1602 L<Log::Log4perl> - Perl implementation of the Log4j API
1604 L<Log::Dispatch> - Dispatches messages to one or more outputs
1606 L<Log::Report> - Report a problem, with exceptions and language support
1612 SUSv3 issue 6, IEEE Std 1003.1, 2004 edition,
1613 L<http://www.opengroup.org/onlinepubs/000095399/basedefs/syslog.h.html>
1615 GNU C Library documentation on syslog,
1616 L<http://www.gnu.org/software/libc/manual/html_node/Syslog.html>
1618 FreeBSD documentation on syslog,
1619 L<https://www.freebsd.org/cgi/man.cgi?query=syslog>
1621 Solaris 11 documentation on syslog,
1622 L<https://docs.oracle.com/cd/E53394_01/html/E54766/syslog-3c.html>
1624 Mac OS X documentation on syslog,
1625 L<http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/syslog.3.html>
1627 IRIX documentation on syslog,
1628 L<http://nixdoc.net/man-pages/IRIX/man3/syslog.3c.html>
1630 AIX 5L 5.3 documentation on syslog,
1631 L<http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf2/syslog.htm>
1633 HP-UX 11i documentation on syslog,
1634 L<http://docs.hp.com/en/B2355-60130/syslog.3C.html>
1636 Tru64 documentation on syslog,
1637 L<http://nixdoc.net/man-pages/Tru64/man3/syslog.3.html>
1640 L<http://stratadoc.stratus.com/vos/15.1.1/r502-01/wwhelp/wwhimpl/js/html/wwhelp.htm?context=r502-01&file=ch5r502-01bi.html>
1644 I<RFC 3164 - The BSD syslog Protocol>, L<http://www.faqs.org/rfcs/rfc3164.html>
1645 -- Please note that this is an informational RFC, and therefore does not
1646 specify a standard of any kind.
1648 I<RFC 3195 - Reliable Delivery for syslog>, L<http://www.faqs.org/rfcs/rfc3195.html>
1652 I<Syslogging with Perl>, L<http://lexington.pm.org/meetings/022001.html>
1657 L<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wes/wes/windows_event_log.asp>
1660 =head1 AUTHORS & ACKNOWLEDGEMENTS
1662 Tom Christiansen E<lt>F<tchrist (at) perl.com>E<gt> and Larry Wall
1663 E<lt>F<larry (at) wall.org>E<gt>.
1665 UNIX domain sockets added by Sean Robinson
1666 E<lt>F<robinson_s (at) sc.maricopa.edu>E<gt> with support from Tim Bunce
1667 E<lt>F<Tim.Bunce (at) ig.co.uk>E<gt> and the C<perl5-porters> mailing list.
1669 Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
1670 E<lt>F<tom (at) compton.nu>E<gt>.
1672 Code for C<constant()>s regenerated by Nicholas Clark E<lt>F<nick (at) ccl4.org>E<gt>.
1674 Failover to different communication modes by Nick Williams
1675 E<lt>F<Nick.Williams (at) morganstanley.com>E<gt>.
1677 Extracted from core distribution for publishing on the CPAN by
1678 SE<eacute>bastien Aperghis-Tramoni E<lt>sebastien (at) aperghis.netE<gt>.
1680 XS code for using native C functions borrowed from C<L<Unix::Syslog>>,
1681 written by Marcus Harnisch E<lt>F<marcus.harnisch (at) gmx.net>E<gt>.
1683 Yves Orton suggested and helped for making C<Sys::Syslog> use the native
1684 event logger under Win32 systems.
1686 Jerry D. Hedden and Reini Urban provided greatly appreciated help to
1687 debug and polish C<Sys::Syslog> under Cygwin.
1692 Please report any bugs or feature requests to
1693 C<bug-sys-syslog (at) rt.cpan.org>, or through the web interface at
1694 L<http://rt.cpan.org/Public/Dist/Display.html?Name=Sys-Syslog>.
1695 I will be notified, and then you'll automatically be notified of progress on
1696 your bug as I make changes.
1701 You can find documentation for this module with the perldoc command.
1705 You can also look for information at:
1709 =item * Perl Documentation
1711 L<http://perldoc.perl.org/Sys/Syslog.html>
1715 L<https://metacpan.org/module/Sys::Syslog>
1719 L<http://search.cpan.org/dist/Sys-Syslog/>
1721 =item * AnnoCPAN: Annotated CPAN documentation
1723 L<http://annocpan.org/dist/Sys-Syslog>
1725 =item * CPAN Ratings
1727 L<http://cpanratings.perl.org/d/Sys-Syslog>
1729 =item * RT: CPAN's request tracker
1731 L<http://rt.cpan.org/Dist/Display.html?Queue=Sys-Syslog>
1735 The source code is available on Git Hub:
1736 L<https://github.com/maddingue/Sys-Syslog/>
1741 Copyright (C) 1990-2012 by Larry Wall and others.
1746 This program is free software; you can redistribute it and/or modify it
1747 under the same terms as Perl itself.
1753 Notes for the future maintainer (even if it's still me..)
1754 - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1756 Using Google Code Search, I search who on Earth was relying on $host being
1757 public. It found 5 hits:
1759 * First was inside Indigo Star Perl2exe documentation. Just an old version
1763 * One real hit was inside DalWeathDB, a weather related program. It simply
1766 $Sys::Syslog::host = '127.0.0.1';
1768 - L<http://www.gallistel.net/nparker/weather/code/>
1771 * Two hits were in TPC, a fax server thingy. It does a
1773 $Sys::Syslog::host = $TPC::LOGHOST;
1775 but also has this strange piece of code:
1777 # work around perl5.003 bug
1778 sub Sys::Syslog::hostname {}
1780 I don't know what bug the author referred to.
1782 - L<http://www.tpc.int/>
1783 - L<ftp://ftp-usa.tpc.int/pub/tpc/server/UNIX/>
1786 * Last hit was in Filefix, which seems to be a FIDOnet mail program (!).
1787 This one does not use $host, but has the following piece of code:
1789 sub Sys::Syslog::hostname
1795 I guess this was a more elaborate form of the previous bit, maybe because
1796 of a bug in Sys::Syslog back then?
1798 - L<ftp://ftp.kiae.su/pub/unix/fido/>
1804 - L<http://www.openss7.org/streams.html>
1806 II12021: SYSLOGD HOWTO TCPIPINFO (z/OS, OS/390, MVS)
1807 - L<http://www-1.ibm.com/support/docview.wss?uid=isg1II12021>
1809 Getting the most out of the Event Viewer
1810 - L<http://www.codeproject.com/dotnet/evtvwr.asp?print=true>
1812 Log events to the Windows NT Event Log with JNI
1813 - L<http://www.javaworld.com/javaworld/jw-09-2001/jw-0928-ntmessages.html>