This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Update DB_File to CPAN version 1.828
[perl5.git] / cpan / Sys-Syslog / Syslog.pm
CommitLineData
a0d0e21e 1package Sys::Syslog;
8168e71f 2use strict;
f93f88eb 3use warnings;
89c3c464 4use warnings::register;
8168e71f 5use Carp;
06fd9d7a
CBW
6use Exporter ();
7use Fcntl qw< O_WRONLY >;
07b7e4bc 8use File::Basename;
06fd9d7a
CBW
9use POSIX qw< strftime setlocale LC_TIME >;
10use Socket qw< :all >;
d329efa2 11require 5.005;
a0d0e21e 12
06fd9d7a 13
89c3c464 14{ no strict 'vars';
aaa7a444 15 $VERSION = '0.32';
06fd9d7a 16 @ISA = qw< Exporter >;
942974c1 17
89c3c464 18 %EXPORT_TAGS = (
4b035b3d
SP
19 standard => [qw(openlog syslog closelog setlogmask)],
20 extended => [qw(setlogsock)],
21 macros => [
22 # levels
23 qw(
24 LOG_ALERT LOG_CRIT LOG_DEBUG LOG_EMERG LOG_ERR
25 LOG_INFO LOG_NOTICE LOG_WARNING
26 ),
27
a650b841 28 # standard facilities
4b035b3d 29 qw(
a650b841
AT
30 LOG_AUTH LOG_AUTHPRIV LOG_CRON LOG_DAEMON LOG_FTP LOG_KERN
31 LOG_LOCAL0 LOG_LOCAL1 LOG_LOCAL2 LOG_LOCAL3 LOG_LOCAL4
32 LOG_LOCAL5 LOG_LOCAL6 LOG_LOCAL7 LOG_LPR LOG_MAIL LOG_NEWS
33 LOG_SYSLOG LOG_USER LOG_UUCP
34 ),
35 # Mac OS X specific facilities
36 qw( LOG_INSTALL LOG_LAUNCHD LOG_NETINFO LOG_RAS LOG_REMOTEAUTH ),
37 # modern BSD specific facilities
38 qw( LOG_CONSOLE LOG_NTP LOG_SECURITY ),
39 # IRIX specific facilities
40 qw( LOG_AUDIT LOG_LFMT ),
4b035b3d
SP
41
42 # options
43 qw(
44 LOG_CONS LOG_PID LOG_NDELAY LOG_NOWAIT LOG_ODELAY LOG_PERROR
45 ),
46
47 # others macros
48 qw(
49 LOG_FACMASK LOG_NFACILITIES LOG_PRIMASK
50 LOG_MASK LOG_UPTO
51 ),
52 ],
89c3c464 53 );
942974c1 54
89c3c464 55 @EXPORT = (
07b7e4bc 56 @{$EXPORT_TAGS{standard}},
89c3c464 57 );
942974c1 58
89c3c464 59 @EXPORT_OK = (
07b7e4bc
RGS
60 @{$EXPORT_TAGS{extended}},
61 @{$EXPORT_TAGS{macros}},
89c3c464
AT
62 );
63
64 eval {
65 require XSLoader;
66 XSLoader::load('Sys::Syslog', $VERSION);
67 1
68 } or do {
69 require DynaLoader;
70 push @ISA, 'DynaLoader';
71 bootstrap Sys::Syslog $VERSION;
72 };
73}
74
75
76#
77# Public variables
78#
a650b841 79use vars qw($host); # host to send syslog messages to (see notes at end)
89c3c464 80
f93f88eb
AT
81#
82# Prototypes
83#
84sub silent_eval (&);
85
89c3c464
AT
86#
87# Global variables
88#
a650b841 89use vars qw($facility);
06fd9d7a 90my $connected = 0; # flag to indicate if we're connected or not
89c3c464 91my $syslog_send; # coderef of the function used to send messages
06fd9d7a
CBW
92my $syslog_path = undef; # syslog path for "stream" and "unix" mechanisms
93my $syslog_xobj = undef; # if defined, holds the external object used to send messages
aaa7a444 94my $transmit_ok = 0; # flag to indicate if the last message was transmitted
06fd9d7a
CBW
95my $sock_port = undef; # socket port
96my $sock_timeout = 0; # socket timeout, see below
97my $current_proto = undef; # current mechanism used to transmit messages
98my $ident = ''; # identifiant prepended to each message
99$facility = ''; # current facility
100my $maskpri = LOG_UPTO(&LOG_DEBUG); # current log mask
89c3c464
AT
101
102my %options = (
103 ndelay => 0,
06fd9d7a 104 noeol => 0,
89c3c464 105 nofatal => 0,
06fd9d7a 106 nonul => 0,
89c3c464 107 nowait => 0,
35a209d1 108 perror => 0,
89c3c464 109 pid => 0,
942974c1 110);
a0d0e21e 111
a650b841 112# Default is now to first use the native mechanism, so Perl programs
d329efa2
AT
113# behave like other normal Unix programs, then try other mechanisms.
114my @connectMethods = qw(native tcp udp unix pipe stream console);
06fd9d7a 115if ($^O eq "freebsd" or $^O eq "linux") {
dbfdd438
SR
116 @connectMethods = grep { $_ ne 'udp' } @connectMethods;
117}
a650b841 118
f93f88eb
AT
119# And on Win32 systems, we try to use the native mechanism for this
120# platform, the events logger, available through Win32::EventLog.
26f266f7 121EVENTLOG: {
26f266f7 122 my $is_Win32 = $^O =~ /Win32/i;
a650b841 123
06fd9d7a 124 if (can_load("Sys::Syslog::Win32", $is_Win32)) {
26f266f7
AT
125 unshift @connectMethods, 'eventlog';
126 }
26f266f7 127}
35a209d1 128
23642f4b 129my @defaultMethods = @connectMethods;
89c3c464 130my @fallbackMethods = ();
8168e71f 131
f93f88eb
AT
132# The timeout in connection_ok() was pushed up to 0.25 sec in
133# Sys::Syslog v0.19 in order to address a heisenbug on MacOSX:
134# http://london.pm.org/pipermail/london.pm/Week-of-Mon-20061211/005961.html
135#
136# However, this also had the effect of slowing this test for
137# all other operating systems, which apparently impacted some
138# users (cf. CPAN-RT #34753). So, in order to make everybody
139# happy, the timeout is now zero by default on all systems
140# except on OSX where it is set to 250 msec, and can be set
141# with the infamous setlogsock() function.
0374b0a2
SH
142#
143# Update 2011-08: this issue is also been seen on multiprocessor
144# Debian GNU/kFreeBSD systems. See http://bugs.debian.org/627821
145# and https://rt.cpan.org/Ticket/Display.html?id=69997
146# Also, lowering the delay to 1 ms, which should be enough.
147
148$sock_timeout = 0.001 if $^O =~ /darwin|gnukfreebsd/;
f93f88eb 149
aaa7a444
CBW
150
151# Perl 5.6.0's warnings.pm doesn't have warnings::warnif()
152if (not defined &warnings::warnif) {
153 *warnings::warnif = sub {
154 goto &warnings::warn if warnings::enabled(__PACKAGE__)
155 }
156}
157
89c3c464
AT
158# coderef for a nicer handling of errors
159my $err_sub = $options{nofatal} ? \&warnings::warnif : \&croak;
5be1dfc7 160
5be1dfc7 161
89c3c464
AT
162sub AUTOLOAD {
163 # This AUTOLOAD is used to 'autoload' constants from the constant()
164 # XS function.
165 no strict 'vars';
166 my $constname;
167 ($constname = $AUTOLOAD) =~ s/.*:://;
168 croak "Sys::Syslog::constant() not defined" if $constname eq 'constant';
169 my ($error, $val) = constant($constname);
a650b841 170 croak $error if $error;
89c3c464
AT
171 no strict 'refs';
172 *$AUTOLOAD = sub { $val };
173 goto &$AUTOLOAD;
174}
5be1dfc7 175
5be1dfc7 176
89c3c464
AT
177sub openlog {
178 ($ident, my $logopt, $facility) = @_;
8168e71f 179
a650b841
AT
180 # default values
181 $ident ||= basename($0) || getlogin() || getpwuid($<) || 'syslog';
182 $logopt ||= '';
183 $facility ||= LOG_USER();
184
89c3c464
AT
185 for my $opt (split /\b/, $logopt) {
186 $options{$opt} = 1 if exists $options{$opt}
187 }
5be1dfc7 188
f93f88eb 189 $err_sub = delete $options{nofatal} ? \&warnings::warnif : \&croak;
89c3c464
AT
190 return 1 unless $options{ndelay};
191 connect_log();
192}
5be1dfc7 193
89c3c464 194sub closelog {
06fd9d7a
CBW
195 disconnect_log() if $connected;
196 $options{$_} = 0 for keys %options;
197 $facility = $ident = "";
198 $connected = 0;
199 return 1
89c3c464 200}
8168e71f 201
89c3c464
AT
202sub setlogmask {
203 my $oldmask = $maskpri;
204 $maskpri = shift unless $_[0] == 0;
205 $oldmask;
206}
f93f88eb 207
a650b841 208
06fd9d7a
CBW
209my %mechanism = (
210 console => {
211 check => sub { 1 },
212 },
213 eventlog => {
214 check => sub { return can_load("Win32::EventLog") },
215 err_msg => "no Win32 API available",
216 },
217 inet => {
218 check => sub { 1 },
219 },
220 native => {
221 check => sub { 1 },
222 },
223 pipe => {
224 check => sub {
225 ($syslog_path) = grep { defined && length && -p && -w _ }
226 $syslog_path, &_PATH_LOG, "/dev/log";
227 return $syslog_path ? 1 : 0
228 },
229 err_msg => "path not available",
230 },
231 stream => {
232 check => sub {
a650b841 233 if (not defined $syslog_path) {
06fd9d7a
CBW
234 my @try = qw(/dev/log /dev/conslog);
235 unshift @try, &_PATH_LOG if length &_PATH_LOG;
236 ($syslog_path) = grep { -w } @try;
a650b841 237 }
06fd9d7a
CBW
238 return defined $syslog_path && -w $syslog_path
239 },
240 err_msg => "could not find any writable device",
241 },
242 tcp => {
243 check => sub {
33f804f6
SH
244 return 1 if defined $sock_port;
245
06fd9d7a
CBW
246 if (getservbyname('syslog', 'tcp') || getservbyname('syslogng', 'tcp')) {
247 $host = $syslog_path;
248 return 1
249 }
250 else {
251 return
252 }
253 },
254 err_msg => "TCP service unavailable",
255 },
256 udp => {
257 check => sub {
33f804f6
SH
258 return 1 if defined $sock_port;
259
06fd9d7a
CBW
260 if (getservbyname('syslog', 'udp')) {
261 $host = $syslog_path;
262 return 1
263 }
264 else {
265 return
266 }
267 },
268 err_msg => "UDP service unavailable",
269 },
270 unix => {
271 check => sub {
272 my @try = ($syslog_path, &_PATH_LOG);
273 ($syslog_path) = grep { defined && length && -w } @try;
274 return defined $syslog_path && -w $syslog_path
275 },
276 err_msg => "path not available",
277 },
278);
279
280sub setlogsock {
281 my %opt;
282
283 # handle arguments
284 # - old API: setlogsock($sock_type, $sock_path, $sock_timeout)
285 # - new API: setlogsock(\%options)
286 croak "setlogsock(): Invalid number of arguments"
287 unless @_ >= 1 and @_ <= 3;
288
289 if (my $ref = ref $_[0]) {
290 if ($ref eq "HASH") {
291 %opt = %{ $_[0] };
292 croak "setlogsock(): No argument given" unless keys %opt;
89c3c464 293 }
06fd9d7a
CBW
294 elsif ($ref eq "ARRAY") {
295 @opt{qw< type path timeout >} = @_;
d329efa2 296 }
06fd9d7a
CBW
297 else {
298 croak "setlogsock(): Unexpected \L$ref\E reference"
a650b841 299 }
06fd9d7a
CBW
300 }
301 else {
302 @opt{qw< type path timeout >} = @_;
303 }
8168e71f 304
0374b0a2 305 # check socket type, remove invalid ones
06fd9d7a
CBW
306 my $diag_invalid_type = "setlogsock(): Invalid type%s; must be one of "
307 . join ", ", map { "'$_'" } sort keys %mechanism;
308 croak sprintf $diag_invalid_type, "" unless defined $opt{type};
309 my @sock_types = ref $opt{type} eq "ARRAY" ? @{$opt{type}} : ($opt{type});
310 my @tmp;
311
312 for my $sock_type (@sock_types) {
313 carp sprintf $diag_invalid_type, " '$sock_type'" and next
314 unless exists $mechanism{$sock_type};
315 push @tmp, "tcp", "udp" and next if $sock_type eq "inet";
316 push @tmp, $sock_type;
317 }
942974c1 318
06fd9d7a 319 @sock_types = @tmp;
942974c1 320
06fd9d7a
CBW
321 # set global options
322 $syslog_path = $opt{path} if defined $opt{path};
323 $host = $opt{host} if defined $opt{host};
324 $sock_timeout = $opt{timeout} if defined $opt{timeout};
325 $sock_port = $opt{port} if defined $opt{port};
942974c1 326
06fd9d7a
CBW
327 disconnect_log() if $connected;
328 $transmit_ok = 0;
329 @fallbackMethods = ();
0374b0a2
SH
330 @connectMethods = ();
331 my $found = 0;
942974c1 332
0374b0a2 333 # check each given mechanism and test if it can be used on the current system
06fd9d7a
CBW
334 for my $sock_type (@sock_types) {
335 if ( $mechanism{$sock_type}{check}->() ) {
0374b0a2
SH
336 push @connectMethods, $sock_type;
337 $found = 1;
06fd9d7a
CBW
338 }
339 else {
aaa7a444
CBW
340 warnings::warnif("setlogsock(): type='$sock_type': "
341 . $mechanism{$sock_type}{err_msg});
06fd9d7a 342 }
89c3c464 343 }
942974c1 344
0374b0a2
SH
345 # if no mechanism worked from the given ones, use the default ones
346 @connectMethods = @defaultMethods unless @connectMethods;
347
348 return $found;
89c3c464 349}
942974c1 350
89c3c464 351sub syslog {
aaa7a444 352 my ($priority, $mask, @args) = @_;
89c3c464
AT
353 my ($message, $buf);
354 my (@words, $num, $numpri, $numfac, $sum);
355 my $failed = undef;
356 my $fail_time = undef;
8edeb3ad 357 my $error = $!;
8168e71f 358
a650b841
AT
359 # if $ident is undefined, it means openlog() wasn't previously called
360 # so do it now in order to have sensible defaults
361 openlog() unless $ident;
362
363 local $facility = $facility; # may need to change temporarily.
8168e71f 364
89c3c464
AT
365 croak "syslog: expecting argument \$priority" unless defined $priority;
366 croak "syslog: expecting argument \$format" unless defined $mask;
5be1dfc7 367
06fd9d7a
CBW
368 if ($priority =~ /^\d+$/) {
369 $numpri = LOG_PRI($priority);
0374b0a2 370 $numfac = LOG_FAC($priority) << 3;
06fd9d7a
CBW
371 }
372 elsif ($priority =~ /^\w+/) {
373 # Allow "level" or "level|facility".
374 @words = split /\W+/, $priority, 2;
5be1dfc7 375
06fd9d7a
CBW
376 undef $numpri;
377 undef $numfac;
f93f88eb 378
06fd9d7a
CBW
379 for my $word (@words) {
380 next if length $word == 0;
f93f88eb 381
06fd9d7a
CBW
382 # Translate word to number.
383 $num = xlate($word);
384
385 if ($num < 0) {
386 croak "syslog: invalid level/facility: $word"
387 }
0374b0a2 388 elsif ($num <= LOG_PRIMASK() and $word ne "kern") {
06fd9d7a
CBW
389 croak "syslog: too many levels given: $word"
390 if defined $numpri;
391 $numpri = $num;
06fd9d7a
CBW
392 }
393 else {
394 croak "syslog: too many facilities given: $word"
395 if defined $numfac;
396 $facility = $word if $word =~ /^[A-Za-z]/;
0374b0a2 397 $numfac = $num;
06fd9d7a 398 }
f93f88eb 399 }
89c3c464 400 }
06fd9d7a
CBW
401 else {
402 croak "syslog: invalid level/facility: $priority"
403 }
5be1dfc7 404
89c3c464 405 croak "syslog: level must be given" unless defined $numpri;
942974c1 406
0374b0a2
SH
407 # don't log if priority is below mask level
408 return 0 unless LOG_MASK($numpri) & $maskpri;
409
89c3c464
AT
410 if (not defined $numfac) { # Facility not specified in this call.
411 $facility = 'user' unless $facility;
412 $numfac = xlate($facility);
413 }
3d256c0f 414
89c3c464 415 connect_log() unless $connected;
8168e71f 416
89c3c464 417 if ($mask =~ /%m/) {
07b7e4bc 418 # escape percent signs for sprintf()
aaa7a444 419 $error =~ s/%/%%/g if @args;
a650b841 420 # replace %m with $error, if preceded by an even number of percent signs
8edeb3ad 421 $mask =~ s/(?<!%)((?:%%)*)%m/$1$error/g;
89c3c464 422 }
5be1dfc7 423
89c3c464 424 $mask .= "\n" unless $mask =~ /\n$/;
aaa7a444 425 $message = @args ? sprintf($mask, @args) : $mask;
942974c1 426
d329efa2 427 if ($current_proto eq 'native') {
89c3c464 428 $buf = $message;
a650b841
AT
429 }
430 elsif ($current_proto eq 'eventlog') {
431 $buf = $message;
432 }
433 else {
89c3c464 434 my $whoami = $ident;
89c3c464 435 $whoami .= "[$$]" if $options{pid};
942974c1 436
89c3c464
AT
437 $sum = $numpri + $numfac;
438 my $oldlocale = setlocale(LC_TIME);
439 setlocale(LC_TIME, 'C');
33f804f6 440 my $timestamp = strftime "%b %d %H:%M:%S", localtime;
89c3c464 441 setlocale(LC_TIME, $oldlocale);
06fd9d7a
CBW
442
443 # construct the stream that will be transmitted
444 $buf = "<$sum>$timestamp $whoami: $message";
445
446 # add (or not) a newline
447 $buf .= "\n" if !$options{noeol} and rindex($buf, "\n") == -1;
448
449 # add (or not) a NUL character
450 $buf .= "\0" if !$options{nonul};
89c3c464 451 }
942974c1 452
35a209d1
AT
453 # handle PERROR option
454 # "native" mechanism already handles it by itself
455 if ($options{perror} and $current_proto ne 'native') {
35a209d1
AT
456 my $whoami = $ident;
457 $whoami .= "[$$]" if $options{pid};
458 print STDERR "$whoami: $message\n";
459 }
460
89c3c464
AT
461 # it's possible that we'll get an error from sending
462 # (e.g. if method is UDP and there is no UDP listener,
463 # then we'll get ECONNREFUSED on the send). So what we
464 # want to do at this point is to fallback onto a different
465 # connection method.
466 while (scalar @fallbackMethods || $syslog_send) {
467 if ($failed && (time - $fail_time) > 60) {
468 # it's been a while... maybe things have been fixed
469 @fallbackMethods = ();
470 disconnect_log();
471 $transmit_ok = 0; # make it look like a fresh attempt
472 connect_log();
473 }
942974c1 474
89c3c464
AT
475 if ($connected && !connection_ok()) {
476 # Something was OK, but has now broken. Remember coz we'll
477 # want to go back to what used to be OK.
478 $failed = $current_proto unless $failed;
479 $fail_time = time;
480 disconnect_log();
481 }
942974c1 482
89c3c464
AT
483 connect_log() unless $connected;
484 $failed = undef if ($current_proto && $failed && $current_proto eq $failed);
942974c1 485
89c3c464 486 if ($syslog_send) {
a650b841 487 if ($syslog_send->($buf, $numpri, $numfac)) {
89c3c464
AT
488 $transmit_ok++;
489 return 1;
490 }
491 # typically doesn't happen, since errors are rare from write().
492 disconnect_log();
493 }
494 }
495 # could not send, could not fallback onto a working
496 # connection method. Lose.
497 return 0;
498}
942974c1 499
89c3c464
AT
500sub _syslog_send_console {
501 my ($buf) = @_;
06fd9d7a 502
89c3c464
AT
503 # The console print is a method which could block
504 # so we do it in a child process and always return success
505 # to the caller.
506 if (my $pid = fork) {
942974c1 507
89c3c464
AT
508 if ($options{nowait}) {
509 return 1;
510 } else {
511 if (waitpid($pid, 0) >= 0) {
512 return ($? >> 8);
513 } else {
514 # it's possible that the caller has other
515 # plans for SIGCHLD, so let's not interfere
516 return 1;
517 }
518 }
519 } else {
520 if (open(CONS, ">/dev/console")) {
521 my $ret = print CONS $buf . "\r"; # XXX: should this be \x0A ?
06fd9d7a 522 POSIX::_exit $ret if defined $pid;
89c3c464
AT
523 close CONS;
524 }
06fd9d7a
CBW
525
526 POSIX::_exit if defined $pid;
89c3c464
AT
527 }
528}
942974c1 529
89c3c464
AT
530sub _syslog_send_stream {
531 my ($buf) = @_;
532 # XXX: this only works if the OS stream implementation makes a write
533 # look like a putmsg() with simple header. For instance it works on
534 # Solaris 8 but not Solaris 7.
535 # To be correct, it should use a STREAMS API, but perl doesn't have one.
536 return syswrite(SYSLOG, $buf, length($buf));
537}
942974c1 538
d329efa2
AT
539sub _syslog_send_pipe {
540 my ($buf) = @_;
541 return print SYSLOG $buf;
542}
543
89c3c464
AT
544sub _syslog_send_socket {
545 my ($buf) = @_;
546 return syswrite(SYSLOG, $buf, length($buf));
547 #return send(SYSLOG, $buf, 0);
548}
942974c1 549
89c3c464 550sub _syslog_send_native {
06fd9d7a
CBW
551 my ($buf, $numpri, $numfac) = @_;
552 syslog_xs($numpri|$numfac, $buf);
a650b841 553 return 1;
89c3c464 554}
ce43db9b 555
5be1dfc7 556
89c3c464
AT
557# xlate()
558# -----
559# private function to translate names to numeric values
560#
561sub xlate {
f93f88eb
AT
562 my ($name) = @_;
563
89c3c464
AT
564 return $name+0 if $name =~ /^\s*\d+\s*$/;
565 $name = uc $name;
566 $name = "LOG_$name" unless $name =~ /^LOG_/;
2605937c
AT
567
568 # ExtUtils::Constant 0.20 introduced a new way to implement
569 # constants, called ProxySubs. When it was used to generate
570 # the C code, the constant() function no longer returns the
571 # correct value. Therefore, we first try a direct call to
572 # constant(), and if the value is an error we try to call the
573 # constant by its full name.
f93f88eb 574 my $value = constant($name);
2605937c
AT
575
576 if (index($value, "not a valid") >= 0) {
577 $name = "Sys::Syslog::$name";
578 $value = eval { no strict "refs"; &$name };
579 $value = $@ unless defined $value;
580 }
581
582 $value = -1 if index($value, "not a valid") >= 0;
f93f88eb 583
35a209d1 584 return defined $value ? $value : -1;
89c3c464 585}
5be1dfc7 586
942974c1 587
89c3c464
AT
588# connect_log()
589# -----------
590# This function acts as a kind of front-end: it tries to connect to
591# a syslog service using the selected methods, trying each one in the
592# selected order.
593#
594sub connect_log {
595 @fallbackMethods = @connectMethods unless scalar @fallbackMethods;
07b7e4bc 596
89c3c464
AT
597 if ($transmit_ok && $current_proto) {
598 # Retry what we were on, because it has worked in the past.
599 unshift(@fallbackMethods, $current_proto);
600 }
07b7e4bc 601
89c3c464
AT
602 $connected = 0;
603 my @errs = ();
604 my $proto = undef;
07b7e4bc 605
89c3c464
AT
606 while ($proto = shift @fallbackMethods) {
607 no strict 'refs';
608 my $fn = "connect_$proto";
609 $connected = &$fn(\@errs) if defined &$fn;
610 last if $connected;
611 }
3d256c0f 612
89c3c464
AT
613 $transmit_ok = 0;
614 if ($connected) {
615 $current_proto = $proto;
a650b841 616 my ($old) = select(SYSLOG); $| = 1; select($old);
89c3c464
AT
617 } else {
618 @fallbackMethods = ();
619 $err_sub->(join "\n\t- ", "no connection to syslog available", @errs);
620 return undef;
621 }
622}
942974c1 623
89c3c464
AT
624sub connect_tcp {
625 my ($errs) = @_;
4b035b3d 626
06fd9d7a
CBW
627 my $proto = getprotobyname('tcp');
628 if (!defined $proto) {
89c3c464
AT
629 push @$errs, "getprotobyname failed for tcp";
630 return 0;
631 }
4b035b3d 632
06fd9d7a
CBW
633 my $port = $sock_port || getservbyname('syslog', 'tcp');
634 $port = getservbyname('syslogng', 'tcp') unless defined $port;
635 if (!defined $port) {
89c3c464
AT
636 push @$errs, "getservbyname failed for syslog/tcp and syslogng/tcp";
637 return 0;
638 }
942974c1 639
4b035b3d 640 my $addr;
89c3c464 641 if (defined $host) {
4b035b3d
SP
642 $addr = inet_aton($host);
643 if (!$addr) {
89c3c464
AT
644 push @$errs, "can't lookup $host";
645 return 0;
646 }
647 } else {
4b035b3d 648 $addr = INADDR_LOOPBACK;
89c3c464 649 }
06fd9d7a 650 $addr = sockaddr_in($port, $addr);
942974c1 651
06fd9d7a 652 if (!socket(SYSLOG, AF_INET, SOCK_STREAM, $proto)) {
89c3c464
AT
653 push @$errs, "tcp socket: $!";
654 return 0;
655 }
a650b841 656
89c3c464 657 setsockopt(SYSLOG, SOL_SOCKET, SO_KEEPALIVE, 1);
f93f88eb 658 if (silent_eval { IPPROTO_TCP() }) {
d329efa2
AT
659 # These constants don't exist in 5.005. They were added in 1999
660 setsockopt(SYSLOG, IPPROTO_TCP(), TCP_NODELAY(), 1);
661 }
4b035b3d 662 if (!connect(SYSLOG, $addr)) {
89c3c464
AT
663 push @$errs, "tcp connect: $!";
664 return 0;
665 }
4b035b3d 666
89c3c464 667 $syslog_send = \&_syslog_send_socket;
4b035b3d 668
89c3c464
AT
669 return 1;
670}
942974c1 671
89c3c464
AT
672sub connect_udp {
673 my ($errs) = @_;
4b035b3d 674
06fd9d7a
CBW
675 my $proto = getprotobyname('udp');
676 if (!defined $proto) {
89c3c464
AT
677 push @$errs, "getprotobyname failed for udp";
678 return 0;
679 }
4b035b3d 680
06fd9d7a
CBW
681 my $port = $sock_port || getservbyname('syslog', 'udp');
682 if (!defined $port) {
89c3c464
AT
683 push @$errs, "getservbyname failed for syslog/udp";
684 return 0;
685 }
4b035b3d
SP
686
687 my $addr;
89c3c464 688 if (defined $host) {
4b035b3d
SP
689 $addr = inet_aton($host);
690 if (!$addr) {
89c3c464
AT
691 push @$errs, "can't lookup $host";
692 return 0;
693 }
694 } else {
4b035b3d 695 $addr = INADDR_LOOPBACK;
89c3c464 696 }
06fd9d7a 697 $addr = sockaddr_in($port, $addr);
942974c1 698
06fd9d7a 699 if (!socket(SYSLOG, AF_INET, SOCK_DGRAM, $proto)) {
89c3c464
AT
700 push @$errs, "udp socket: $!";
701 return 0;
702 }
4b035b3d 703 if (!connect(SYSLOG, $addr)) {
89c3c464
AT
704 push @$errs, "udp connect: $!";
705 return 0;
706 }
4b035b3d 707
89c3c464
AT
708 # We want to check that the UDP connect worked. However the only
709 # way to do that is to send a message and see if an ICMP is returned
710 _syslog_send_socket("");
711 if (!connection_ok()) {
712 push @$errs, "udp connect: nobody listening";
713 return 0;
714 }
4b035b3d 715
89c3c464 716 $syslog_send = \&_syslog_send_socket;
4b035b3d 717
89c3c464
AT
718 return 1;
719}
9903e4c8 720
89c3c464
AT
721sub connect_stream {
722 my ($errs) = @_;
723 # might want syslog_path to be variable based on syslog.h (if only
724 # it were in there!)
8edeb3ad 725 $syslog_path = '/dev/conslog' unless defined $syslog_path;
89c3c464
AT
726 if (!-w $syslog_path) {
727 push @$errs, "stream $syslog_path is not writable";
728 return 0;
729 }
f93f88eb 730 if (!sysopen(SYSLOG, $syslog_path, O_WRONLY, 0400)) {
89c3c464
AT
731 push @$errs, "stream can't open $syslog_path: $!";
732 return 0;
733 }
734 $syslog_send = \&_syslog_send_stream;
735 return 1;
736}
942974c1 737
d329efa2
AT
738sub connect_pipe {
739 my ($errs) = @_;
740
741 $syslog_path ||= &_PATH_LOG || "/dev/log";
742
743 if (not -w $syslog_path) {
744 push @$errs, "$syslog_path is not writable";
745 return 0;
746 }
747
748 if (not open(SYSLOG, ">$syslog_path")) {
749 push @$errs, "can't write to $syslog_path: $!";
750 return 0;
751 }
752
753 $syslog_send = \&_syslog_send_pipe;
754
755 return 1;
756}
757
89c3c464
AT
758sub connect_unix {
759 my ($errs) = @_;
4b035b3d
SP
760
761 $syslog_path ||= _PATH_LOG() if length _PATH_LOG();
762
763 if (not defined $syslog_path) {
764 push @$errs, "_PATH_LOG not available in syslog.h and no user-supplied socket path";
89c3c464
AT
765 return 0;
766 }
4b035b3d 767
35a209d1 768 if (not (-S $syslog_path or -c _)) {
89c3c464
AT
769 push @$errs, "$syslog_path is not a socket";
770 return 0;
771 }
4b035b3d
SP
772
773 my $addr = sockaddr_un($syslog_path);
774 if (!$addr) {
89c3c464
AT
775 push @$errs, "can't locate $syslog_path";
776 return 0;
777 }
4b035b3d 778 if (!socket(SYSLOG, AF_UNIX, SOCK_STREAM, 0)) {
89c3c464
AT
779 push @$errs, "unix stream socket: $!";
780 return 0;
781 }
a650b841 782
4b035b3d
SP
783 if (!connect(SYSLOG, $addr)) {
784 if (!socket(SYSLOG, AF_UNIX, SOCK_DGRAM, 0)) {
89c3c464
AT
785 push @$errs, "unix dgram socket: $!";
786 return 0;
787 }
4b035b3d 788 if (!connect(SYSLOG, $addr)) {
89c3c464
AT
789 push @$errs, "unix dgram connect: $!";
790 return 0;
791 }
792 }
4b035b3d 793
89c3c464 794 $syslog_send = \&_syslog_send_socket;
4b035b3d 795
89c3c464
AT
796 return 1;
797}
942974c1 798
89c3c464
AT
799sub connect_native {
800 my ($errs) = @_;
801 my $logopt = 0;
5be1dfc7 802
89c3c464
AT
803 # reconstruct the numeric equivalent of the options
804 for my $opt (keys %options) {
805 $logopt += xlate($opt) if $options{$opt}
806 }
942974c1 807
f93f88eb 808 openlog_xs($ident, $logopt, xlate($facility));
89c3c464 809 $syslog_send = \&_syslog_send_native;
942974c1 810
89c3c464
AT
811 return 1;
812}
6e4ef777 813
a650b841
AT
814sub connect_eventlog {
815 my ($errs) = @_;
816
817 $syslog_xobj = Sys::Syslog::Win32::_install();
818 $syslog_send = \&Sys::Syslog::Win32::_syslog_send;
819
820 return 1;
821}
822
89c3c464
AT
823sub connect_console {
824 my ($errs) = @_;
825 if (!-w '/dev/console') {
826 push @$errs, "console is not writable";
827 return 0;
828 }
829 $syslog_send = \&_syslog_send_console;
830 return 1;
831}
6e4ef777 832
a650b841 833# To test if the connection is still good, we need to check if any
89c3c464
AT
834# errors are present on the connection. The errors will not be raised
835# by a write. Instead, sockets are made readable and the next read
836# would cause the error to be returned. Unfortunately the syslog
837# 'protocol' never provides anything for us to read. But with
838# judicious use of select(), we can see if it would be readable...
839sub connection_ok {
840 return 1 if defined $current_proto and (
841 $current_proto eq 'native' or $current_proto eq 'console'
a650b841 842 or $current_proto eq 'eventlog'
89c3c464 843 );
a650b841 844
89c3c464
AT
845 my $rin = '';
846 vec($rin, fileno(SYSLOG), 1) = 1;
f93f88eb 847 my $ret = select $rin, undef, $rin, $sock_timeout;
89c3c464
AT
848 return ($ret ? 0 : 1);
849}
942974c1 850
89c3c464
AT
851sub disconnect_log {
852 $connected = 0;
853 $syslog_send = undef;
942974c1 854
a650b841
AT
855 if (defined $current_proto and $current_proto eq 'native') {
856 closelog_xs();
06fd9d7a
CBW
857 unshift @fallbackMethods, $current_proto;
858 $current_proto = undef;
a650b841
AT
859 return 1;
860 }
861 elsif (defined $current_proto and $current_proto eq 'eventlog') {
862 $syslog_xobj->Close();
06fd9d7a
CBW
863 unshift @fallbackMethods, $current_proto;
864 $current_proto = undef;
89c3c464
AT
865 return 1;
866 }
6e4ef777 867
89c3c464
AT
868 return close SYSLOG;
869}
6e4ef777 870
f93f88eb
AT
871
872#
873# Wrappers around eval() that makes sure that nobody, and I say NOBODY,
874# ever knows that I wanted to test if something was here or not.
875# It is needed because some applications are trying to be too smart,
876# do it wrong, and it ends up in EPIC FAIL.
877# Yes I'm speaking of YOU, SpamAssassin.
878#
879sub silent_eval (&) {
880 local($SIG{__DIE__}, $SIG{__WARN__}, $@);
2605937c 881 return eval { $_[0]->() }
f93f88eb
AT
882}
883
884sub can_load {
06fd9d7a 885 my ($module, $verbose) = @_;
f93f88eb 886 local($SIG{__DIE__}, $SIG{__WARN__}, $@);
06fd9d7a
CBW
887 my $loaded = eval "use $module; 1";
888 warn $@ if not $loaded and $verbose;
889 return $loaded
f93f88eb
AT
890}
891
892
893"Eighth Rule: read the documentation."
942974c1 894
89c3c464 895__END__
5be1dfc7 896
89c3c464 897=head1 NAME
8168e71f 898
89c3c464 899Sys::Syslog - Perl interface to the UNIX syslog(3) calls
3ffabb8c 900
89c3c464 901=head1 VERSION
3ffabb8c 902
aaa7a444 903This is the documentation of version 0.32
23642f4b 904
89c3c464 905=head1 SYNOPSIS
cb63fe9d 906
06fd9d7a
CBW
907 use Sys::Syslog; # all except setlogsock()
908 use Sys::Syslog qw(:standard :macros); # standard functions & macros
23642f4b 909
06fd9d7a
CBW
910 openlog($ident, $logopt, $facility); # don't forget this
911 syslog($priority, $format, @args);
912 $oldmask = setlogmask($mask_priority);
913 closelog();
cb63fe9d 914
942974c1 915
89c3c464 916=head1 DESCRIPTION
5be1dfc7 917
89c3c464
AT
918C<Sys::Syslog> is an interface to the UNIX C<syslog(3)> program.
919Call C<syslog()> with a string priority and a list of C<printf()> args
920just like C<syslog(3)>.
5be1dfc7 921
5be1dfc7 922
89c3c464 923=head1 EXPORTS
5be1dfc7 924
89c3c464 925C<Sys::Syslog> exports the following C<Exporter> tags:
5be1dfc7 926
89c3c464
AT
927=over 4
928
929=item *
930
931C<:standard> exports the standard C<syslog(3)> functions:
932
933 openlog closelog setlogmask syslog
934
935=item *
936
937C<:extended> exports the Perl specific functions for C<syslog(3)>:
938
939 setlogsock
940
941=item *
942
943C<:macros> exports the symbols corresponding to most of your C<syslog(3)>
944macros and the C<LOG_UPTO()> and C<LOG_MASK()> functions.
945See L<"CONSTANTS"> for the supported constants and their meaning.
946
947=back
948
949By default, C<Sys::Syslog> exports the symbols from the C<:standard> tag.
950
951
952=head1 FUNCTIONS
953
954=over 4
955
956=item B<openlog($ident, $logopt, $facility)>
957
958Opens the syslog.
959C<$ident> is prepended to every message. C<$logopt> contains zero or
960more of the options detailed below. C<$facility> specifies the part
961of the system to report about, for example C<LOG_USER> or C<LOG_LOCAL0>:
962see L<"Facilities"> for a list of well-known facilities, and your
963C<syslog(3)> documentation for the facilities available in your system.
964Check L<"SEE ALSO"> for useful links. Facility can be given as a string
965or a numeric macro.
966
967This function will croak if it can't connect to the syslog daemon.
968
969Note that C<openlog()> now takes three arguments, just like C<openlog(3)>.
970
971B<You should use C<openlog()> before calling C<syslog()>.>
972
973B<Options>
974
975=over 4
976
977=item *
978
979C<cons> - This option is ignored, since the failover mechanism will drop
980down to the console automatically if all other media fail.
981
982=item *
983
984C<ndelay> - Open the connection immediately (normally, the connection is
985opened when the first message is logged).
986
987=item *
988
06fd9d7a
CBW
989C<noeol> - When set to true, no end of line character (C<\n>) will be
990appended to the message. This can be useful for some buggy syslog daemons.
991
992=item *
993
89c3c464
AT
994C<nofatal> - When set to true, C<openlog()> and C<syslog()> will only
995emit warnings instead of dying if the connection to the syslog can't
996be established.
997
998=item *
999
06fd9d7a
CBW
1000C<nonul> - When set to true, no C<NUL> character (C<\0>) will be
1001appended to the message. This can be useful for some buggy syslog daemons.
1002
1003=item *
1004
89c3c464
AT
1005C<nowait> - Don't wait for child processes that may have been created
1006while logging the message. (The GNU C library does not create a child
1007process, so this option has no effect on Linux.)
1008
1009=item *
1010
35a209d1 1011C<perror> - Write the message to standard error output as well to the
06fd9d7a 1012system log (added in C<Sys::Syslo> 0.22).
35a209d1
AT
1013
1014=item *
1015
89c3c464
AT
1016C<pid> - Include PID with each message.
1017
1018=back
1019
1020B<Examples>
1021
1022Open the syslog with options C<ndelay> and C<pid>, and with facility C<LOCAL0>:
1023
1024 openlog($name, "ndelay,pid", "local0");
1025
1026Same thing, but this time using the macro corresponding to C<LOCAL0>:
1027
1028 openlog($name, "ndelay,pid", LOG_LOCAL0);
1029
1030
1031=item B<syslog($priority, $message)>
1032
1033=item B<syslog($priority, $format, @args)>
1034
1035If C<$priority> permits, logs C<$message> or C<sprintf($format, @args)>
1036with the addition that C<%m> in $message or C<$format> is replaced with
1037C<"$!"> (the latest error message).
1038
1039C<$priority> can specify a level, or a level and a facility. Levels and
a650b841
AT
1040facilities can be given as strings or as macros. When using the C<eventlog>
1041mechanism, priorities C<DEBUG> and C<INFO> are mapped to event type
06fd9d7a 1042C<informational>, C<NOTICE> and C<WARNING> to C<warning> and C<ERR> to
a650b841 1043C<EMERG> to C<error>.
89c3c464
AT
1044
1045If you didn't use C<openlog()> before using C<syslog()>, C<syslog()> will
1046try to guess the C<$ident> by extracting the shortest prefix of
1047C<$format> that ends in a C<":">.
1048
1049B<Examples>
1050
06fd9d7a
CBW
1051 # informational level
1052 syslog("info", $message);
1053 syslog(LOG_INFO, $message);
89c3c464 1054
06fd9d7a
CBW
1055 # information level, Local0 facility
1056 syslog("info|local0", $message);
1057 syslog(LOG_INFO|LOG_LOCAL0, $message);
89c3c464
AT
1058
1059=over 4
1060
1061=item B<Note>
1062
1063C<Sys::Syslog> version v0.07 and older passed the C<$message> as the
1064formatting string to C<sprintf()> even when no formatting arguments
1065were provided. If the code calling C<syslog()> might execute with
1066older versions of this module, make sure to call the function as
1067C<syslog($priority, "%s", $message)> instead of C<syslog($priority,
1068$message)>. This protects against hostile formatting sequences that
1069might show up if $message contains tainted data.
1070
1071=back
1072
1073
1074=item B<setlogmask($mask_priority)>
1075
1076Sets the log mask for the current process to C<$mask_priority> and
1077returns the old mask. If the mask argument is 0, the current log mask
1078is not modified. See L<"Levels"> for the list of available levels.
1079You can use the C<LOG_UPTO()> function to allow all levels up to a
1080given priority (but it only accept the numeric macros as arguments).
1081
1082B<Examples>
1083
1084Only log errors:
1085
1086 setlogmask( LOG_MASK(LOG_ERR) );
1087
1088Log everything except informational messages:
1089
1090 setlogmask( ~(LOG_MASK(LOG_INFO)) );
1091
1092Log critical messages, errors and warnings:
1093
06fd9d7a
CBW
1094 setlogmask( LOG_MASK(LOG_CRIT)
1095 | LOG_MASK(LOG_ERR)
1096 | LOG_MASK(LOG_WARNING) );
89c3c464
AT
1097
1098Log all messages up to debug:
1099
1100 setlogmask( LOG_UPTO(LOG_DEBUG) );
1101
1102
06fd9d7a
CBW
1103=item B<setlogsock()>
1104
1105Sets the socket type and options to be used for the next call to C<openlog()>
1106or C<syslog()>. Returns true on success, C<undef> on failure.
89c3c464 1107
06fd9d7a
CBW
1108Being Perl-specific, this function has evolved along time. It can currently
1109be called as follow:
89c3c464 1110
06fd9d7a
CBW
1111=over
1112
1113=item *
1114
1115C<setlogsock($sock_type)>
1116
1117=item *
1118
1119C<setlogsock($sock_type, $stream_location)> (added in Perl 5.004_02)
1120
1121=item *
1122
1123C<setlogsock($sock_type, $stream_location, $sock_timeout)> (added in
1124C<Sys::Syslog> 0.25)
1125
1126=item *
1127
1128C<setlogsock(\%options)> (added in C<Sys::Syslog> 0.28)
1129
1130=back
f93f88eb 1131
06fd9d7a
CBW
1132The available options are:
1133
1134=over
1135
1136=item *
1137
1138C<type> - equivalent to C<$sock_type>, selects the socket type (or
1139"mechanism"). An array reference can be passed to specify several
1140mechanisms to try, in the given order.
1141
1142=item *
1143
1144C<path> - equivalent to C<$stream_location>, sets the stream location.
1145Defaults to standard Unix location, or C<_PATH_LOG>.
1146
1147=item *
1148
1149C<timeout> - equivalent to C<$sock_timeout>, sets the socket timeout
1150in seconds. Defaults to 0 on all systems except S<Mac OS X> where it
1151is set to 0.25 sec.
1152
1153=item *
1154
1155C<host> - sets the hostname to send the messages to. Defaults to
1156the local host.
1157
1158=item *
1159
1160C<port> - sets the TCP or UDP port to connect to. Defaults to the
1161first standard syslog port available on the system.
1162
1163=back
1164
1165
1166The available mechanisms are:
4b035b3d
SP
1167
1168=over
1169
1170=item *
1171
07b7e4bc
RGS
1172C<"native"> - use the native C functions from your C<syslog(3)> library
1173(added in C<Sys::Syslog> 0.15).
4b035b3d
SP
1174
1175=item *
1176
d329efa2
AT
1177C<"eventlog"> - send messages to the Win32 events logger (Win32 only;
1178added in C<Sys::Syslog> 0.19).
1179
1180=item *
1181
4b035b3d 1182C<"tcp"> - connect to a TCP socket, on the C<syslog/tcp> or C<syslogng/tcp>
06fd9d7a 1183service. See also the C<host>, C<port> and C<timeout> options.
4b035b3d
SP
1184
1185=item *
1186
1187C<"udp"> - connect to a UDP socket, on the C<syslog/udp> service.
06fd9d7a 1188See also the C<host>, C<port> and C<timeout> options.
4b035b3d
SP
1189
1190=item *
1191
f93f88eb 1192C<"inet"> - connect to an INET socket, either TCP or UDP, tried in that
06fd9d7a 1193order. See also the C<host>, C<port> and C<timeout> options.
4b035b3d
SP
1194
1195=item *
1196
1197C<"unix"> - connect to a UNIX domain socket (in some systems a character
06fd9d7a
CBW
1198special device). The name of that socket is given by the C<path> option
1199or, if omitted, the value returned by the C<_PATH_LOG> macro (if your
1200system defines it), F</dev/log> or F</dev/conslog>, whichever is writable.
4b035b3d
SP
1201
1202=item *
1203
06fd9d7a
CBW
1204C<"stream"> - connect to the stream indicated by the C<path> option, or,
1205if omitted, the value returned by the C<_PATH_LOG> macro (if your system
1206defines it), F</dev/log> or F</dev/conslog>, whichever is writable. For
1207example Solaris and IRIX system may prefer C<"stream"> instead of C<"unix">.
4b035b3d
SP
1208
1209=item *
1210
06fd9d7a
CBW
1211C<"pipe"> - connect to the named pipe indicated by the C<path> option,
1212or, if omitted, to the value returned by the C<_PATH_LOG> macro (if your
1213system defines it), or F</dev/log> (added in C<Sys::Syslog> 0.21).
1214HP-UX is a system which uses such a named pipe.
4b035b3d 1215
a650b841
AT
1216=item *
1217
d329efa2
AT
1218C<"console"> - send messages directly to the console, as for the C<"cons">
1219option of C<openlog()>.
a650b841 1220
4b035b3d 1221=back
89c3c464 1222
f93f88eb
AT
1223The default is to try C<native>, C<tcp>, C<udp>, C<unix>, C<pipe>, C<stream>,
1224C<console>.
35a209d1
AT
1225Under systems with the Win32 API, C<eventlog> will be added as the first
1226mechanism to try if C<Win32::EventLog> is available.
89c3c464 1227
07b7e4bc 1228Giving an invalid value for C<$sock_type> will C<croak>.
89c3c464 1229
4b035b3d
SP
1230B<Examples>
1231
06fd9d7a 1232Select the UDP socket mechanism:
4b035b3d
SP
1233
1234 setlogsock("udp");
1235
06fd9d7a
CBW
1236Send messages using the TCP socket mechanism on a custom port:
1237
1238 setlogsock({ type => "tcp", port => 2486 });
1239
1240Send messages to a remote host using the TCP socket mechanism:
1241
1242 setlogsock({ type => "tcp", host => $loghost });
1243
1244Try the native, UDP socket then UNIX domain socket mechanisms:
4b035b3d
SP
1245
1246 setlogsock(["native", "udp", "unix"]);
1247
07b7e4bc
RGS
1248=over
1249
1250=item B<Note>
1251
1252Now that the "native" mechanism is supported by C<Sys::Syslog> and selected
1253by default, the use of the C<setlogsock()> function is discouraged because
1254other mechanisms are less portable across operating systems. Authors of
1255modules and programs that use this function, especially its cargo-cult form
1256C<setlogsock("unix")>, are advised to remove any occurence of it unless they
1257specifically want to use a given mechanism (like TCP or UDP to connect to
1258a remote host).
1259
1260=back
89c3c464
AT
1261
1262=item B<closelog()>
1263
4b035b3d 1264Closes the log file and returns true on success.
89c3c464
AT
1265
1266=back
1267
1268
a650b841
AT
1269=head1 THE RULES OF SYS::SYSLOG
1270
1271I<The First Rule of Sys::Syslog is:>
1272You do not call C<setlogsock>.
1273
1274I<The Second Rule of Sys::Syslog is:>
1275You B<do not> call C<setlogsock>.
1276
1277I<The Third Rule of Sys::Syslog is:>
1278The program crashes, C<die>s, calls C<closelog>, the log is over.
1279
1280I<The Fourth Rule of Sys::Syslog is:>
1281One facility, one priority.
1282
1283I<The Fifth Rule of Sys::Syslog is:>
1284One log at a time.
1285
1286I<The Sixth Rule of Sys::Syslog is:>
1287No C<syslog> before C<openlog>.
1288
1289I<The Seventh Rule of Sys::Syslog is:>
1290Logs will go on as long as they have to.
1291
1292I<The Eighth, and Final Rule of Sys::Syslog is:>
1293If this is your first use of Sys::Syslog, you must read the doc.
1294
1295
89c3c464
AT
1296=head1 EXAMPLES
1297
a650b841
AT
1298An example:
1299
89c3c464
AT
1300 openlog($program, 'cons,pid', 'user');
1301 syslog('info', '%s', 'this is another test');
1302 syslog('mail|warning', 'this is a better test: %d', time);
1303 closelog();
5be1dfc7
HF
1304
1305 syslog('debug', 'this is the last test');
cb63fe9d 1306
a650b841
AT
1307Another example:
1308
5be1dfc7
HF
1309 openlog("$program $$", 'ndelay', 'user');
1310 syslog('notice', 'fooprogram: this is really done');
1311
a650b841
AT
1312Example of use of C<%m>:
1313
5be1dfc7 1314 $! = 55;
6e4ef777
SP
1315 syslog('info', 'problem was %m'); # %m == $! in syslog(3)
1316
1317Log to UDP port on C<$remotehost> instead of logging locally:
5be1dfc7 1318
f93f88eb 1319 setlogsock("udp", $remotehost);
476b65d9
JH
1320 openlog($program, 'ndelay', 'user');
1321 syslog('info', 'something happened over here');
1322
8168e71f
SP
1323
1324=head1 CONSTANTS
1325
1326=head2 Facilities
1327
1328=over 4
1329
1330=item *
1331
a650b841
AT
1332C<LOG_AUDIT> - audit daemon (IRIX); falls back to C<LOG_AUTH>
1333
1334=item *
1335
8168e71f
SP
1336C<LOG_AUTH> - security/authorization messages
1337
1338=item *
1339
1340C<LOG_AUTHPRIV> - security/authorization messages (private)
1341
1342=item *
1343
a650b841
AT
1344C<LOG_CONSOLE> - C</dev/console> output (FreeBSD); falls back to C<LOG_USER>
1345
1346=item *
1347
4b035b3d 1348C<LOG_CRON> - clock daemons (B<cron> and B<at>)
8168e71f
SP
1349
1350=item *
1351
1352C<LOG_DAEMON> - system daemons without separate facility value
1353
1354=item *
1355
4b035b3d 1356C<LOG_FTP> - FTP daemon
8168e71f
SP
1357
1358=item *
1359
1360C<LOG_KERN> - kernel messages
1361
1362=item *
1363
a650b841 1364C<LOG_INSTALL> - installer subsystem (Mac OS X); falls back to C<LOG_USER>
4b035b3d
SP
1365
1366=item *
1367
a650b841
AT
1368C<LOG_LAUNCHD> - launchd - general bootstrap daemon (Mac OS X);
1369falls back to C<LOG_DAEMON>
1370
1371=item *
1372
1373C<LOG_LFMT> - logalert facility; falls back to C<LOG_USER>
4b035b3d
SP
1374
1375=item *
1376
8168e71f
SP
1377C<LOG_LOCAL0> through C<LOG_LOCAL7> - reserved for local use
1378
1379=item *
1380
1381C<LOG_LPR> - line printer subsystem
1382
1383=item *
1384
1385C<LOG_MAIL> - mail subsystem
1386
1387=item *
1388
a650b841 1389C<LOG_NETINFO> - NetInfo subsystem (Mac OS X); falls back to C<LOG_DAEMON>
4b035b3d
SP
1390
1391=item *
1392
8168e71f
SP
1393C<LOG_NEWS> - USENET news subsystem
1394
1395=item *
1396
a650b841
AT
1397C<LOG_NTP> - NTP subsystem (FreeBSD, NetBSD); falls back to C<LOG_DAEMON>
1398
1399=item *
1400
1401C<LOG_RAS> - Remote Access Service (VPN / PPP) (Mac OS X);
1402falls back to C<LOG_AUTH>
4b035b3d
SP
1403
1404=item *
1405
a650b841
AT
1406C<LOG_REMOTEAUTH> - remote authentication/authorization (Mac OS X);
1407falls back to C<LOG_AUTH>
1408
1409=item *
1410
1411C<LOG_SECURITY> - security subsystems (firewalling, etc.) (FreeBSD);
1412falls back to C<LOG_AUTH>
4b035b3d
SP
1413
1414=item *
1415
8168e71f
SP
1416C<LOG_SYSLOG> - messages generated internally by B<syslogd>
1417
1418=item *
1419
1420C<LOG_USER> (default) - generic user-level messages
1421
1422=item *
1423
1424C<LOG_UUCP> - UUCP subsystem
1425
1426=back
1427
1428
1429=head2 Levels
1430
1431=over 4
1432
1433=item *
1434
1435C<LOG_EMERG> - system is unusable
1436
1437=item *
1438
1439C<LOG_ALERT> - action must be taken immediately
1440
1441=item *
1442
1443C<LOG_CRIT> - critical conditions
1444
1445=item *
1446
942974c1 1447C<LOG_ERR> - error conditions
8168e71f
SP
1448
1449=item *
1450
1451C<LOG_WARNING> - warning conditions
1452
1453=item *
1454
1455C<LOG_NOTICE> - normal, but significant, condition
1456
1457=item *
1458
1459C<LOG_INFO> - informational message
1460
1461=item *
1462
1463C<LOG_DEBUG> - debug-level message
1464
1465=back
1466
1467
1468=head1 DIAGNOSTICS
1469
a650b841 1470=over
8168e71f 1471
a650b841 1472=item C<Invalid argument passed to setlogsock>
8168e71f
SP
1473
1474B<(F)> You gave C<setlogsock()> an invalid value for C<$sock_type>.
1475
35a209d1 1476=item C<eventlog passed to setlogsock, but no Win32 API available>
a650b841
AT
1477
1478B<(W)> You asked C<setlogsock()> to use the Win32 event logger but the
1479operating system running the program isn't Win32 or does not provides Win32
35a209d1 1480compatible facilities.
a650b841
AT
1481
1482=item C<no connection to syslog available>
8168e71f
SP
1483
1484B<(F)> C<syslog()> failed to connect to the specified socket.
1485
a650b841 1486=item C<stream passed to setlogsock, but %s is not writable>
8168e71f 1487
942974c1 1488B<(W)> You asked C<setlogsock()> to use a stream socket, but the given
8168e71f
SP
1489path is not writable.
1490
a650b841 1491=item C<stream passed to setlogsock, but could not find any device>
8168e71f 1492
942974c1 1493B<(W)> You asked C<setlogsock()> to use a stream socket, but didn't
8168e71f
SP
1494provide a path, and C<Sys::Syslog> was unable to find an appropriate one.
1495
a650b841 1496=item C<tcp passed to setlogsock, but tcp service unavailable>
8168e71f 1497
942974c1 1498B<(W)> You asked C<setlogsock()> to use a TCP socket, but the service
8168e71f
SP
1499is not available on the system.
1500
a650b841 1501=item C<syslog: expecting argument %s>
8168e71f
SP
1502
1503B<(F)> You forgot to give C<syslog()> the indicated argument.
1504
a650b841 1505=item C<syslog: invalid level/facility: %s>
8168e71f 1506
6e4ef777 1507B<(F)> You specified an invalid level or facility.
8168e71f 1508
a650b841 1509=item C<syslog: too many levels given: %s>
8168e71f
SP
1510
1511B<(F)> You specified too many levels.
1512
a650b841 1513=item C<syslog: too many facilities given: %s>
8168e71f
SP
1514
1515B<(F)> You specified too many facilities.
1516
a650b841 1517=item C<syslog: level must be given>
8168e71f
SP
1518
1519B<(F)> You forgot to specify a level.
1520
a650b841 1521=item C<udp passed to setlogsock, but udp service unavailable>
8168e71f 1522
942974c1 1523B<(W)> You asked C<setlogsock()> to use a UDP socket, but the service
8168e71f
SP
1524is not available on the system.
1525
a650b841 1526=item C<unix passed to setlogsock, but path not available>
8168e71f 1527
942974c1 1528B<(W)> You asked C<setlogsock()> to use a UNIX socket, but C<Sys::Syslog>
8168e71f
SP
1529was unable to find an appropriate an appropriate device.
1530
1531=back
1532
1533
06fd9d7a
CBW
1534=head1 HISTORY
1535
1536C<Sys::Syslog> is a core module, part of the standard Perl distribution
1537since 1990. At this time, modules as we know them didn't exist, the
1538Perl library was a collection of F<.pl> files, and the one for sending
1539syslog messages with was simply F<lib/syslog.pl>, included with Perl 3.0.
1540It was converted as a module with Perl 5.0, but had a version number
1541only starting with Perl 5.6. Here is a small table with the matching
1542Perl and C<Sys::Syslog> versions.
1543
1544 Sys::Syslog Perl
1545 ----------- ----
33f804f6
SH
1546 undef 5.0.0 ~ 5.5.4
1547 0.01 5.6.*
06fd9d7a
CBW
1548 0.03 5.8.0
1549 0.04 5.8.1, 5.8.2, 5.8.3
1550 0.05 5.8.4, 5.8.5, 5.8.6
1551 0.06 5.8.7
1552 0.13 5.8.8
1553 0.22 5.10.0
33f804f6
SH
1554 0.27 5.8.9, 5.10.1 ~ 5.14.2
1555 0.29 5.16.0, 5.16.1
06fd9d7a
CBW
1556
1557
5be1dfc7
HF
1558=head1 SEE ALSO
1559
a650b841
AT
1560=head2 Manual Pages
1561
5be1dfc7
HF
1562L<syslog(3)>
1563
6e4ef777
SP
1564SUSv3 issue 6, IEEE Std 1003.1, 2004 edition,
1565L<http://www.opengroup.org/onlinepubs/000095399/basedefs/syslog.h.html>
1566
1567GNU C Library documentation on syslog,
1568L<http://www.gnu.org/software/libc/manual/html_node/Syslog.html>
1569
1570Solaris 10 documentation on syslog,
f93f88eb
AT
1571L<http://docs.sun.com/app/docs/doc/816-5168/syslog-3c?a=view>
1572
1573Mac OS X documentation on syslog,
1574L<http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/syslog.3.html>
6e4ef777 1575
f93f88eb
AT
1576IRIX 6.5 documentation on syslog,
1577L<http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?coll=0650&db=man&fname=3c+syslog>
a650b841 1578
6e4ef777 1579AIX 5L 5.3 documentation on syslog,
d329efa2 1580L<http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf2/syslog.htm>
6e4ef777
SP
1581
1582HP-UX 11i documentation on syslog,
f93f88eb 1583L<http://docs.hp.com/en/B2355-60130/syslog.3C.html>
6e4ef777
SP
1584
1585Tru64 5.1 documentation on syslog,
1586L<http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V51_HTML/MAN/MAN3/0193____.HTM>
1587
1588Stratus VOS 15.1,
1589L<http://stratadoc.stratus.com/vos/15.1.1/r502-01/wwhelp/wwhimpl/js/html/wwhelp.htm?context=r502-01&file=ch5r502-01bi.html>
1590
a650b841
AT
1591=head2 RFCs
1592
6e4ef777
SP
1593I<RFC 3164 - The BSD syslog Protocol>, L<http://www.faqs.org/rfcs/rfc3164.html>
1594-- Please note that this is an informational RFC, and therefore does not
1595specify a standard of any kind.
1596
1597I<RFC 3195 - Reliable Delivery for syslog>, L<http://www.faqs.org/rfcs/rfc3195.html>
1598
a650b841
AT
1599=head2 Articles
1600
04f98b29
RGS
1601I<Syslogging with Perl>, L<http://lexington.pm.org/meetings/022001.html>
1602
a650b841 1603=head2 Event Log
8168e71f 1604
a650b841
AT
1605Windows Event Log,
1606L<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wes/wes/windows_event_log.asp>
5be1dfc7 1607
a650b841
AT
1608
1609=head1 AUTHORS & ACKNOWLEDGEMENTS
1610
1611Tom Christiansen E<lt>F<tchrist (at) perl.com>E<gt> and Larry Wall
1612E<lt>F<larry (at) wall.org>E<gt>.
150b260b
GS
1613
1614UNIX domain sockets added by Sean Robinson
a650b841
AT
1615E<lt>F<robinson_s (at) sc.maricopa.edu>E<gt> with support from Tim Bunce
1616E<lt>F<Tim.Bunce (at) ig.co.uk>E<gt> and the C<perl5-porters> mailing list.
150b260b
GS
1617
1618Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
a650b841 1619E<lt>F<tom (at) compton.nu>E<gt>.
5be1dfc7 1620
a650b841 1621Code for C<constant()>s regenerated by Nicholas Clark E<lt>F<nick (at) ccl4.org>E<gt>.
23642f4b
NW
1622
1623Failover to different communication modes by Nick Williams
a650b841
AT
1624E<lt>F<Nick.Williams (at) morganstanley.com>E<gt>.
1625
1626Extracted from core distribution for publishing on the CPAN by
1627SE<eacute>bastien Aperghis-Tramoni E<lt>sebastien (at) aperghis.netE<gt>.
b903fcff 1628
89c3c464 1629XS code for using native C functions borrowed from C<L<Unix::Syslog>>,
a650b841 1630written by Marcus Harnisch E<lt>F<marcus.harnisch (at) gmx.net>E<gt>.
89c3c464 1631
a650b841
AT
1632Yves Orton suggested and helped for making C<Sys::Syslog> use the native
1633event logger under Win32 systems.
1634
1635Jerry D. Hedden and Reini Urban provided greatly appreciated help to
1636debug and polish C<Sys::Syslog> under Cygwin.
8168e71f
SP
1637
1638
1639=head1 BUGS
1640
1641Please report any bugs or feature requests to
a650b841 1642C<bug-sys-syslog (at) rt.cpan.org>, or through the web interface at
35a209d1 1643L<http://rt.cpan.org/Public/Dist/Display.html?Name=Sys-Syslog>.
8168e71f
SP
1644I will be notified, and then you'll automatically be notified of progress on
1645your bug as I make changes.
1646
1647
1648=head1 SUPPORT
1649
1650You can find documentation for this module with the perldoc command.
1651
1652 perldoc Sys::Syslog
1653
1654You can also look for information at:
1655
1656=over 4
1657
1658=item * AnnoCPAN: Annotated CPAN documentation
1659
1660L<http://annocpan.org/dist/Sys-Syslog>
1661
1662=item * CPAN Ratings
1663
1664L<http://cpanratings.perl.org/d/Sys-Syslog>
1665
1666=item * RT: CPAN's request tracker
1667
06fd9d7a 1668L<http://rt.cpan.org/Dist/Display.html?Queue=Sys-Syslog>
8168e71f
SP
1669
1670=item * Search CPAN
1671
6e4ef777
SP
1672L<http://search.cpan.org/dist/Sys-Syslog/>
1673
33f804f6 1674=item * MetaCPAN
6e4ef777 1675
33f804f6 1676L<https://metacpan.org/module/Sys::Syslog>
6e4ef777
SP
1677
1678=item * Perl Documentation
1679
1680L<http://perldoc.perl.org/Sys/Syslog.html>
8168e71f
SP
1681
1682=back
1683
1684
35a209d1
AT
1685=head1 COPYRIGHT
1686
33f804f6 1687Copyright (C) 1990-2012 by Larry Wall and others.
35a209d1
AT
1688
1689
8168e71f
SP
1690=head1 LICENSE
1691
1692This program is free software; you can redistribute it and/or modify it
1693under the same terms as Perl itself.
1694
5be1dfc7 1695=cut
a650b841
AT
1696
1697=begin comment
1698
1699Notes for the future maintainer (even if it's still me..)
1700- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1701
1702Using Google Code Search, I search who on Earth was relying on $host being
1703public. It found 5 hits:
1704
1705* First was inside Indigo Star Perl2exe documentation. Just an old version
1706of Sys::Syslog.
1707
1708
1709* One real hit was inside DalWeathDB, a weather related program. It simply
1710does a
1711
1712 $Sys::Syslog::host = '127.0.0.1';
1713
1714- L<http://www.gallistel.net/nparker/weather/code/>
1715
1716
1717* Two hits were in TPC, a fax server thingy. It does a
1718
1719 $Sys::Syslog::host = $TPC::LOGHOST;
1720
1721but also has this strange piece of code:
1722
1723 # work around perl5.003 bug
1724 sub Sys::Syslog::hostname {}
1725
1726I don't know what bug the author referred to.
1727
1728- L<http://www.tpc.int/>
a650b841
AT
1729- L<ftp://ftp-usa.tpc.int/pub/tpc/server/UNIX/>
1730
1731
1732* Last hit was in Filefix, which seems to be a FIDOnet mail program (!).
1733This one does not use $host, but has the following piece of code:
1734
1735 sub Sys::Syslog::hostname
1736 {
1737 use Sys::Hostname;
1738 return hostname;
1739 }
1740
1741I guess this was a more elaborate form of the previous bit, maybe because
1742of a bug in Sys::Syslog back then?
1743
1744- L<ftp://ftp.kiae.su/pub/unix/fido/>
1745
d329efa2
AT
1746
1747Links
1748-----
f93f88eb
AT
1749Linux Fast-STREAMS
1750- L<http://www.openss7.org/streams.html>
1751
d329efa2
AT
1752II12021: SYSLOGD HOWTO TCPIPINFO (z/OS, OS/390, MVS)
1753- L<http://www-1.ibm.com/support/docview.wss?uid=isg1II12021>
1754
1755Getting the most out of the Event Viewer
1756- L<http://www.codeproject.com/dotnet/evtvwr.asp?print=true>
1757
1758Log events to the Windows NT Event Log with JNI
1759- L<http://www.javaworld.com/javaworld/jw-09-2001/jw-0928-ntmessages.html>
1760
a650b841 1761=end comment
d329efa2 1762