LogViewerCommand.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * @package Grav\Console\Cli
  4. *
  5. * @copyright Copyright (c) 2015 - 2023 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Console\Cli;
  9. use DateTime;
  10. use Grav\Common\Grav;
  11. use Grav\Common\Helpers\LogViewer;
  12. use Grav\Console\GravCommand;
  13. use Symfony\Component\Console\Input\InputOption;
  14. /**
  15. * Class LogViewerCommand
  16. * @package Grav\Console\Cli
  17. */
  18. class LogViewerCommand extends GravCommand
  19. {
  20. /**
  21. * @return void
  22. */
  23. protected function configure(): void
  24. {
  25. $this
  26. ->setName('logviewer')
  27. ->addOption(
  28. 'file',
  29. 'f',
  30. InputOption::VALUE_OPTIONAL,
  31. 'custom log file location (default = grav.log)'
  32. )
  33. ->addOption(
  34. 'lines',
  35. 'l',
  36. InputOption::VALUE_OPTIONAL,
  37. 'number of lines (default = 10)'
  38. )
  39. ->setDescription('Display the last few entries of Grav log')
  40. ->setHelp('Display the last few entries of Grav log');
  41. }
  42. /**
  43. * @return int
  44. */
  45. protected function serve(): int
  46. {
  47. $input = $this->getInput();
  48. $io = $this->getIO();
  49. $file = $input->getOption('file') ?? 'grav.log';
  50. $lines = $input->getOption('lines') ?? 20;
  51. $verbose = $input->getOption('verbose') ?? false;
  52. $io->title('Log Viewer');
  53. $io->writeln(sprintf('viewing last %s entries in <white>%s</white>', $lines, $file));
  54. $io->newLine();
  55. $viewer = new LogViewer();
  56. $grav = Grav::instance();
  57. $logfile = $grav['locator']->findResource('log://' . $file);
  58. if (!$logfile) {
  59. $io->error('cannot find the log file: logs/' . $file);
  60. return 1;
  61. }
  62. $rows = $viewer->objectTail($logfile, $lines, true);
  63. foreach ($rows as $log) {
  64. $date = $log['date'];
  65. $level_color = LogViewer::levelColor($log['level']);
  66. if ($date instanceof DateTime) {
  67. $output = "<yellow>{$log['date']->format('Y-m-d h:i:s')}</yellow> [<{$level_color}>{$log['level']}</{$level_color}>]";
  68. if ($log['trace'] && $verbose) {
  69. $output .= " <white>{$log['message']}</white>\n";
  70. foreach ((array) $log['trace'] as $index => $tracerow) {
  71. $output .= "<white>{$index}</white>{$tracerow}\n";
  72. }
  73. } else {
  74. $output .= " {$log['message']}";
  75. }
  76. $io->writeln($output);
  77. }
  78. }
  79. return 0;
  80. }
  81. }