LogViewerCommand.php 2.6 KB

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