What should happen if I log an exception? Example:
Yii::error(new Exception('test'));
Currently with my basic application template nothing happens. Nothing gets logged (further error() calls don't log either). Is this correct? Configuration is:
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
I have had expected that exceptions get logged appropiately. How should I log exceptions, esp. if I want to see the trace?
Update:
See Issue on GitHub. With Yii 2.0.6 it is possible to log exceptions.
This might be useful if you catch an exception and throw another. Then you can log the original problem. However, if you throw an exception that is based on a Yii exception you can often (or always?) attach the original exception as $previous
. Such an exception will be logged with the previous one automatically if it does not get catched anywhere.
To make each log message appear immediately in the log targets, you should set both flushInterval and exportInterval to be 1, as shown below: return [ 'bootstrap' => ['log'], 'components' => [ 'log' => [ 'flushInterval' => 1, 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'exportInterval' => 1, ], ], ], ], ];
Using Error Actions A better way of customizing the error display is to use dedicated error actions. To do so, first configure the errorAction property of the errorHandler component like the following: return [ 'components' => [ 'errorHandler' => [ 'errorAction' => 'site/error', ], ] ];
Message Logging Messages can be logged by calling either Yii::log or Yii::trace. The difference between these two methods is that the latter logs a message only when the application is in debug mode. Yii::log($message, $level, $category); Yii::trace($message, $category);
I believe, your config is correct.
But you don't need to cover your exception by Yii::error()
. There are two basic ways to log error:
1) Just throw any exception:
throw new \Exception("My error message #1");
2) Use Yii::error()
Yii::error("My error message #2");
The difference is that you will quietly put this second message into log without stopping your application.
To log exception fully after catching it, you can write this in your catch block
Yii::$app->errorHandler->logException($e);
You can read about error handling in yii2 here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With