Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TheFriendlyHacker's avatar

How to parse a Laravel log

What would be the best way to parse out the date, environment, level and message from each log entry in one of Laravel's log files?

I know that there are packages that do this for you, but I'd rather not use them in this case.

0 likes
7 replies
jekinney's avatar

Google.

File_get_contents() returns a files data as a string. Then sort as needed.

mehany's avatar

@Ackirb I just looked at this package and the source code seem to be a good place to get inspired.

I don't believe file_get_content was created for this purpose, you may like file instead - since php4

  // from PHP documentations
  $logFile = file(storage_path().'/logs/laravel-2016-04-24.log');
  $logCollection = [];
  // Loop through an array, show HTML source as HTML source; and line numbers too.
  foreach ($logFile as $line_num => $line) {
     $logCollection[] = array('line'=> $line_num, 'content'=> htmlspecialchars($line));
  }
  dd($logCollection);
3 likes
wiedem's avatar
wiedem
Best Answer
Level 1

@Ackirb if you really want to process log files the easiest way to do so would propably be using fgets in combination with a regular expression (preg_match). You have to keep in mind though that log messages may span over multiple lines.

The Monolog LineFormatter class contains the default format used for log lines, this should help you create your regex.

However, have you considered using a custom log handler / formatter / logger? Log files are not really meant to be parsed. Laravel uses Monlog itself so you could e.g. use a handler to write log entries to a Redis or an Elasticsearch server (or even a mySQL database).

I highly recommend using your own handler especially if you want to build a view for your log entries and make them searchable through some kind of interface.

2 likes

Please or to participate in this conversation.