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

phpMick's avatar
Level 15

Testing that the log record has been written.

Hi,

How can I test that a record has been written to my log file?

I am just using the standard Laravel logging?

Cheers,

Mick

0 likes
7 replies
ChristophHarms's avatar

You do not have to test that. The Laravel framework uses Monolog. The tests that ensure Monolog is used correctly are already part of the Framework. The tests that ensure Monolog works as expected are naturally part of the Monolog repository

All of this is framework functionality that you should not have to test (again). If you really need to do so for some reason, I guess you would just

  1. Trigger a log message to be written
  2. Inspect the log file (for example with file_get_contents()) and see if everything is as you would expect.
1 like
ohffs's avatar

There is a fake logging package that might be of help - at least you will know the calls to write the log have happened :-)

phpMick's avatar
Level 15

Yes @ohffs I guess that is what I want (test that the calls have happend). I have been tasked with retrofitting logging to an application and I always try and start a task with failing tests and then fix them.

ChristophHarms's avatar
Level 18

I guess I misunderstood your question then. ¯_(ツ)_/¯

If you are using Laravel's Log facade to write log messages in your app, you can take advantage of the fact that you can easily mock laravel facades in your tests. So in your tests, you could do something like

/** @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);
}
7 likes
phpMick's avatar
Level 15

Or, it was a poorly written question :-)

That's working now, thanks. I had this, why didn't it work?

  Log::shouldReceive('info')
        ->once()
        ->with('User created: '.$user->id);

Cheers,

Mick

la_sebastian's avatar

@phpMick For anyone coming around and wondering.

This is probably because the context of the log doesn't match []

ChristophHarms's avatar

Only thing I can think of is that the strings did not match exactly. Maybe there is some prefixing being done or something like that? Something that causes the Log::info() method to not be triggered with the exact string 'User created: ' . $user->id, but with something slightly different. Maybe with a lower case 'user' or some whitespace added.

In any case, using withArgs() combined with a closure lets you inspect the args a little more sophisticated. You could even do a preg_match() in there, or really anything you need.

Please or to participate in this conversation.