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

DivDax's avatar
Level 10

phpunit: How to test write to log file

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

0 likes
4 replies
druc's avatar
druc
Best Answer
Level 1

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.

2 likes
yshang77's avatar

You could use laravel mock

function myFunction()
{
    try {
        doSomething();
    } catch(Exception $e) {
        Log::error('something error', $e);
    }
}

//test

function testMyFunction()
{
    myFunction();

    $e = new Exception();
    Log::shouldReceive('error')->once()
           ->withArgs(array('something error', $e);
}
5 likes
eugenefvdm's avatar

@yshang77 I have a feeling this format is now outdated 3 years later. This answer seems more current, although I couldn't get it working for my use case:

https://laracasts.com/discuss/channels/testing/testing-that-the-log-record-has-been-written

/** @test */
public function it_logs_a_warning_message_if_an_invalid_user_id_is_given()
{
    Log::shouldReceive('warning')
        ->once()
        ->withArgs(function ($message) {
            return strpos($message, 'user id invalid') !== false;
        });
    
    $testSubject->someActionThatRequiresAValidUserId($invalidId);
}
2 likes

Please or to participate in this conversation.