4 * This file is part of the Monolog package.
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Monolog\Handler;
17 * Simple handler wrapper that deduplicates log records across multiple requests
19 * It also includes the BufferHandler functionality and will buffer
20 * all messages until the end of the request or flush() is called.
22 * This works by storing all log records' messages above $deduplicationLevel
23 * to the file specified by $deduplicationStore. When further logs come in at the end of the
24 * request (or when flush() is called), all those above $deduplicationLevel are checked
25 * against the existing stored logs. If they match and the timestamps in the stored log is
26 * not older than $time seconds, the new log record is discarded. If no log record is new, the
27 * whole data set is discarded.
29 * This is mainly useful in combination with Mail handlers or things like Slack or HipChat handlers
30 * that send messages to people, to avoid spamming with the same message over and over in case of
31 * a major component failure like a database server being down which makes all requests fail in the
34 * @author Jordi Boggiano <j.boggiano@seld.be>
36 class DeduplicationHandler extends BufferHandler
41 protected $deduplicationStore;
46 protected $deduplicationLevel;
59 * @param HandlerInterface $handler Handler.
60 * @param string $deduplicationStore The file/path where the deduplication log should be kept
61 * @param int $deduplicationLevel The minimum logging level for log records to be looked at for deduplication purposes
62 * @param int $time The period (in seconds) during which duplicate entries should be suppressed after a given log is sent through
63 * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
65 public function __construct(HandlerInterface $handler, $deduplicationStore = null, $deduplicationLevel = Logger::ERROR, $time = 60, $bubble = true)
67 parent::__construct($handler, 0, Logger::DEBUG, $bubble, false);
69 $this->deduplicationStore = $deduplicationStore === null ? sys_get_temp_dir() . '/monolog-dedup-' . substr(md5(__FILE__), 0, 20) .'.log' : $deduplicationStore;
70 $this->deduplicationLevel = Logger::toMonologLevel($deduplicationLevel);
74 public function flush()
76 if ($this->bufferSize === 0) {
82 foreach ($this->buffer as $record) {
83 if ($record['level'] >= $this->deduplicationLevel) {
85 $passthru = $passthru || !$this->isDuplicate($record);
87 $this->appendRecord($record);
92 // default of null is valid as well as if no record matches duplicationLevel we just pass through
93 if ($passthru === true || $passthru === null) {
94 $this->handler->handleBatch($this->buffer);
100 $this->collectLogs();
104 private function isDuplicate(array $record)
106 if (!file_exists($this->deduplicationStore)) {
110 $store = file($this->deduplicationStore, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
111 if (!is_array($store)) {
115 $yesterday = time() - 86400;
116 $timestampValidity = $record['datetime']->getTimestamp() - $this->time;
117 $expectedMessage = preg_replace('{[\r\n].*}', '', $record['message']);
119 for ($i = count($store) - 1; $i >= 0; $i--) {
120 list($timestamp, $level, $message) = explode(':', $store[$i], 3);
122 if ($level === $record['level_name'] && $message === $expectedMessage && $timestamp > $timestampValidity) {
126 if ($timestamp < $yesterday) {
134 private function collectLogs()
136 if (!file_exists($this->deduplicationStore)) {
140 $handle = fopen($this->deduplicationStore, 'rw+');
141 flock($handle, LOCK_EX);
142 $validLogs = array();
144 $timestampValidity = time() - $this->time;
146 while (!feof($handle)) {
147 $log = fgets($handle);
148 if (substr($log, 0, 10) >= $timestampValidity) {
153 ftruncate($handle, 0);
155 foreach ($validLogs as $log) {
156 fwrite($handle, $log);
159 flock($handle, LOCK_UN);
165 private function appendRecord(array $record)
167 file_put_contents($this->deduplicationStore, $record['datetime']->getTimestamp() . ':' . $record['level_name'] . ':' . preg_replace('{[\r\n].*}', '', $record['message']) . "\n", FILE_APPEND);