log-functions.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. if (file_exists($file)) {
  63. $filter = strtoupper($filter);
  64. switch ($filter) {
  65. case 'DEBUG':
  66. case 'INFO':
  67. case 'NOTICE':
  68. case 'WARNING':
  69. case 'ERROR':
  70. case 'CRITICAL':
  71. case 'ALERT':
  72. case 'EMERGENCY':
  73. break;
  74. case 'NONE':
  75. $filter = null;
  76. break;
  77. default:
  78. $filter = 'DEBUG';
  79. break;
  80. }
  81. $lineGenerator = Bcremer\LineReader\LineReader::readLinesBackwards($file);
  82. $lines = iterator_to_array($lineGenerator);
  83. if ($filter) {
  84. $results = [];
  85. foreach ($lines as $line) {
  86. if (stripos($line, '"' . $filter . '"') !== false) {
  87. $results[] = $line;
  88. }
  89. }
  90. $lines = $results;
  91. }
  92. return $this->formatLogResults($lines, $pageSize, $offset);
  93. }
  94. return false;
  95. }
  96. public function formatLogResults($lines, $pageSize, $offset)
  97. {
  98. $totalLines = count($lines);
  99. $totalPages = $totalLines / $pageSize;
  100. $results = array_slice($lines, $offset, $pageSize);
  101. $lines = [];
  102. foreach ($results as $line) {
  103. $lines[] = json_decode($line, true);
  104. }
  105. return [
  106. 'pageInfo' => [
  107. 'results' => $totalLines,
  108. 'totalPages' => ceil($totalPages),
  109. 'pageSize' => $pageSize,
  110. 'page' => $offset >= $totalPages ? -1 : ceil($offset / $pageSize) + 1
  111. ],
  112. 'results' => $lines
  113. ];
  114. }
  115. public function getLatestLogFile()
  116. {
  117. if ($this->log) {
  118. if (isset($this->log)) {
  119. $folder = $this->config['dbLocation'] . 'logs' . DIRECTORY_SEPARATOR;
  120. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  121. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  122. $files = [];
  123. foreach ($iteratorIterator as $info) {
  124. $files[] = $info->getPathname();
  125. }
  126. if (count($files) > 0) {
  127. usort($files, function ($x, $y) {
  128. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $x, $xArray);
  129. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $y, $yArray);
  130. return strtotime($xArray[0]) < strtotime($yArray[0]);
  131. });
  132. if (file_exists($files[0])) {
  133. return $files[0];
  134. }
  135. }
  136. }
  137. }
  138. return false;
  139. }
  140. public function getLogFiles()
  141. {
  142. if ($this->log) {
  143. if (isset($this->log)) {
  144. $folder = $this->config['dbLocation'] . 'logs' . DIRECTORY_SEPARATOR;
  145. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  146. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  147. $files = [];
  148. foreach ($iteratorIterator as $info) {
  149. $files[] = $info->getPathname();
  150. }
  151. if (count($files) > 0) {
  152. usort($files, function ($x, $y) {
  153. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $x, $xArray);
  154. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $y, $yArray);
  155. return strtotime($xArray[0]) < strtotime($yArray[0]);
  156. });
  157. return $files;
  158. }
  159. }
  160. }
  161. return false;
  162. }
  163. public function setLoggerChannel($channel = 'Organizr', $username = null)
  164. {
  165. if ($this->hasDB()) {
  166. $setLogger = false;
  167. if ($this->logger) {
  168. if ($channel) {
  169. if (strtolower($this->logger->getChannel()) !== strtolower($channel)) {
  170. $setLogger = true;
  171. }
  172. }
  173. if ($username) {
  174. if (strtolower($this->logger->getTraceId()) !== strtolower($channel)) {
  175. $setLogger = true;
  176. }
  177. }
  178. } else {
  179. $setLogger = true;
  180. }
  181. if ($setLogger) {
  182. $channel = $channel ?: 'Organizr';
  183. $this->setupLogger($channel, $username);
  184. }
  185. }
  186. }
  187. public function setupLogger($channel = 'Organizr', $username = null)
  188. {
  189. if ($this->hasDB()) {
  190. if ($this->log) {
  191. if (!$username) {
  192. $username = $this->user['username'] ?? 'System';
  193. }
  194. $loggerBuilder = new Nekonomokochan\PhpJsonLogger\LoggerBuilder();
  195. $loggerBuilder->setMaxFiles($this->config['maxLogFiles']);
  196. $loggerBuilder->setFileName($this->log);
  197. $loggerBuilder->setTraceId($username);
  198. $loggerBuilder->setChannel(ucwords(strtolower($channel)));
  199. switch ($this->config['logLevel']) {
  200. case 'DEBUG':
  201. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::DEBUG;
  202. break;
  203. case 'INFO':
  204. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::INFO;
  205. break;
  206. case 'NOTICE':
  207. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::NOTICE;
  208. break;
  209. case 'ERROR':
  210. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::ERROR;
  211. break;
  212. case 'CRITICAL':
  213. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::CRITICAL;
  214. break;
  215. case 'ALERT':
  216. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::ALERT;
  217. break;
  218. case 'EMERGENCY':
  219. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::EMERGENCY;
  220. break;
  221. default:
  222. $logLevel = Nekonomokochan\PhpJsonLogger\LoggerBuilder::WARNING;
  223. break;
  224. }
  225. $loggerBuilder->setLogLevel($logLevel);
  226. try {
  227. $this->logger = $loggerBuilder->build();
  228. } catch (Exception $e) {
  229. // nothing so far
  230. }
  231. /* setup:
  232. 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):
  233. $this->setLoggerChannel('Plex Homepage');
  234. normal log:
  235. $this->info('test');
  236. normal log with context ($context must be an array):
  237. $this->info('test', $context);
  238. exception:
  239. $this->critical($exception, $context);
  240. */
  241. }
  242. }
  243. }
  244. public function getLog($pageSize = 10, $offset = 0, $filter = 'NONE', $number = 0)
  245. {
  246. if ($this->log) {
  247. if (isset($this->log)) {
  248. if ($number !== 0) {
  249. $logs = $this->getLogFiles();
  250. $log = $logs[$number] ?? $this->getLatestLogFile();
  251. } else {
  252. $log = $this->getLatestLogFile();
  253. }
  254. $readLog = $this->readLog($log, 1000, 0, $filter);
  255. $this->setResponse(200, 'Results for log: ' . $log, $readLog);
  256. return $readLog;
  257. } else {
  258. $this->setResponse(404, 'Log not found');
  259. return false;
  260. }
  261. } else {
  262. $this->setResponse(409, 'Logging not setup');
  263. return false;
  264. }
  265. }
  266. public function purgeLog($number)
  267. {
  268. $this->setLoggerChannel('Logger');
  269. $this->debug('Starting log purge function');
  270. if ($this->log) {
  271. $this->debug('Checking if log id exists');
  272. if ($number !== 0) {
  273. $logs = $this->getLogFiles();
  274. $file = $logs[$number] ?? false;
  275. if (!$file) {
  276. $this->setResponse(404, 'Log not found');
  277. return false;
  278. }
  279. } else {
  280. $file = $this->getLatestLogFile();
  281. }
  282. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $file, $log);
  283. $log = $log[0];
  284. $this->debug('Checking if log exists');
  285. if (file_exists($file)) {
  286. $this->debug('Log: ' . $log . ' does exist');
  287. $this->debug('Attempting to purge log: ' . $log);
  288. if (unlink($file)) {
  289. $this->info('Log: ' . $log . ' has been purged/deleted');
  290. $this->setAPIResponse(null, 'Log purged');
  291. return true;
  292. } else {
  293. $this->warning('Log: ' . $log . ' could not be purged/deleted');
  294. $this->setAPIResponse('error', 'Log could not be purged', 500);
  295. return false;
  296. }
  297. } else {
  298. $this->debug('Log does not exist');
  299. $this->setAPIResponse('error', 'Log does not exist', 404);
  300. return false;
  301. }
  302. } else {
  303. $this->setResponse(409, 'Logging not setup');
  304. return false;
  305. }
  306. }
  307. public function logArray($context)
  308. {
  309. if (!is_array($context)) {
  310. if (is_string($context)) {
  311. return ['data' => $context];
  312. } else {
  313. $context = (string)$context;
  314. return ['data' => $context];
  315. }
  316. } else {
  317. return $context;
  318. }
  319. }
  320. function buildLogDropdown()
  321. {
  322. $logs = $this->getLogFiles();
  323. //<select class='form-control settings-dropdown-box system-settings-menu'><option value=''>About</option></select>
  324. if ($logs) {
  325. if (count($logs) > 0) {
  326. $options = '';
  327. $i = 0;
  328. foreach ($logs as $k => $log) {
  329. $selected = $i == 0 ? 'selected' : '';
  330. preg_match('/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $log, $name);
  331. $options .= '<option data-id="' . $k . '" value="api/v2/log/' . $k . '" ' . $selected . '>' . $name[0] . '</option>';
  332. $i++;
  333. }
  334. return '<select class="form-control choose-organizr-log">' . $options . '</select>';
  335. }
  336. }
  337. return false;
  338. }
  339. }