phpunit: How to test write to log file

Published 2 months ago by DivDax

i'm really new to phpunit testing and want to test if something was written to the logfile. How you would test this?

Best Answer (As Selected By DivDax)
druc

If you don't really care about what's being written in the log file and only what to check if something was logged you could do this.

/** @test */
public function when_some_action_fails_the_system_will_log_the_errors()
{
    // make sure the laravel log is empty
    file_put_contents(storage_path('logs/laravel.log'), "");

    // execute the action that will write in the log

    //assert that the laravel.log is not empty
    $this->assertTrue(
        !empty(file_get_contents(storage_path('/logs/laravel.log')))
    );
}

Be careful. Errors will be logged when other tests are failing - the above test clears out the log file.

druc
druc
2 months ago (2,450 XP)

If you don't really care about what's being written in the log file and only what to check if something was logged you could do this.

/** @test */
public function when_some_action_fails_the_system_will_log_the_errors()
{
    // make sure the laravel log is empty
    file_put_contents(storage_path('logs/laravel.log'), "");

    // execute the action that will write in the log

    //assert that the laravel.log is not empty
    $this->assertTrue(
        !empty(file_get_contents(storage_path('/logs/laravel.log')))
    );
}

Be careful. Errors will be logged when other tests are failing - the above test clears out the log file.

DivDax

Thank you @druc. :)

Please sign in or create an account to participate in this conversation.