Available log targets:
| Target | Destination |
|---|---|
yii\log\DbTarget |
A database table. |
yii\log\EmailTarget |
Email, using an address configured in advance. |
yii\log\FileTarget |
A file. |
yii\log\SyslogTarget |
syslog, via the syslog() function. |
Configuration
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
Next to levels you can add the variables to dump with every message:
'logVars' => ['_GET', '_POST'],
Or simply (my favourite option):
'logVars' => [],
This strips noise like $_SERVER and $_COOKIE from the log entries.
Writing to the log
Yii::info('Displaying the whole list of cars.');
Flushing immediately
Because of the flushing and exporting level settings, calling Yii::debug() or any other logging method does not write the message to the target immediately. This can be a problem for long-running console applications. To make each message appear right away, set both flushInterval and exportInterval to 1:
return [
'bootstrap' => ['log'],
'components' => [
'log' => [
'flushInterval' => 1,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'exportInterval' => 1,
],
],
],
],
];
Stack traces
You can log the call path where the error happened:
'log' => [
'traceLevel' => 10,
// ...
The output is primitive but sometimes useful:
2019-09-04 15:21:07 [-][-][-][error][application] Process stopped: Hello error!
in /var/www/app/models/Spreadsheet.php:313
in /var/www/app/models/Spreadsheet.php:123
in /var/www/app/commands/AppController.php:21
Sending logs by email
'components' => [
'log' => [
'flushInterval' => 1,
'targets' => [
[
'class' => 'yii\log\EmailTarget',
'exportInterval' => 1,
'mailer' => 'mailer',
'levels' => ['error'],
'message' => [
'from' => 'robot@example.com',
'to' => 'developer@example.com',
'subject' => 'Error log message [App]',
],
],
],
],
],
VarDumper helper
yii\helpers\VarDumper is a safer alternative to var_dump() for objects with recursive references.
Print a variable:
VarDumper::dump($var);
Return the dump as a string:
VarDumper::dumpAsString($var);
Andrew Dorokhov