Plop
A simple logging library for PHP
RotatingFile.php
1 <?php
2 /*
3  This file is part of Plop, a simple logging library for PHP.
4 
5  Copyright © 2010-2014 François Poirotte
6 
7  Plop is free software: you can redistribute it and/or modify
8  it under the terms of the GNU General Public License as published by
9  the Free Software Foundation, either version 3 of the License, or
10  (at your option) any later version.
11 
12  Plop is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  GNU General Public License for more details.
16 
17  You should have received a copy of the GNU General Public License
18  along with Plop. If not, see <http://www.gnu.org/licenses/>.
19 */
20 
21 namespace Plop\Handler;
22 
30 {
32  protected $maxBytes;
33 
35  protected $backupCount;
36 
69  public function __construct(
70  $filename,
71  $maxBytes = 0,
72  $backupCount = 0,
73  $mode = 'a',
74  $delay = 0
75  ) {
76  if ($maxBytes > 0) {
77  $mode = 'a';
78  }
79  parent::__construct($filename, $mode, $delay);
80  $this->maxBytes = $maxBytes;
81  $this->backupCount = $backupCount;
82  }
83 
85  protected function doRollover()
86  {
87  fclose($this->stream);
88  if ($this->backupCount > 0) {
89  for ($i = $this->backupCount - 1; $i > 0; $i--) {
90  $sfn = sprintf("%s.%d", $this->baseFilename, $i);
91  $dfn = sprintf("%s.%d", $this->baseFilename, $i + 1);
92  if (file_exists($sfn)) {
93  if (file_exists($dfn)) {
94  @unlink($dfn);
95  }
96  rename($sfn, $dfn);
97  }
98  }
99  $dfn = sprintf("%s.1", $this->baseFilename);
100  if (file_exists($dfn)) {
101  @unlink($dfn);
102  }
103  rename($this->baseFilename, $dfn);
104  }
105  $this->mode = 'w';
106  $this->stream = $this->open();
107  }
108 
110  protected function shouldRollover(\Plop\RecordInterface $record)
111  {
112  if (!$this->stream) {
113  $this->stream = $this->open();
114  }
115 
116  if ($this->maxBytes > 0) {
117  $msg = $this->format($record)."\n";
118  // The Python doc states this is due to a non-POSIX-compliant
119  // behaviour under Windows.
120  fseek($this->stream, 0, SEEK_END);
121  $newPos = ftell($this->stream) + strlen($msg);
122  if ($newPos >= $this->maxBytes || $newPos < 0) {
123  return true;
124  }
125  }
126  return false;
127  }
128 }
shouldRollover(\Plop\RecordInterface $record)
An handler the saves log messages in a file, which is rotated whenever it reaches a certain size...
$mode
Opening mode for the log file.
Definition: File.php:34
Interface for a log record.
__construct($filename, $maxBytes=0, $backupCount=0, $mode= 'a', $delay=0)
format(\Plop\RecordInterface $record)
$maxBytes
The maximum size the log file may reach before being rotated.
An abstract class for handlers that must deal with file rotations.
$backupCount
Number of backup log files to keep.