Search code examples
laravelflysystem

How do I monitor file system access in Laravel?


I'm trying to find a way to monitor basic information regarding the access of files on my applications filesystem. The files are stored using the public driver, and are available publicly through the appropriate symlink. I want to add a record to a databased whenever a file is accessed. Is there a way to accomplish this without creating a separate controller? Maybe a filesystem middleware type mechanism?


Solution

  • First, static files don't get handled by your PHP application (in this case Laravel), those are handled by your web server (Nginx, Apache, etc).
    The usual configuration will only route the request to PHP if is a PHP request and will just serve the file if is a static file.

    You could tell the web server to route all static files through a specific URL of your application and then in your controller serve that file and save the statistics, but I advice you against this, because static files are very efficient served by the web server and you would add a lot of work that affects the performance if you process them through a PHP application.

    A solution

    You could create a Laravel console command that gets call with each new line of the log file and use maybe SupervisorD to make sure the command is always called.

    So, you could have something like this to call your command:

    tail -F -n 1 /path/to/access.log | /usr/bin/php /path/to/application/artisan register:log
    

    Where -F will handle the log rotation, -n 1 will use the first last line (or maybe you could try with -n 0) to make sure you don't consider old lines if for some reason the process gets restarted and register:log can be signature of your console command in Laravel.

    That way, each new line in the access log will call your command with the log line as input.