skip to Main Content

I’m trying to write a Laravel 8.0 task that renames the default log file every week and makes another empty file. I’m using a Debian 10 virtual machine as a testing environment.

Here’s my handle() code:

$now = Carbon::now();
$baseLog = "/laravel.log";
$oldLog = storage_path("logs".$baseLog);
$renamedLog = storage_path("logs"."/log_".$now->day."_"
    .$now->month."_".$now->year.".log");

Storage::move($oldLog, $renamedLog);
Storage::delete($oldLog);
Storage::put(storage_path("logs".$baseLog), "");

The problem is that Laravel
says…

File not found at path: var/www/html/storage/logs/laravel.log

2

Answers


  1. Chosen as BEST ANSWER

    As you correctly pointed out, I called delete on a moved file (my bad) but the error happened before, while trying to locate the laravel.log.

    After adding an exists check, I noticed the storage path returned has an "/app" so I've just created another disk instance in config/filesystems

     'log' => [
                'driver' => 'local',
                'root' => storage_path('logs'),
            ],
    

    and then I could finally resolve my issue like that:

    $baseLog = "/laravel.log";
        if(Storage::disk('log')->exists($baseLog)){
           $now = Carbon::now();
           $renamedLog ="/log_".$now->day."_".$now->month."_".$now->year.".log";
           Storage::disk('log')->move($baseLog, $renamedLog);
           Storage::disk('log')->put($baseLog, "");
        }
    

    Thank you


  2. Add check for file exists and not use delete – because you move file:

    $baseLog = "/laravel.log";
    $oldLog = storage_path("logs".$baseLog);
    if(Storage::exists($oldLog)){
      $now = Carbon::now();
      $renamedLog = storage_path("logs"."/log_".$now->day."_".$now->month."_".$now->year.".log");
      Storage::move($oldLog, $renamedLog);
      Storage::put(storage_path("logs".$baseLog), "");
    }
    

    Or, if this is not for studying, use package for log rotate, e.g. this

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search