4 use warnings::register;
6 use Exporter qw< import >;
8 use POSIX qw< strftime setlocale LC_TIME >;
17 standard => [qw(openlog syslog closelog setlogmask)],
18 extended => [qw(setlogsock)],
22 LOG_ALERT LOG_CRIT LOG_DEBUG LOG_EMERG LOG_ERR
23 LOG_INFO LOG_NOTICE LOG_WARNING
28 LOG_AUTH LOG_AUTHPRIV LOG_CRON LOG_DAEMON LOG_FTP LOG_KERN
29 LOG_LOCAL0 LOG_LOCAL1 LOG_LOCAL2 LOG_LOCAL3 LOG_LOCAL4
30 LOG_LOCAL5 LOG_LOCAL6 LOG_LOCAL7 LOG_LPR LOG_MAIL LOG_NEWS
31 LOG_SYSLOG LOG_USER LOG_UUCP
33 # Mac OS X specific facilities
34 qw( LOG_INSTALL LOG_LAUNCHD LOG_NETINFO LOG_RAS LOG_REMOTEAUTH ),
35 # modern BSD specific facilities
36 qw( LOG_CONSOLE LOG_NTP LOG_SECURITY ),
37 # IRIX specific facilities
38 qw( LOG_AUDIT LOG_LFMT ),
42 LOG_CONS LOG_PID LOG_NDELAY LOG_NOWAIT LOG_ODELAY LOG_PERROR
47 LOG_FACMASK LOG_NFACILITIES LOG_PRIMASK
54 @{$EXPORT_TAGS{standard}},
58 @{$EXPORT_TAGS{extended}},
59 @{$EXPORT_TAGS{macros}},
64 XSLoader::load('Sys::Syslog', $VERSION);
68 push @ISA, 'DynaLoader';
69 bootstrap Sys::Syslog $VERSION;
77 use vars qw($host); # host to send syslog messages to (see notes at end)
87 use vars qw($facility);
88 my $connected = 0; # flag to indicate if we're connected or not
89 my $syslog_send; # coderef of the function used to send messages
90 my $syslog_path = undef; # syslog path for "stream" and "unix" mechanisms
91 my $syslog_xobj = undef; # if defined, holds the external object used to send messages
92 my $transmit_ok = 0; # flag to indicate if the last message was transmitted
93 my $sock_port = undef; # socket port
94 my $sock_timeout = 0; # socket timeout, see below
95 my $current_proto = undef; # current mechanism used to transmit messages
96 my $ident = ''; # identifiant prepended to each message
97 $facility = ''; # current facility
98 my $maskpri = LOG_UPTO(&LOG_DEBUG); # current log mask
110 # Default is now to first use the native mechanism, so Perl programs
111 # behave like other normal Unix programs, then try other mechanisms.
112 my @connectMethods = qw(native tcp udp unix pipe stream console);
113 if ($^O eq "freebsd" or $^O eq "linux") {
114 @connectMethods = grep { $_ ne 'udp' } @connectMethods;
117 # And on Win32 systems, we try to use the native mechanism for this
118 # platform, the events logger, available through Win32::EventLog.
120 my $is_Win32 = $^O =~ /Win32/i;
122 if (can_load("Sys::Syslog::Win32", $is_Win32)) {
123 unshift @connectMethods, 'eventlog';
127 my @defaultMethods = @connectMethods;
128 my @fallbackMethods = ();
130 # The timeout in connection_ok() was pushed up to 0.25 sec in
131 # Sys::Syslog v0.19 in order to address a heisenbug on MacOSX:
132 # http://london.pm.org/pipermail/london.pm/Week-of-Mon-20061211/005961.html
134 # However, this also had the effect of slowing this test for
135 # all other operating systems, which apparently impacted some
136 # users (cf. CPAN-RT #34753). So, in order to make everybody
137 # happy, the timeout is now zero by default on all systems
138 # except on OSX where it is set to 250 msec, and can be set
139 # with the infamous setlogsock() function.
141 # Update 2011-08: this issue is also been seen on multiprocessor
142 # Debian GNU/kFreeBSD systems. See http://bugs.debian.org/627821
143 # and https://rt.cpan.org/Ticket/Display.html?id=69997
144 # Also, lowering the delay to 1 ms, which should be enough.
146 $sock_timeout = 0.001 if $^O =~ /darwin|gnukfreebsd/;
149 # Perl 5.6.0's warnings.pm doesn't have warnings::warnif()
150 if (not defined &warnings::warnif) {
151 *warnings::warnif = sub {
152 goto &warnings::warn if warnings::enabled(__PACKAGE__)
156 # coderef for a nicer handling of errors
157 my $err_sub = $options{nofatal} ? \&warnings::warnif : \&croak;
161 # This AUTOLOAD is used to 'autoload' constants from the constant()
165 ($constname = $AUTOLOAD) =~ s/.*:://;
166 croak "Sys::Syslog::constant() not defined" if $constname eq 'constant';
167 my ($error, $val) = constant($constname);
168 croak $error if $error;
170 *$AUTOLOAD = sub { $val };
176 ($ident, my $logopt, $facility) = @_;
179 $ident ||= basename($0) || getlogin() || getpwuid($<) || 'syslog';
181 $facility ||= LOG_USER();
183 for my $opt (split /\b/, $logopt) {
184 $options{$opt} = 1 if exists $options{$opt}
187 $err_sub = delete $options{nofatal} ? \&warnings::warnif : \&croak;
188 return 1 unless $options{ndelay};
193 disconnect_log() if $connected;
194 $options{$_} = 0 for keys %options;
195 $facility = $ident = "";
201 my $oldmask = $maskpri;
202 $maskpri = shift unless $_[0] == 0;
212 check => sub { return can_load("Win32::EventLog") },
213 err_msg => "no Win32 API available",
223 ($syslog_path) = grep { defined && length && -p && -w _ }
224 $syslog_path, &_PATH_LOG, "/dev/log";
225 return $syslog_path ? 1 : 0
227 err_msg => "path not available",
231 if (not defined $syslog_path) {
232 my @try = qw(/dev/log /dev/conslog);
233 unshift @try, &_PATH_LOG if length &_PATH_LOG;
234 ($syslog_path) = grep { -w } @try;
236 return defined $syslog_path && -w $syslog_path
238 err_msg => "could not find any writable device",
242 return 1 if defined $sock_port;
244 if (getservbyname('syslog', 'tcp') || getservbyname('syslogng', 'tcp')) {
245 $host = $syslog_path;
252 err_msg => "TCP service unavailable",
256 return 1 if defined $sock_port;
258 if (getservbyname('syslog', 'udp')) {
259 $host = $syslog_path;
266 err_msg => "UDP service unavailable",
270 my @try = ($syslog_path, &_PATH_LOG);
271 ($syslog_path) = grep { defined && length && -w } @try;
272 return defined $syslog_path && -w $syslog_path
274 err_msg => "path not available",
282 # - old API: setlogsock($sock_type, $sock_path, $sock_timeout)
283 # - new API: setlogsock(\%options)
284 croak "setlogsock(): Invalid number of arguments"
285 unless @_ >= 1 and @_ <= 3;
287 if (my $ref = ref $_[0]) {
288 if ($ref eq "HASH") {
290 croak "setlogsock(): No argument given" unless keys %opt;
292 elsif ($ref eq "ARRAY") {
293 @opt{qw< type path timeout >} = @_;
296 croak "setlogsock(): Unexpected \L$ref\E reference"
300 @opt{qw< type path timeout >} = @_;
303 # check socket type, remove invalid ones
304 my $diag_invalid_type = "setlogsock(): Invalid type%s; must be one of "
305 . join ", ", map { "'$_'" } sort keys %mechanism;
306 croak sprintf $diag_invalid_type, "" unless defined $opt{type};
307 my @sock_types = ref $opt{type} eq "ARRAY" ? @{$opt{type}} : ($opt{type});
310 for my $sock_type (@sock_types) {
311 carp sprintf $diag_invalid_type, " '$sock_type'" and next
312 unless exists $mechanism{$sock_type};
313 push @tmp, "tcp", "udp" and next if $sock_type eq "inet";
314 push @tmp, $sock_type;
320 $syslog_path = $opt{path} if defined $opt{path};
321 $host = $opt{host} if defined $opt{host};
322 $sock_timeout = $opt{timeout} if defined $opt{timeout};
323 $sock_port = $opt{port} if defined $opt{port};
325 disconnect_log() if $connected;
327 @fallbackMethods = ();
328 @connectMethods = ();
331 # check each given mechanism and test if it can be used on the current system
332 for my $sock_type (@sock_types) {
333 if ( $mechanism{$sock_type}{check}->() ) {
334 push @connectMethods, $sock_type;
338 warnings::warnif("setlogsock(): type='$sock_type': "
339 . $mechanism{$sock_type}{err_msg});
343 # if no mechanism worked from the given ones, use the default ones
344 @connectMethods = @defaultMethods unless @connectMethods;
350 my ($priority, $mask, @args) = @_;
352 my (@words, $num, $numpri, $numfac, $sum);
354 my $fail_time = undef;
357 # if $ident is undefined, it means openlog() wasn't previously called
358 # so do it now in order to have sensible defaults
359 openlog() unless $ident;
361 local $facility = $facility; # may need to change temporarily.
363 croak "syslog: expecting argument \$priority" unless defined $priority;
364 croak "syslog: expecting argument \$format" unless defined $mask;
366 if ($priority =~ /^\d+$/) {
367 $numpri = LOG_PRI($priority);
368 $numfac = LOG_FAC($priority) << 3;
370 elsif ($priority =~ /^\w+/) {
371 # Allow "level" or "level|facility".
372 @words = split /\W+/, $priority, 2;
377 for my $word (@words) {
378 next if length $word == 0;
380 # Translate word to number.
384 croak "syslog: invalid level/facility: $word"
386 elsif ($num <= LOG_PRIMASK() and $word ne "kern") {
387 croak "syslog: too many levels given: $word"
392 croak "syslog: too many facilities given: $word"
394 $facility = $word if $word =~ /^[A-Za-z]/;
400 croak "syslog: invalid level/facility: $priority"
403 croak "syslog: level must be given" unless defined $numpri;
405 # don't log if priority is below mask level
406 return 0 unless LOG_MASK($numpri) & $maskpri;
408 if (not defined $numfac) { # Facility not specified in this call.
409 $facility = 'user' unless $facility;
410 $numfac = xlate($facility);
413 connect_log() unless $connected;
416 # escape percent signs for sprintf()
417 $error =~ s/%/%%/g if @args;
418 # replace %m with $error, if preceded by an even number of percent signs
419 $mask =~ s/(?<!%)((?:%%)*)%m/$1$error/g;
422 $mask .= "\n" unless $mask =~ /\n$/;
423 $message = @args ? sprintf($mask, @args) : $mask;
425 if ($current_proto eq 'native') {
428 elsif ($current_proto eq 'eventlog') {
433 $whoami .= "[$$]" if $options{pid};
435 $sum = $numpri + $numfac;
436 my $oldlocale = setlocale(LC_TIME);
437 setlocale(LC_TIME, 'C');
438 my $timestamp = strftime "%b %d %H:%M:%S", localtime;
439 setlocale(LC_TIME, $oldlocale);
441 # construct the stream that will be transmitted
442 $buf = "<$sum>$timestamp $whoami: $message";
444 # add (or not) a newline
445 $buf .= "\n" if !$options{noeol} and rindex($buf, "\n") == -1;
447 # add (or not) a NUL character
448 $buf .= "\0" if !$options{nonul};
451 # handle PERROR option
452 # "native" mechanism already handles it by itself
453 if ($options{perror} and $current_proto ne 'native') {
455 $whoami .= "[$$]" if $options{pid};
456 print STDERR "$whoami: $message\n";
459 # it's possible that we'll get an error from sending
460 # (e.g. if method is UDP and there is no UDP listener,
461 # then we'll get ECONNREFUSED on the send). So what we
462 # want to do at this point is to fallback onto a different
464 while (scalar @fallbackMethods || $syslog_send) {
465 if ($failed && (time - $fail_time) > 60) {
466 # it's been a while... maybe things have been fixed
467 @fallbackMethods = ();
469 $transmit_ok = 0; # make it look like a fresh attempt
473 if ($connected && !connection_ok()) {
474 # Something was OK, but has now broken. Remember coz we'll
475 # want to go back to what used to be OK.
476 $failed = $current_proto unless $failed;
481 connect_log() unless $connected;
482 $failed = undef if ($current_proto && $failed && $current_proto eq $failed);
485 if ($syslog_send->($buf, $numpri, $numfac)) {
489 # typically doesn't happen, since errors are rare from write().
493 # could not send, could not fallback onto a working
494 # connection method. Lose.
498 sub _syslog_send_console {
501 # The console print is a method which could block
502 # so we do it in a child process and always return success
504 if (my $pid = fork) {
506 if ($options{nowait}) {
509 if (waitpid($pid, 0) >= 0) {
512 # it's possible that the caller has other
513 # plans for SIGCHLD, so let's not interfere
518 if (open(CONS, ">/dev/console")) {
519 my $ret = print CONS $buf . "\r"; # XXX: should this be \x0A ?
520 POSIX::_exit($ret) if defined $pid;
524 POSIX::_exit(0) if defined $pid;
528 sub _syslog_send_stream {
530 # XXX: this only works if the OS stream implementation makes a write
531 # look like a putmsg() with simple header. For instance it works on
532 # Solaris 8 but not Solaris 7.
533 # To be correct, it should use a STREAMS API, but perl doesn't have one.
534 return syswrite(SYSLOG, $buf, length($buf));
537 sub _syslog_send_pipe {
539 return print SYSLOG $buf;
542 sub _syslog_send_socket {
544 return syswrite(SYSLOG, $buf, length($buf));
545 #return send(SYSLOG, $buf, 0);
548 sub _syslog_send_native {
549 my ($buf, $numpri, $numfac) = @_;
550 syslog_xs($numpri|$numfac, $buf);
557 # private function to translate names to numeric values
562 return $name+0 if $name =~ /^\s*\d+\s*$/;
564 $name = "LOG_$name" unless $name =~ /^LOG_/;
566 # ExtUtils::Constant 0.20 introduced a new way to implement
567 # constants, called ProxySubs. When it was used to generate
568 # the C code, the constant() function no longer returns the
569 # correct value. Therefore, we first try a direct call to
570 # constant(), and if the value is an error we try to call the
571 # constant by its full name.
572 my $value = constant($name);
574 if (index($value, "not a valid") >= 0) {
575 $name = "Sys::Syslog::$name";
576 $value = eval { no strict "refs"; &$name };
577 $value = $@ unless defined $value;
580 $value = -1 if index($value, "not a valid") >= 0;
582 return defined $value ? $value : -1;
588 # This function acts as a kind of front-end: it tries to connect to
589 # a syslog service using the selected methods, trying each one in the
593 @fallbackMethods = @connectMethods unless scalar @fallbackMethods;
595 if ($transmit_ok && $current_proto) {
596 # Retry what we were on, because it has worked in the past.
597 unshift(@fallbackMethods, $current_proto);
604 while ($proto = shift @fallbackMethods) {
606 my $fn = "connect_$proto";
607 $connected = &$fn(\@errs) if defined &$fn;
613 $current_proto = $proto;
614 my ($old) = select(SYSLOG); $| = 1; select($old);
616 @fallbackMethods = ();
617 $err_sub->(join "\n\t- ", "no connection to syslog available", @errs);
625 my $proto = getprotobyname('tcp');
626 if (!defined $proto) {
627 push @$errs, "getprotobyname failed for tcp";
631 my $port = $sock_port || getservbyname('syslog', 'tcp');
632 $port = getservbyname('syslogng', 'tcp') unless defined $port;
633 if (!defined $port) {
634 push @$errs, "getservbyname failed for syslog/tcp and syslogng/tcp";
640 $addr = inet_aton($host);
642 push @$errs, "can't lookup $host";
646 $addr = INADDR_LOOPBACK;
648 $addr = sockaddr_in($port, $addr);
650 if (!socket(SYSLOG, AF_INET, SOCK_STREAM, $proto)) {
651 push @$errs, "tcp socket: $!";
655 setsockopt(SYSLOG, SOL_SOCKET, SO_KEEPALIVE, 1);
656 if (silent_eval { IPPROTO_TCP() }) {
657 # These constants don't exist in 5.005. They were added in 1999
658 setsockopt(SYSLOG, IPPROTO_TCP(), TCP_NODELAY(), 1);
660 if (!connect(SYSLOG, $addr)) {
661 push @$errs, "tcp connect: $!";
665 $syslog_send = \&_syslog_send_socket;
673 my $proto = getprotobyname('udp');
674 if (!defined $proto) {
675 push @$errs, "getprotobyname failed for udp";
679 my $port = $sock_port || getservbyname('syslog', 'udp');
680 if (!defined $port) {
681 push @$errs, "getservbyname failed for syslog/udp";
687 $addr = inet_aton($host);
689 push @$errs, "can't lookup $host";
693 $addr = INADDR_LOOPBACK;
695 $addr = sockaddr_in($port, $addr);
697 if (!socket(SYSLOG, AF_INET, SOCK_DGRAM, $proto)) {
698 push @$errs, "udp socket: $!";
701 if (!connect(SYSLOG, $addr)) {
702 push @$errs, "udp connect: $!";
706 # We want to check that the UDP connect worked. However the only
707 # way to do that is to send a message and see if an ICMP is returned
708 _syslog_send_socket("");
709 if (!connection_ok()) {
710 push @$errs, "udp connect: nobody listening";
714 $syslog_send = \&_syslog_send_socket;
721 # might want syslog_path to be variable based on syslog.h (if only
723 $syslog_path = '/dev/conslog' unless defined $syslog_path;
725 if (!-w $syslog_path) {
726 push @$errs, "stream $syslog_path is not writable";
732 if (!sysopen(SYSLOG, $syslog_path, Fcntl::O_WRONLY(), 0400)) {
733 push @$errs, "stream can't open $syslog_path: $!";
737 $syslog_send = \&_syslog_send_stream;
745 $syslog_path ||= &_PATH_LOG || "/dev/log";
747 if (not -w $syslog_path) {
748 push @$errs, "$syslog_path is not writable";
752 if (not open(SYSLOG, ">$syslog_path")) {
753 push @$errs, "can't write to $syslog_path: $!";
757 $syslog_send = \&_syslog_send_pipe;
765 $syslog_path ||= _PATH_LOG() if length _PATH_LOG();
767 if (not defined $syslog_path) {
768 push @$errs, "_PATH_LOG not available in syslog.h and no user-supplied socket path";
772 if (not (-S $syslog_path or -c _)) {
773 push @$errs, "$syslog_path is not a socket";
777 my $addr = sockaddr_un($syslog_path);
779 push @$errs, "can't locate $syslog_path";
782 if (!socket(SYSLOG, AF_UNIX, SOCK_STREAM, 0)) {
783 push @$errs, "unix stream socket: $!";
787 if (!connect(SYSLOG, $addr)) {
788 if (!socket(SYSLOG, AF_UNIX, SOCK_DGRAM, 0)) {
789 push @$errs, "unix dgram socket: $!";
792 if (!connect(SYSLOG, $addr)) {
793 push @$errs, "unix dgram connect: $!";
798 $syslog_send = \&_syslog_send_socket;
807 # reconstruct the numeric equivalent of the options
808 for my $opt (keys %options) {
809 $logopt += xlate($opt) if $options{$opt}
812 openlog_xs($ident, $logopt, xlate($facility));
813 $syslog_send = \&_syslog_send_native;
818 sub connect_eventlog {
821 $syslog_xobj = Sys::Syslog::Win32::_install();
822 $syslog_send = \&Sys::Syslog::Win32::_syslog_send;
827 sub connect_console {
829 if (!-w '/dev/console') {
830 push @$errs, "console is not writable";
833 $syslog_send = \&_syslog_send_console;
837 # To test if the connection is still good, we need to check if any
838 # errors are present on the connection. The errors will not be raised
839 # by a write. Instead, sockets are made readable and the next read
840 # would cause the error to be returned. Unfortunately the syslog
841 # 'protocol' never provides anything for us to read. But with
842 # judicious use of select(), we can see if it would be readable...
844 return 1 if defined $current_proto and (
845 $current_proto eq 'native' or $current_proto eq 'console'
846 or $current_proto eq 'eventlog'
850 vec($rin, fileno(SYSLOG), 1) = 1;
851 my $ret = select $rin, undef, $rin, $sock_timeout;
852 return ($ret ? 0 : 1);
857 $syslog_send = undef;
859 if (defined $current_proto and $current_proto eq 'native') {
861 unshift @fallbackMethods, $current_proto;
862 $current_proto = undef;
865 elsif (defined $current_proto and $current_proto eq 'eventlog') {
866 $syslog_xobj->Close();
867 unshift @fallbackMethods, $current_proto;
868 $current_proto = undef;
877 # Wrappers around eval() that makes sure that nobody, and I say NOBODY,
878 # ever knows that I wanted to test if something was here or not.
879 # It is needed because some applications are trying to be too smart,
880 # do it wrong, and it ends up in EPIC FAIL.
881 # Yes I'm speaking of YOU, SpamAssassin.
883 sub silent_eval (&) {
884 local($SIG{__DIE__}, $SIG{__WARN__}, $@);
885 return eval { $_[0]->() }
889 my ($module, $verbose) = @_;
890 local($SIG{__DIE__}, $SIG{__WARN__}, $@);
891 my $loaded = eval "use $module; 1";
892 warn $@ if not $loaded and $verbose;
897 "Eighth Rule: read the documentation."
903 Sys::Syslog - Perl interface to the UNIX syslog(3) calls
907 This is the documentation of version 0.33
911 use Sys::Syslog; # all except setlogsock()
912 use Sys::Syslog qw(:standard :macros); # standard functions & macros
914 openlog($ident, $logopt, $facility); # don't forget this
915 syslog($priority, $format, @args);
916 $oldmask = setlogmask($mask_priority);
922 C<Sys::Syslog> is an interface to the UNIX C<syslog(3)> program.
923 Call C<syslog()> with a string priority and a list of C<printf()> args
924 just like C<syslog(3)>.
929 C<Sys::Syslog> exports the following C<Exporter> tags:
935 C<:standard> exports the standard C<syslog(3)> functions:
937 openlog closelog setlogmask syslog
941 C<:extended> exports the Perl specific functions for C<syslog(3)>:
947 C<:macros> exports the symbols corresponding to most of your C<syslog(3)>
948 macros and the C<LOG_UPTO()> and C<LOG_MASK()> functions.
949 See L<"CONSTANTS"> for the supported constants and their meaning.
953 By default, C<Sys::Syslog> exports the symbols from the C<:standard> tag.
960 =item B<openlog($ident, $logopt, $facility)>
963 C<$ident> is prepended to every message. C<$logopt> contains zero or
964 more of the options detailed below. C<$facility> specifies the part
965 of the system to report about, for example C<LOG_USER> or C<LOG_LOCAL0>:
966 see L<"Facilities"> for a list of well-known facilities, and your
967 C<syslog(3)> documentation for the facilities available in your system.
968 Check L<"SEE ALSO"> for useful links. Facility can be given as a string
971 This function will croak if it can't connect to the syslog daemon.
973 Note that C<openlog()> now takes three arguments, just like C<openlog(3)>.
975 B<You should use C<openlog()> before calling C<syslog()>.>
983 C<cons> - This option is ignored, since the failover mechanism will drop
984 down to the console automatically if all other media fail.
988 C<ndelay> - Open the connection immediately (normally, the connection is
989 opened when the first message is logged).
993 C<noeol> - When set to true, no end of line character (C<\n>) will be
994 appended to the message. This can be useful for some buggy syslog daemons.
998 C<nofatal> - When set to true, C<openlog()> and C<syslog()> will only
999 emit warnings instead of dying if the connection to the syslog can't
1004 C<nonul> - When set to true, no C<NUL> character (C<\0>) will be
1005 appended to the message. This can be useful for some buggy syslog daemons.
1009 C<nowait> - Don't wait for child processes that may have been created
1010 while logging the message. (The GNU C library does not create a child
1011 process, so this option has no effect on Linux.)
1015 C<perror> - Write the message to standard error output as well to the
1016 system log (added in C<Sys::Syslog> 0.22).
1020 C<pid> - Include PID with each message.
1026 Open the syslog with options C<ndelay> and C<pid>, and with facility C<LOCAL0>:
1028 openlog($name, "ndelay,pid", "local0");
1030 Same thing, but this time using the macro corresponding to C<LOCAL0>:
1032 openlog($name, "ndelay,pid", LOG_LOCAL0);
1035 =item B<syslog($priority, $message)>
1037 =item B<syslog($priority, $format, @args)>
1039 If C<$priority> permits, logs C<$message> or C<sprintf($format, @args)>
1040 with the addition that C<%m> in $message or C<$format> is replaced with
1041 C<"$!"> (the latest error message).
1043 C<$priority> can specify a level, or a level and a facility. Levels and
1044 facilities can be given as strings or as macros. When using the C<eventlog>
1045 mechanism, priorities C<DEBUG> and C<INFO> are mapped to event type
1046 C<informational>, C<NOTICE> and C<WARNING> to C<warning> and C<ERR> to
1047 C<EMERG> to C<error>.
1049 If you didn't use C<openlog()> before using C<syslog()>, C<syslog()> will
1050 try to guess the C<$ident> by extracting the shortest prefix of
1051 C<$format> that ends in a C<":">.
1055 # informational level
1056 syslog("info", $message);
1057 syslog(LOG_INFO, $message);
1059 # information level, Local0 facility
1060 syslog("info|local0", $message);
1061 syslog(LOG_INFO|LOG_LOCAL0, $message);
1067 C<Sys::Syslog> version v0.07 and older passed the C<$message> as the
1068 formatting string to C<sprintf()> even when no formatting arguments
1069 were provided. If the code calling C<syslog()> might execute with
1070 older versions of this module, make sure to call the function as
1071 C<syslog($priority, "%s", $message)> instead of C<syslog($priority,
1072 $message)>. This protects against hostile formatting sequences that
1073 might show up if $message contains tainted data.
1078 =item B<setlogmask($mask_priority)>
1080 Sets the log mask for the current process to C<$mask_priority> and
1081 returns the old mask. If the mask argument is 0, the current log mask
1082 is not modified. See L<"Levels"> for the list of available levels.
1083 You can use the C<LOG_UPTO()> function to allow all levels up to a
1084 given priority (but it only accept the numeric macros as arguments).
1090 setlogmask( LOG_MASK(LOG_ERR) );
1092 Log everything except informational messages:
1094 setlogmask( ~(LOG_MASK(LOG_INFO)) );
1096 Log critical messages, errors and warnings:
1098 setlogmask( LOG_MASK(LOG_CRIT)
1100 | LOG_MASK(LOG_WARNING) );
1102 Log all messages up to debug:
1104 setlogmask( LOG_UPTO(LOG_DEBUG) );
1107 =item B<setlogsock()>
1109 Sets the socket type and options to be used for the next call to C<openlog()>
1110 or C<syslog()>. Returns true on success, C<undef> on failure.
1112 Being Perl-specific, this function has evolved along time. It can currently
1113 be called as follow:
1119 C<setlogsock($sock_type)>
1123 C<setlogsock($sock_type, $stream_location)> (added in Perl 5.004_02)
1127 C<setlogsock($sock_type, $stream_location, $sock_timeout)> (added in
1128 C<Sys::Syslog> 0.25)
1132 C<setlogsock(\%options)> (added in C<Sys::Syslog> 0.28)
1136 The available options are:
1142 C<type> - equivalent to C<$sock_type>, selects the socket type (or
1143 "mechanism"). An array reference can be passed to specify several
1144 mechanisms to try, in the given order.
1148 C<path> - equivalent to C<$stream_location>, sets the stream location.
1149 Defaults to standard Unix location, or C<_PATH_LOG>.
1153 C<timeout> - equivalent to C<$sock_timeout>, sets the socket timeout
1154 in seconds. Defaults to 0 on all systems except S<Mac OS X> where it
1159 C<host> - sets the hostname to send the messages to. Defaults to
1164 C<port> - sets the TCP or UDP port to connect to. Defaults to the
1165 first standard syslog port available on the system.
1170 The available mechanisms are:
1176 C<"native"> - use the native C functions from your C<syslog(3)> library
1177 (added in C<Sys::Syslog> 0.15).
1181 C<"eventlog"> - send messages to the Win32 events logger (Win32 only;
1182 added in C<Sys::Syslog> 0.19).
1186 C<"tcp"> - connect to a TCP socket, on the C<syslog/tcp> or C<syslogng/tcp>
1187 service. See also the C<host>, C<port> and C<timeout> options.
1191 C<"udp"> - connect to a UDP socket, on the C<syslog/udp> service.
1192 See also the C<host>, C<port> and C<timeout> options.
1196 C<"inet"> - connect to an INET socket, either TCP or UDP, tried in that
1197 order. See also the C<host>, C<port> and C<timeout> options.
1201 C<"unix"> - connect to a UNIX domain socket (in some systems a character
1202 special device). The name of that socket is given by the C<path> option
1203 or, if omitted, the value returned by the C<_PATH_LOG> macro (if your
1204 system defines it), F</dev/log> or F</dev/conslog>, whichever is writable.
1208 C<"stream"> - connect to the stream indicated by the C<path> option, or,
1209 if omitted, the value returned by the C<_PATH_LOG> macro (if your system
1210 defines it), F</dev/log> or F</dev/conslog>, whichever is writable. For
1211 example Solaris and IRIX system may prefer C<"stream"> instead of C<"unix">.
1215 C<"pipe"> - connect to the named pipe indicated by the C<path> option,
1216 or, if omitted, to the value returned by the C<_PATH_LOG> macro (if your
1217 system defines it), or F</dev/log> (added in C<Sys::Syslog> 0.21).
1218 HP-UX is a system which uses such a named pipe.
1222 C<"console"> - send messages directly to the console, as for the C<"cons">
1223 option of C<openlog()>.
1227 The default is to try C<native>, C<tcp>, C<udp>, C<unix>, C<pipe>, C<stream>,
1229 Under systems with the Win32 API, C<eventlog> will be added as the first
1230 mechanism to try if C<Win32::EventLog> is available.
1232 Giving an invalid value for C<$sock_type> will C<croak>.
1236 Select the UDP socket mechanism:
1240 Send messages using the TCP socket mechanism on a custom port:
1242 setlogsock({ type => "tcp", port => 2486 });
1244 Send messages to a remote host using the TCP socket mechanism:
1246 setlogsock({ type => "tcp", host => $loghost });
1248 Try the native, UDP socket then UNIX domain socket mechanisms:
1250 setlogsock(["native", "udp", "unix"]);
1256 Now that the "native" mechanism is supported by C<Sys::Syslog> and selected
1257 by default, the use of the C<setlogsock()> function is discouraged because
1258 other mechanisms are less portable across operating systems. Authors of
1259 modules and programs that use this function, especially its cargo-cult form
1260 C<setlogsock("unix")>, are advised to remove any occurrence of it unless they
1261 specifically want to use a given mechanism (like TCP or UDP to connect to
1268 Closes the log file and returns true on success.
1273 =head1 THE RULES OF SYS::SYSLOG
1275 I<The First Rule of Sys::Syslog is:>
1276 You do not call C<setlogsock>.
1278 I<The Second Rule of Sys::Syslog is:>
1279 You B<do not> call C<setlogsock>.
1281 I<The Third Rule of Sys::Syslog is:>
1282 The program crashes, C<die>s, calls C<closelog>, the log is over.
1284 I<The Fourth Rule of Sys::Syslog is:>
1285 One facility, one priority.
1287 I<The Fifth Rule of Sys::Syslog is:>
1290 I<The Sixth Rule of Sys::Syslog is:>
1291 No C<syslog> before C<openlog>.
1293 I<The Seventh Rule of Sys::Syslog is:>
1294 Logs will go on as long as they have to.
1296 I<The Eighth, and Final Rule of Sys::Syslog is:>
1297 If this is your first use of Sys::Syslog, you must read the doc.
1304 openlog($program, 'cons,pid', 'user');
1305 syslog('info', '%s', 'this is another test');
1306 syslog('mail|warning', 'this is a better test: %d', time);
1309 syslog('debug', 'this is the last test');
1313 openlog("$program $$", 'ndelay', 'user');
1314 syslog('notice', 'fooprogram: this is really done');
1316 Example of use of C<%m>:
1319 syslog('info', 'problem was %m'); # %m == $! in syslog(3)
1321 Log to UDP port on C<$remotehost> instead of logging locally:
1323 setlogsock("udp", $remotehost);
1324 openlog($program, 'ndelay', 'user');
1325 syslog('info', 'something happened over here');
1336 C<LOG_AUDIT> - audit daemon (IRIX); falls back to C<LOG_AUTH>
1340 C<LOG_AUTH> - security/authorization messages
1344 C<LOG_AUTHPRIV> - security/authorization messages (private)
1348 C<LOG_CONSOLE> - C</dev/console> output (FreeBSD); falls back to C<LOG_USER>
1352 C<LOG_CRON> - clock daemons (B<cron> and B<at>)
1356 C<LOG_DAEMON> - system daemons without separate facility value
1360 C<LOG_FTP> - FTP daemon
1364 C<LOG_KERN> - kernel messages
1368 C<LOG_INSTALL> - installer subsystem (Mac OS X); falls back to C<LOG_USER>
1372 C<LOG_LAUNCHD> - launchd - general bootstrap daemon (Mac OS X);
1373 falls back to C<LOG_DAEMON>
1377 C<LOG_LFMT> - logalert facility; falls back to C<LOG_USER>
1381 C<LOG_LOCAL0> through C<LOG_LOCAL7> - reserved for local use
1385 C<LOG_LPR> - line printer subsystem
1389 C<LOG_MAIL> - mail subsystem
1393 C<LOG_NETINFO> - NetInfo subsystem (Mac OS X); falls back to C<LOG_DAEMON>
1397 C<LOG_NEWS> - USENET news subsystem
1401 C<LOG_NTP> - NTP subsystem (FreeBSD, NetBSD); falls back to C<LOG_DAEMON>
1405 C<LOG_RAS> - Remote Access Service (VPN / PPP) (Mac OS X);
1406 falls back to C<LOG_AUTH>
1410 C<LOG_REMOTEAUTH> - remote authentication/authorization (Mac OS X);
1411 falls back to C<LOG_AUTH>
1415 C<LOG_SECURITY> - security subsystems (firewalling, etc.) (FreeBSD);
1416 falls back to C<LOG_AUTH>
1420 C<LOG_SYSLOG> - messages generated internally by B<syslogd>
1424 C<LOG_USER> (default) - generic user-level messages
1428 C<LOG_UUCP> - UUCP subsystem
1439 C<LOG_EMERG> - system is unusable
1443 C<LOG_ALERT> - action must be taken immediately
1447 C<LOG_CRIT> - critical conditions
1451 C<LOG_ERR> - error conditions
1455 C<LOG_WARNING> - warning conditions
1459 C<LOG_NOTICE> - normal, but significant, condition
1463 C<LOG_INFO> - informational message
1467 C<LOG_DEBUG> - debug-level message
1476 =item C<Invalid argument passed to setlogsock>
1478 B<(F)> You gave C<setlogsock()> an invalid value for C<$sock_type>.
1480 =item C<eventlog passed to setlogsock, but no Win32 API available>
1482 B<(W)> You asked C<setlogsock()> to use the Win32 event logger but the
1483 operating system running the program isn't Win32 or does not provides Win32
1484 compatible facilities.
1486 =item C<no connection to syslog available>
1488 B<(F)> C<syslog()> failed to connect to the specified socket.
1490 =item C<stream passed to setlogsock, but %s is not writable>
1492 B<(W)> You asked C<setlogsock()> to use a stream socket, but the given
1493 path is not writable.
1495 =item C<stream passed to setlogsock, but could not find any device>
1497 B<(W)> You asked C<setlogsock()> to use a stream socket, but didn't
1498 provide a path, and C<Sys::Syslog> was unable to find an appropriate one.
1500 =item C<tcp passed to setlogsock, but tcp service unavailable>
1502 B<(W)> You asked C<setlogsock()> to use a TCP socket, but the service
1503 is not available on the system.
1505 =item C<syslog: expecting argument %s>
1507 B<(F)> You forgot to give C<syslog()> the indicated argument.
1509 =item C<syslog: invalid level/facility: %s>
1511 B<(F)> You specified an invalid level or facility.
1513 =item C<syslog: too many levels given: %s>
1515 B<(F)> You specified too many levels.
1517 =item C<syslog: too many facilities given: %s>
1519 B<(F)> You specified too many facilities.
1521 =item C<syslog: level must be given>
1523 B<(F)> You forgot to specify a level.
1525 =item C<udp passed to setlogsock, but udp service unavailable>
1527 B<(W)> You asked C<setlogsock()> to use a UDP socket, but the service
1528 is not available on the system.
1530 =item C<unix passed to setlogsock, but path not available>
1532 B<(W)> You asked C<setlogsock()> to use a UNIX socket, but C<Sys::Syslog>
1533 was unable to find an appropriate an appropriate device.
1540 C<Sys::Syslog> is a core module, part of the standard Perl distribution
1541 since 1990. At this time, modules as we know them didn't exist, the
1542 Perl library was a collection of F<.pl> files, and the one for sending
1543 syslog messages with was simply F<lib/syslog.pl>, included with Perl 3.0.
1544 It was converted as a module with Perl 5.0, but had a version number
1545 only starting with Perl 5.6. Here is a small table with the matching
1546 Perl and C<Sys::Syslog> versions.
1553 0.04 5.8.1, 5.8.2, 5.8.3
1554 0.05 5.8.4, 5.8.5, 5.8.6
1558 0.27 5.8.9, 5.10.1 ~ 5.14.2
1564 =head2 Other modules
1566 L<Log::Log4perl> - Perl implementation of the Log4j API
1568 L<Log::Dispatch> - Dispatches messages to one or more outputs
1570 L<Log::Report> - Report a problem, with exceptions and language support
1576 SUSv3 issue 6, IEEE Std 1003.1, 2004 edition,
1577 L<http://www.opengroup.org/onlinepubs/000095399/basedefs/syslog.h.html>
1579 GNU C Library documentation on syslog,
1580 L<http://www.gnu.org/software/libc/manual/html_node/Syslog.html>
1582 Solaris 10 documentation on syslog,
1583 L<http://docs.sun.com/app/docs/doc/816-5168/syslog-3c?a=view>
1585 Mac OS X documentation on syslog,
1586 L<http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/syslog.3.html>
1588 IRIX 6.5 documentation on syslog,
1589 L<http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?coll=0650&db=man&fname=3c+syslog>
1591 AIX 5L 5.3 documentation on syslog,
1592 L<http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf2/syslog.htm>
1594 HP-UX 11i documentation on syslog,
1595 L<http://docs.hp.com/en/B2355-60130/syslog.3C.html>
1597 Tru64 5.1 documentation on syslog,
1598 L<http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V51_HTML/MAN/MAN3/0193____.HTM>
1601 L<http://stratadoc.stratus.com/vos/15.1.1/r502-01/wwhelp/wwhimpl/js/html/wwhelp.htm?context=r502-01&file=ch5r502-01bi.html>
1605 I<RFC 3164 - The BSD syslog Protocol>, L<http://www.faqs.org/rfcs/rfc3164.html>
1606 -- Please note that this is an informational RFC, and therefore does not
1607 specify a standard of any kind.
1609 I<RFC 3195 - Reliable Delivery for syslog>, L<http://www.faqs.org/rfcs/rfc3195.html>
1613 I<Syslogging with Perl>, L<http://lexington.pm.org/meetings/022001.html>
1618 L<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wes/wes/windows_event_log.asp>
1621 =head1 AUTHORS & ACKNOWLEDGEMENTS
1623 Tom Christiansen E<lt>F<tchrist (at) perl.com>E<gt> and Larry Wall
1624 E<lt>F<larry (at) wall.org>E<gt>.
1626 UNIX domain sockets added by Sean Robinson
1627 E<lt>F<robinson_s (at) sc.maricopa.edu>E<gt> with support from Tim Bunce
1628 E<lt>F<Tim.Bunce (at) ig.co.uk>E<gt> and the C<perl5-porters> mailing list.
1630 Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
1631 E<lt>F<tom (at) compton.nu>E<gt>.
1633 Code for C<constant()>s regenerated by Nicholas Clark E<lt>F<nick (at) ccl4.org>E<gt>.
1635 Failover to different communication modes by Nick Williams
1636 E<lt>F<Nick.Williams (at) morganstanley.com>E<gt>.
1638 Extracted from core distribution for publishing on the CPAN by
1639 SE<eacute>bastien Aperghis-Tramoni E<lt>sebastien (at) aperghis.netE<gt>.
1641 XS code for using native C functions borrowed from C<L<Unix::Syslog>>,
1642 written by Marcus Harnisch E<lt>F<marcus.harnisch (at) gmx.net>E<gt>.
1644 Yves Orton suggested and helped for making C<Sys::Syslog> use the native
1645 event logger under Win32 systems.
1647 Jerry D. Hedden and Reini Urban provided greatly appreciated help to
1648 debug and polish C<Sys::Syslog> under Cygwin.
1653 Please report any bugs or feature requests to
1654 C<bug-sys-syslog (at) rt.cpan.org>, or through the web interface at
1655 L<http://rt.cpan.org/Public/Dist/Display.html?Name=Sys-Syslog>.
1656 I will be notified, and then you'll automatically be notified of progress on
1657 your bug as I make changes.
1662 You can find documentation for this module with the perldoc command.
1666 You can also look for information at:
1670 =item * AnnoCPAN: Annotated CPAN documentation
1672 L<http://annocpan.org/dist/Sys-Syslog>
1674 =item * CPAN Ratings
1676 L<http://cpanratings.perl.org/d/Sys-Syslog>
1678 =item * RT: CPAN's request tracker
1680 L<http://rt.cpan.org/Dist/Display.html?Queue=Sys-Syslog>
1684 L<http://search.cpan.org/dist/Sys-Syslog/>
1688 L<https://metacpan.org/module/Sys::Syslog>
1690 =item * Perl Documentation
1692 L<http://perldoc.perl.org/Sys/Syslog.html>
1699 Copyright (C) 1990-2012 by Larry Wall and others.
1704 This program is free software; you can redistribute it and/or modify it
1705 under the same terms as Perl itself.
1711 Notes for the future maintainer (even if it's still me..)
1712 - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1714 Using Google Code Search, I search who on Earth was relying on $host being
1715 public. It found 5 hits:
1717 * First was inside Indigo Star Perl2exe documentation. Just an old version
1721 * One real hit was inside DalWeathDB, a weather related program. It simply
1724 $Sys::Syslog::host = '127.0.0.1';
1726 - L<http://www.gallistel.net/nparker/weather/code/>
1729 * Two hits were in TPC, a fax server thingy. It does a
1731 $Sys::Syslog::host = $TPC::LOGHOST;
1733 but also has this strange piece of code:
1735 # work around perl5.003 bug
1736 sub Sys::Syslog::hostname {}
1738 I don't know what bug the author referred to.
1740 - L<http://www.tpc.int/>
1741 - L<ftp://ftp-usa.tpc.int/pub/tpc/server/UNIX/>
1744 * Last hit was in Filefix, which seems to be a FIDOnet mail program (!).
1745 This one does not use $host, but has the following piece of code:
1747 sub Sys::Syslog::hostname
1753 I guess this was a more elaborate form of the previous bit, maybe because
1754 of a bug in Sys::Syslog back then?
1756 - L<ftp://ftp.kiae.su/pub/unix/fido/>
1762 - L<http://www.openss7.org/streams.html>
1764 II12021: SYSLOGD HOWTO TCPIPINFO (z/OS, OS/390, MVS)
1765 - L<http://www-1.ibm.com/support/docview.wss?uid=isg1II12021>
1767 Getting the most out of the Event Viewer
1768 - L<http://www.codeproject.com/dotnet/evtvwr.asp?print=true>
1770 Log events to the Windows NT Event Log with JNI
1771 - L<http://www.javaworld.com/javaworld/jw-09-2001/jw-0928-ntmessages.html>