home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / languages / perl / tutorial / eg / syslog.pl < prev    next >
Encoding:
Perl Script  |  1990-03-12  |  1.8 KB  |  82 lines

  1. #
  2. # syslog.pl
  3. #
  4. # tom christiansen <tchrist@convex.com>
  5. #
  6. # call syslog() with a string priority and a list of printf() args
  7. # like syslog(3) but using logger(8).  will only open a new pipe
  8. # to logger if it needs to.
  9. #
  10. #  usage: do 'syslog.pl' || die "syslog.pl: $@";
  11. #
  12. #  then (put these all in a script to test function)
  13. #        
  14. #
  15. #    do openlog($program,'user');
  16. #    do syslog('info','this is another test');
  17. #    do syslog('warn','this is a better test: %d', time);
  18. #    do closelog();
  19. #    
  20. #    do syslog('debug','this is the last test');
  21. #    do openlog("$program $$",'user');
  22. #    do syslog('notice','fooprogram: this is really done');
  23. #
  24. #    $! = 55;
  25. #    do syslog('info','problem was %m'); # %m == $! in syslog(3)
  26.  
  27. package syslog;
  28.  
  29. $logpath = '/usr/ucb/logger';
  30.  
  31. $opriority = $ofacility = $facility = $ident = '';
  32.  
  33. die "syslog: can't call $logpath: $!" unless -x $logpath;
  34.  
  35. sub main'openlog {
  36.     &main'closelog if $logopen;
  37.     ($ident, $facility) = @_;  # package vars
  38.  
  39. sub main'closelog {
  40.     $facility = $ident = '';
  41.     if ($logopen) {
  42.     $logopen = 0;
  43.     close LOG;
  44.     } 
  45.  
  46. sub main'syslog {
  47.     local($priority) = shift;
  48.     local($mask) = shift;
  49.     local($message, $whoami, $oldfh);
  50.  
  51.     $whoami = $ident;
  52.  
  53.     die "syslog: expected both priority and mask" unless $mask && $priority;
  54.  
  55.     $facility = "user" unless $facility;
  56.  
  57.     if (!$ident && $mask =~ /^(\S.*):\s?(.*)/) {
  58.     $whoami = $1;
  59.     $mask = $2;
  60.     } 
  61.  
  62.     $mask =~ s/%m/$!/g;
  63.     $mask .= "\n" unless $mask =~ /\n$/;
  64.  
  65.     $whoami = sprintf ("%s %d", $ENV{'USER'}, $$) unless $whoami;
  66.  
  67.     if ($opriority ne $priority || $ofacility ne $facility) {
  68.     $opriority = $priority;
  69.     $ofacility = $facility;
  70.     close LOG if $logopen++;
  71.     open(LOG, "| $logpath -t '$whoami' -p '$facility.$priority'");
  72.     $oldfh = select(LOG);
  73.     $| = 1;
  74.     select($oldfh);
  75.     } 
  76.     printf LOG "$mask", @_;
  77. }
  78.  
  79. 1;
  80.