SHARE
TWEET

Untitled

a guest Mar 27th, 2017 43 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package FusionInventory::Agent::Logger::File;
  2.  
  3. use strict;
  4. use warnings;
  5. use base 'FusionInventory::Agent::Logger::Backend';
  6.  
  7. use English qw(-no_match_vars);
  8. use Fcntl qw(:flock);
  9. use File::stat;
  10.  
  11. sub new {
  12.     my ($class, %params) = @_;
  13.  
  14.     my $self = {
  15.         logfile         => $params{config}->{logfile},
  16.         logfile_maxsize => $params{config}->{'logfile-maxsize'} ?
  17.             $params{config}->{'logfile-maxsize'} * 1024 * 1024 : 0
  18.     };
  19.     bless $self, $class;
  20.  
  21.     return $self;
  22. }
  23.  
  24. sub addMessage {
  25.     my ($self, %params) = @_;
  26.  
  27.     my $level = $params{level};
  28.     my $message = $params{message};
  29.  
  30.     my $handle;
  31.     if ($self->{logfile_maxsize}) {
  32.         my $stat = stat($self->{logfile});
  33.         if ($stat && $stat->size() > $self->{logfile_maxsize}) {
  34.             if (!open $handle, '>', $self->{logfile}) {
  35.                 warn "Can't open $self->{logfile}: $ERRNO";
  36.                 return;
  37.             }
  38.         }
  39.     }
  40.  
  41.     if (!$handle && !open $handle, '>>', $self->{logfile}) {
  42.         warn "can't open $self->{logfile}: $ERRNO";
  43.         return;
  44.     }
  45.  
  46.     my $locked;
  47.     my $retryTill = time + 60;
  48.  
  49.     while ($retryTill > time && !$locked) {
  50.         ## no critic (ProhibitBitwise)
  51.         # get an exclusive lock on log file
  52.         $locked = 1 if flock($handle, LOCK_EX|LOCK_NB);
  53.     }
  54.  
  55.     if (!$locked) {
  56.         die "can't get an exclusive lock on $self->{logfile}: $ERRNO";
  57.     }
  58.  
  59.     print {$handle}
  60.         "[". localtime() ."]" .
  61.         "[$level]" .
  62.         " $message\n";
  63.  
  64.     # closing handle release the lock automatically
  65.     close $handle;
  66.  
  67. }
  68.  
  69. 1;
  70. __END__
  71.  
  72. =head1 NAME
  73.  
  74. FusionInventory::Agent::Logger::File - A file backend for the logger
  75.  
  76. =head1 DESCRIPTION
  77.  
  78. This is a file-based backend for the logger. It supports automatic filesize
  79. limitation.
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top