Yii2: How to log exceptions?

robsch picture robsch · Feb 12, 2015 · Viewed 8.8k times · Source

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.

Answer

Pavel Bariev picture Pavel Bariev · Feb 12, 2015

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.