log-functions.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. trait LogFunctions
  3. {
  4. public function debug($msg, $context = [])
  5. {
  6. if ($this->logger) {
  7. $this->logger->debug($msg, $context);
  8. }
  9. }
  10. public function info($msg, $context = [])
  11. {
  12. if ($this->logger) {
  13. $this->logger->info($msg, $context);
  14. }
  15. }
  16. public function notice($msg, $context = [])
  17. {
  18. if ($this->logger) {
  19. $this->logger->notice($msg, $context);
  20. }
  21. }
  22. public function warning($msg, $context = [])
  23. {
  24. if ($this->logger) {
  25. $this->logger->warning($msg, $context);
  26. }
  27. }
  28. public function error($msg, $context = [])
  29. {
  30. if ($this->logger) {
  31. $this->logger->error($msg, $context);
  32. }
  33. }
  34. public function critical($msg, $context = [])
  35. {
  36. if ($this->logger) {
  37. $this->logger->critical($msg, $context);
  38. }
  39. }
  40. public function alert($msg, $context = [])
  41. {
  42. if ($this->logger) {
  43. $this->logger->alert($msg, $context);
  44. }
  45. }
  46. public function emergency($msg, $context = [])
  47. {
  48. if ($this->logger) {
  49. $this->logger->emergency($msg, $context);
  50. }
  51. }
  52. public function setOrganizrLog()
  53. {
  54. if ($this->hasDB()) {
  55. $logPath = $this->config['dbLocation'] . 'logs' . DIRECTORY_SEPARATOR;
  56. return $logPath . 'organizr.log';
  57. }
  58. return false;
  59. }
  60. public function readLog($file, $pageSize = 10, $offset = 0, $filter = 'NONE')
  61. {
  62. $combinedLogs = false;
  63. if ($file == 'combined-logs') {
  64. $combinedLogs = true;
  65. }
  66. if (file_exists($file) || $combinedLogs) {
  67. $filter = strtoupper($filter);
  68. switch ($filter) {
  69. case 'DEBUG':
  70. case 'INFO':
  71. case 'NOTICE':
  72. case 'WARNING':
  73. case 'ERROR':
  74. case 'CRITICAL':
  75. case 'ALERT':
  76. case 'EMERGENCY':
  77. break;
  78. case 'NONE':
  79. $filter = null;
  80. break;
  81. default:
  82. $filter = 'DEBUG';
  83. break;
  84. }
  85. if ($combinedLogs) {
  86. $logs = $this->getLogFiles();
  87. $lines = [];
  88. if ($logs) {
  89. foreach ($logs as $log) {
  90. if (file_exists($log)) {
  91. $lineGenerator = Bcremer\LineReader\LineReader::readLinesBackwards($log);
  92. $lines = array_merge(iterator_to_array($lineGenerator), $lines);
  93. }
  94. }
  95. }
  96. } else {
  97. $lineGenerator = Bcremer\LineReader\LineReader::readLinesBackwards($file);
  98. $lines = iterator_to_array($lineGenerator);
  99. }
  100. if ($filter) {
  101. $results = [];
  102. foreach ($lines as $line) {
  103. if (stripos($line, '"' . $filter . '"') !== false) {
  104. $results[] = $line;
  105. }
  106. }
  107. $lines = $results;
  108. }
  109. return $this->formatLogResults($lines, $pageSize, $offset);
  110. }
  111. return false;
  112. }
  113. public function formatLogResults($lines, $pageSize, $offset)
  114. {
  115. $totalLines = count($lines);
  116. $totalPages = $totalLines / $pageSize;
  117. $results = array_slice($lines, $offset, $pageSize);
  118. $lines = [];
  119. foreach ($results as $line) {
  120. $lines[] = json_decode($line, true);
  121. }
  122. return [
  123. 'pageInfo' => [
  124. 'results' => $totalLines,
  125. 'totalPages' => ceil($totalPages),
  126. 'pageSize' => $pageSize,
  127. 'page' => $offset >= $totalPages ? -1 : ceil($offset / $pageSize) + 1
  128. ],
  129. 'results' => $lines
  130. ];
  131. }
  132. public function getLatestLogFile()
  133. {
  134. if ($this->log) {
  135. if (isset($this->log)) {
  136. $folder = $this->config['dbLocation'] . 'logs' . DIRECTORY_SEPARATOR;
  137. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  138. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  139. $files = [];
  140. foreach ($iteratorIterator as $info) {
  141. $files[] = $info->getPathname();
  142. }
  143. if (count($files) > 0) {
  144. usort($files, function ($x, $y) {
  145. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $x, $xArray);
  146. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $y, $yArray);
  147. return strtotime($xArray[0]) < strtotime($yArray[0]);
  148. });
  149. if (file_exists($files[0])) {
  150. return $files[0];
  151. }
  152. }
  153. }
  154. }
  155. return false;
  156. }
  157. public function getLogFiles()
  158. {
  159. if ($this->log) {
  160. if (isset($this->log)) {
  161. $folder = $this->config['dbLocation'] . 'logs' . DIRECTORY_SEPARATOR;
  162. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  163. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  164. $files = [];
  165. foreach ($iteratorIterator as $info) {
  166. $files[] = $info->getPathname();
  167. }
  168. if (count($files) > 0) {
  169. usort($files, function ($x, $y) {
  170. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $x, $xArray);
  171. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $y, $yArray);
  172. return strtotime($xArray[0]) < strtotime($yArray[0]);
  173. });
  174. return $files;
  175. }
  176. }
  177. }
  178. return false;
  179. }
  180. public function setLoggerChannel($channel = 'Organizr', $username = null)
  181. {
  182. if ($this->hasDB()) {
  183. $setLogger = false;
  184. if ($this->logger) {
  185. if ($channel) {
  186. if (strtolower($this->logger->getChannel()) !== strtolower($channel)) {
  187. $setLogger = true;
  188. }
  189. }
  190. if ($username) {
  191. if (strtolower($this->logger->getTraceId()) !== strtolower($channel)) {
  192. $setLogger = true;
  193. }
  194. }
  195. } else {
  196. $setLogger = true;
  197. }
  198. if ($setLogger) {
  199. $channel = $channel ?: 'Organizr';
  200. $this->setupLogger($channel, $username);
  201. }
  202. }
  203. }
  204. public function setupLogger($channel = 'Organizr', $username = null)
  205. {
  206. if ($this->hasDB()) {
  207. if ($this->log) {
  208. if (!$username) {
  209. $username = $this->user['username'] ?? 'System';
  210. }
  211. $loggerBuilder = new Nekonomokochan\PhpJsonLogger\LoggerBuilder();
  212. $loggerBuilder->setMaxFiles($this->config['maxLogFiles']);
  213. $loggerBuilder->setFileName($this->log);
  214. $loggerBuilder->setTraceId($username);
  215. $loggerBuilder->setChannel(ucwords(strtolower($channel)));
  216. switch ($this->config['logLevel']) {
  217. case 'DEBUG':
  218. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::DEBUG;
  219. break;
  220. case 'INFO':
  221. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::INFO;
  222. break;
  223. case 'NOTICE':
  224. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::NOTICE;
  225. break;
  226. case 'ERROR':
  227. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::ERROR;
  228. break;
  229. case 'CRITICAL':
  230. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::CRITICAL;
  231. break;
  232. case 'ALERT':
  233. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::ALERT;
  234. break;
  235. case 'EMERGENCY':
  236. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::EMERGENCY;
  237. break;
  238. default:
  239. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::WARNING;
  240. break;
  241. }
  242. $loggerBuilder->setLogLevel($logLevel);
  243. try {
  244. $this->logger = $loggerBuilder->build();
  245. } catch (Exception $e) {
  246. // nothing so far
  247. $this->logger = null;
  248. }
  249. /* setup:
  250. set the log channel before you send log (You can set an optional Username (2nd Variable) | If user is logged already logged in, it will use their username):
  251. $this->setLoggerChannel('Plex Homepage');
  252. normal log:
  253. $this->info('test');
  254. normal log with context ($context must be an array):
  255. $this->info('test', $context);
  256. exception:
  257. $this->critical($exception, $context);
  258. */
  259. } else {
  260. $this->logger = null;
  261. }
  262. } else {
  263. $this->logger = null;
  264. }
  265. }
  266. public function getLog($pageSize = 10, $offset = 0, $filter = 'NONE', $number = 0)
  267. {
  268. if ($this->log) {
  269. if (isset($this->log)) {
  270. if ($number !== 0) {
  271. if ($number == 'all' || $number == 'combined-logs') {
  272. $log = 'combined-logs';
  273. } else {
  274. $logs = $this->getLogFiles();
  275. $log = $logs[$number] ?? $this->getLatestLogFile();
  276. }
  277. } else {
  278. $log = $this->getLatestLogFile();
  279. }
  280. $readLog = $this->readLog($log, 1000, 0, $filter);
  281. $this->setResponse(200, 'Results for log: ' . $log, $readLog);
  282. return $readLog;
  283. } else {
  284. $this->setResponse(404, 'Log not found');
  285. return false;
  286. }
  287. } else {
  288. $this->setResponse(409, 'Logging not setup');
  289. return false;
  290. }
  291. }
  292. public function purgeLog($number)
  293. {
  294. $this->setLoggerChannel('Logger');
  295. $this->debug('Starting log purge function');
  296. if ($this->log) {
  297. $this->debug('Checking if log id exists');
  298. if ($number !== 0) {
  299. if ($number == 'all' || $number == 'combined-logs') {
  300. $this->debug('Cannot delete log [all] as it is not a real log');
  301. $this->setResponse(409, 'Cannot delete log [all] as it is not a real log');
  302. return false;
  303. }
  304. $logs = $this->getLogFiles();
  305. $file = $logs[$number] ?? false;
  306. if (!$file) {
  307. $this->setResponse(404, 'Log not found');
  308. return false;
  309. }
  310. } else {
  311. $file = $this->getLatestLogFile();
  312. }
  313. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $file, $log);
  314. $log = $log[0];
  315. $this->debug('Checking if log exists');
  316. if (file_exists($file)) {
  317. $this->debug('Log: ' . $log . ' does exist');
  318. $this->debug('Attempting to purge log: ' . $log);
  319. if (unlink($file)) {
  320. $this->info('Log: ' . $log . ' has been purged/deleted');
  321. $this->setResponse(200, 'Log purged');
  322. return true;
  323. } else {
  324. $this->warning('Log: ' . $log . ' could not be purged/deleted');
  325. $this->setResponse(500, 'Log could not be purged');
  326. return false;
  327. }
  328. } else {
  329. $this->debug('Log does not exist');
  330. $this->setResponse(404, 'Log does not exist');
  331. return false;
  332. }
  333. } else {
  334. $this->setResponse(409, 'Logging not setup');
  335. return false;
  336. }
  337. }
  338. public function logArray($context)
  339. {
  340. if (!is_array($context)) {
  341. if (is_string($context)) {
  342. return ['data' => $context];
  343. } else {
  344. $context = (string)$context;
  345. return ['data' => $context];
  346. }
  347. } else {
  348. return $context;
  349. }
  350. }
  351. function buildLogDropdown()
  352. {
  353. $logs = $this->getLogFiles();
  354. //<select class='form-control settings-dropdown-box system-settings-menu'><option value=''>About</option></select>
  355. if ($logs) {
  356. if (count($logs) > 0) {
  357. $options = '';
  358. $i = 0;
  359. foreach ($logs as $k => $log) {
  360. $selected = $i == 0 ? 'selected' : '';
  361. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $log, $name);
  362. $options .= '<option data-id="' . $k . '" value="api/v2/log/' . $k . '?filter=NONE&pageSize=1000&offset=0" ' . $selected . '>' . $name[0] . '</option>';
  363. $i++;
  364. }
  365. return '<select class="form-control choose-organizr-log"><option data-id="all" value="api/v2/log/all?filter=NONE&pageSize=1000&offset=0">All</option>' . $options . '</select>';
  366. }
  367. }
  368. return false;
  369. }
  370. }