log-functions.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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($lines, iterator_to_array($lineGenerator));
  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 (!$username) {
  207. $username = $this->user['username'] ?? 'System';
  208. }
  209. $loggerBuilder = new OrganizrLogger();
  210. $loggerBuilder->setReadyStatus($this->hasDB() && $this->log);
  211. $loggerBuilder->setMaxFiles($this->config['maxLogFiles']);
  212. $loggerBuilder->setFileName($this->tempLogIfNeeded());
  213. $loggerBuilder->setTraceId($username);
  214. $loggerBuilder->setChannel(ucwords(strtolower($channel)));
  215. switch ($this->config['logLevel']) {
  216. case 'DEBUG':
  217. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::DEBUG;
  218. break;
  219. case 'INFO':
  220. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::INFO;
  221. break;
  222. case 'NOTICE':
  223. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::NOTICE;
  224. break;
  225. case 'ERROR':
  226. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::ERROR;
  227. break;
  228. case 'CRITICAL':
  229. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::CRITICAL;
  230. break;
  231. case 'ALERT':
  232. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::ALERT;
  233. break;
  234. case 'EMERGENCY':
  235. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::EMERGENCY;
  236. break;
  237. default:
  238. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::WARNING;
  239. break;
  240. }
  241. $loggerBuilder->setLogLevel($logLevel);
  242. try {
  243. $this->logger = $loggerBuilder->build();
  244. } catch (Exception $e) {
  245. // nothing so far
  246. $this->logger = null;
  247. }
  248. /* setup:
  249. 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):
  250. $this->setLoggerChannel('Plex Homepage');
  251. normal log:
  252. $this->logger->info('test');
  253. normal log with context ($context must be an array):
  254. $this->logger->info('test', $context);
  255. exception:
  256. $this->logger->critical($exception, $context);
  257. */
  258. }
  259. public function tempLogIfNeeded()
  260. {
  261. if (!$this->log) {
  262. return $this->root . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . 'organizr-' . $this->randString() . '.log';
  263. } else {
  264. return $this->log;
  265. }
  266. }
  267. public function getLog($pageSize = 10, $offset = 0, $filter = 'NONE', $number = 0)
  268. {
  269. if ($this->log) {
  270. if (isset($this->log)) {
  271. if ($number !== 0) {
  272. if ($number == 'all' || $number == 'combined-logs') {
  273. $log = 'combined-logs';
  274. } else {
  275. $logs = $this->getLogFiles();
  276. $log = $logs[$number] ?? $this->getLatestLogFile();
  277. }
  278. } else {
  279. $log = $this->getLatestLogFile();
  280. }
  281. $readLog = $this->readLog($log, 1000, 0, $filter);
  282. $this->setResponse(200, 'Results for log: ' . $log, $readLog);
  283. return $readLog;
  284. } else {
  285. $this->setResponse(404, 'Log not found');
  286. return false;
  287. }
  288. } else {
  289. $this->setResponse(409, 'Logging not setup');
  290. return false;
  291. }
  292. }
  293. public function purgeLog($number)
  294. {
  295. $this->setLoggerChannel('Logger');
  296. $this->logger->debug('Starting log purge function');
  297. if ($this->log) {
  298. $this->logger->debug('Checking if log id exists');
  299. if ($number !== 0) {
  300. if ($number == 'all' || $number == 'combined-logs') {
  301. $this->logger->debug('Cannot delete log [all] as it is not a real log');
  302. $this->setResponse(409, 'Cannot delete log [all] as it is not a real log');
  303. return false;
  304. }
  305. $logs = $this->getLogFiles();
  306. $file = $logs[$number] ?? false;
  307. if (!$file) {
  308. $this->setResponse(404, 'Log not found');
  309. return false;
  310. }
  311. } else {
  312. $file = $this->getLatestLogFile();
  313. }
  314. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $file, $log);
  315. $log = $log[0];
  316. $this->logger->debug('Checking if log exists');
  317. if (file_exists($file)) {
  318. $this->logger->debug('Log: ' . $log . ' does exist');
  319. $this->logger->debug('Attempting to purge log: ' . $log);
  320. if (unlink($file)) {
  321. $this->logger->info('Log: ' . $log . ' has been purged/deleted');
  322. $this->setResponse(200, 'Log purged');
  323. return true;
  324. } else {
  325. $this->logger->warning('Log: ' . $log . ' could not be purged/deleted');
  326. $this->setResponse(500, 'Log could not be purged');
  327. return false;
  328. }
  329. } else {
  330. $this->logger->debug('Log does not exist');
  331. $this->setResponse(404, 'Log does not exist');
  332. return false;
  333. }
  334. } else {
  335. $this->setResponse(409, 'Logging not setup');
  336. return false;
  337. }
  338. }
  339. public function logArray($context)
  340. {
  341. if (!is_array($context)) {
  342. if (is_string($context)) {
  343. return ['data' => $context];
  344. } else {
  345. $context = (string)$context;
  346. return ['data' => $context];
  347. }
  348. } else {
  349. return $context;
  350. }
  351. }
  352. function buildLogDropdown()
  353. {
  354. $logs = $this->getLogFiles();
  355. //<select class='form-control settings-dropdown-box system-settings-menu'><option value=''>About</option></select>
  356. if ($logs) {
  357. if (count($logs) > 0) {
  358. $options = '';
  359. $i = 0;
  360. foreach ($logs as $k => $log) {
  361. $selected = $i == 0 ? 'selected' : '';
  362. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $log, $name);
  363. $options .= '<option data-id="' . $k . '" value="api/v2/log/' . $k . '?filter=NONE&pageSize=1000&offset=0" ' . $selected . '>' . $name[0] . '</option>';
  364. $i++;
  365. }
  366. 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>';
  367. }
  368. }
  369. return false;
  370. }
  371. function buildFilterDropdown()
  372. {
  373. $dropdownItems = '<li><a href="javascript:toggleLogFilter(\'DEBUG\')"><span lang="en">Debug</span></a></li>';
  374. $dropdownItems .= '<li><a href="javascript:toggleLogFilter(\'INFO\')"><span lang="en">Info</span></a></li>';
  375. $dropdownItems .= '<li><a href="javascript:toggleLogFilter(\'NOTICE\')"><span lang="en">Notice</span></a></li>';
  376. $dropdownItems .= '<li><a href="javascript:toggleLogFilter(\'WARNING\')"><span lang="en">Warning</span></a></li>';
  377. $dropdownItems .= '<li><a href="javascript:toggleLogFilter(\'ERROR\')"><span lang="en">Error</span></a></li>';
  378. $dropdownItems .= '<li><a href="javascript:toggleLogFilter(\'CRITICAL\')"><span lang="en">Critical</span></a></li>';
  379. $dropdownItems .= '<li><a href="javascript:toggleLogFilter(\'ALERT\')"><span lang="en">Alert</span></a></li>';
  380. $dropdownItems .= '<li><a href="javascript:toggleLogFilter(\'EMERGENCY\')"><span lang="en">Emergency</span></a></li>';
  381. $dropdownItems .= '<li class="divider"></li><li><a href="javascript:toggleLogFilter(\'NONE\')"><span lang="en">None</span></a></li>';
  382. return '<button aria-expanded="false" data-toggle="dropdown" class="btn btn-inverse dropdown-toggle waves-effect waves-light pull-right m-r-5 hidden-xs" type="button"> <span class="log-filter-text m-r-5" lang="en">NONE</span><i class="fa fa-filter m-r-5"></i></button><ul role="menu" class="dropdown-menu log-filter-dropdown pull-right">' . $dropdownItems . '</ul>';
  383. }
  384. }