|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Dframe\ActivityLog\Demo\Drivers; |
| 4 | + |
| 5 | +define('APP_DIR', __DIR__ . '/../'); |
| 6 | + |
| 7 | +/** |
| 8 | + * Dframe/ActivityLog |
| 9 | + * Copyright (c) Sławomir Kaleta |
| 10 | + * |
| 11 | + * @license https://github.com/dusta/activityLog/blob/master/LICENCE |
| 12 | + */ |
| 13 | +class PSR3FileLog extends \Psr\Log\AbstractLogger implements \Psr\Log\LoggerInterface, \Dframe\ActivityLog\Driver |
| 14 | +{ |
| 15 | + const FILE_DB = APP_DIR . 'Logs' . DIRECTORY_SEPARATOR . 'db.txt'; |
| 16 | + |
| 17 | + public function push($loggedId, $on, $entity, $log) |
| 18 | + { |
| 19 | + $data = [ |
| 20 | + 'level' => $entity['data']['level'], |
| 21 | + 'data' => $entity['data']['message'], |
| 22 | + 'context' => $entity['data']['context'] |
| 23 | + ]; |
| 24 | + |
| 25 | + $fp = fopen(self::FILE_DB, 'rw+'); |
| 26 | + if (!flock($fp, LOCK_EX)) { |
| 27 | + return false; |
| 28 | + } |
| 29 | + |
| 30 | + if (filesize(self::FILE_DB) > 0) { |
| 31 | + $contents = null; |
| 32 | + while (!feof($fp)) { |
| 33 | + $contents .= fread($fp, 8192); |
| 34 | + } |
| 35 | + |
| 36 | + $jsondecode = json_decode($contents, true); |
| 37 | + $jsondecode[] = $data; |
| 38 | + |
| 39 | + flock($fp, LOCK_UN); |
| 40 | + fclose($fp); |
| 41 | + |
| 42 | + $fp = fopen(self::FILE_DB, 'w+'); |
| 43 | + $result = fwrite($fp, json_encode($jsondecode)); |
| 44 | + } else { |
| 45 | + $result = fwrite($fp, json_encode($data)); |
| 46 | + } |
| 47 | + |
| 48 | + flock($fp, LOCK_UN); |
| 49 | + fclose($fp); |
| 50 | + |
| 51 | + |
| 52 | + return $result !== false; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Logs with an arbitrary level. |
| 57 | + * |
| 58 | + * @param mixed $level |
| 59 | + * @param string $message |
| 60 | + * @param array $context |
| 61 | + * |
| 62 | + * @return void |
| 63 | + */ |
| 64 | + public function log($level, $message, array $context = []) |
| 65 | + { |
| 66 | + $this->push(null, null, null, $message); |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * @param $start |
| 71 | + * @param $limit |
| 72 | + * @param $whereArray |
| 73 | + * @param string $order |
| 74 | + * @param string $sort |
| 75 | + * |
| 76 | + * @return mixed |
| 77 | + */ |
| 78 | + public function logs($start, $limit, $where, $order, $sort) |
| 79 | + { |
| 80 | + if (!file_exists(self::FILE_DB)) { |
| 81 | + return false; |
| 82 | + } |
| 83 | + |
| 84 | + $fp = fopen(self::FILE_DB, 'r'); |
| 85 | + |
| 86 | + $contents = null; |
| 87 | + while (!feof($fp)) { |
| 88 | + $contents .= fread($fp, 8192); |
| 89 | + } |
| 90 | + |
| 91 | + fclose($fp); |
| 92 | + |
| 93 | + $data = json_decode($contents, true); |
| 94 | + return ['return' => true, 'data' => $data]; |
| 95 | + } |
| 96 | +} |
0 commit comments