1. <?php
  2. /**
  3. * Pretty-prints log file contents with basic input validation.
  4. *
  5. * @param string $logFilePath Path to the log file.
  6. * @return void
  7. */
  8. function prettyPrintLog(string $logFilePath): void
  9. {
  10. //Basic input validation
  11. if (!file_exists($logFilePath)) {
  12. echo "Error: Log file not found at '$logFilePath'\n";
  13. return;
  14. }
  15. if (!is_readable($logFilePath)) {
  16. echo "Error: Log file is not readable.\n";
  17. return;
  18. }
  19. $logContent = file_get_contents($logFilePath);
  20. if ($logContent === false) {
  21. echo "Error: Failed to read log file.\n";
  22. return;
  23. }
  24. // Split the log content into lines
  25. $logLines = explode("\n", $logContent);
  26. // Pretty print each log line
  27. foreach ($logLines as $lineNumber => $logLine) {
  28. //Clean up the line by removing leading/trailing whitespace
  29. $logLine = trim($logLine);
  30. if ($logLine !== "") {
  31. echo sprintf("[%03d] %s\n", $lineNumber, $logLine); // Format with line number
  32. }
  33. }
  34. }
  35. //Example Usage (replace with your log file path)
  36. if (isset($argv[1])) {
  37. prettyPrintLog($argv[1]);
  38. } else {
  39. echo "Usage: php pretty_print_log.php <log_file_path>\n";
  40. }
  41. ?>

Add your comment