@@ -295,7 +295,7 @@ following keys:
295295 used. See ``syslog `` documentation for more options
296296
297297Creating Log Engines
298- =====================
298+ ====================
299299
300300Log engines can be part of your application, or part of
301301plugins. If for example you had a database logger called
@@ -347,7 +347,7 @@ interface as it only requires you to implement the ``log()`` method.
347347.. _logging-formatters :
348348
349349Logging Formatters
350- ------------------
350+ ==================
351351
352352Logging formatters allow you to control how log messages are formatted
353353independent of the storage engine. Each core provided logging engine comes with
@@ -378,6 +378,55 @@ To implement your own logging formatter you need to extend
378378method you need to implement is ``format($level, $message, $context) `` which is
379379responsible for formatting log messages.
380380
381+ .. _log-testing :
382+
383+ Testing Logs
384+ ============
385+
386+ To test logging, add ``Cake\TestSuite\LogTestTrait `` to your test case. The
387+ ``LogTestTrait `` uses PHPUnit hooks to attach log engines that intercept the log
388+ messages your application is making. Once you have captured logs you can perform
389+ assertions on log messages your application is emitting. For example::
390+
391+ namespace App\Test\TestCase\Controller;
392+
393+ use Cake\TestSuite\LogTestTrait;
394+ use Cake\TestSuite\TestCase;
395+
396+ class UsersControllerTest extends TestCase
397+ {
398+ use LogTestTrait;
399+
400+ public function setUp(): void
401+ {
402+ parent::setUp();
403+ $this->setupLog([
404+ 'error' => ['scopes' => ['app.security']]
405+ ]);
406+ }
407+
408+ public function testResetPassword()
409+ {
410+ $this->post('/users/resetpassword', ['email' => 'bob@example.com']);
411+ $this->assertLogMessageContains('info', 'bob@example.com reset password', 'app.security');
412+ }
413+ }
414+
415+ You use ``setupLog() `` to define the log messages you wish to capture and
416+ perform assertions on. After logs have been emitted you can make assertions on
417+ the contents of logs, or the absence of them:
418+
419+ * ``assertLogMessage(string $level, string $expectedMessage, ?string $scope
420+ = null, string $failMsg = '') `` Assert that a log message was found.
421+ * ``assertLogMessageContains(string $level, string $expectedMessage, ?string
422+ $scope = null, string $failMsg = '') `` Assert that a log message contains the
423+ substring.
424+ * ``assertLogAbsent(string $level, ?string $failMsg = '') `` Assert that no log
425+ messages of the given level were captured.
426+
427+ The ``LogTestTrait `` will automatically clean up any loggers that were
428+ configured.
429+
381430Log API
382431=======
383432
0 commit comments