robsch
robsch

Reputation: 9718

Yii2: How to log exceptions?

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.

Upvotes: 7

Views: 11143

Answers (2)

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

Upvotes: 2

Pavel Bariev
Pavel Bariev

Reputation: 2626

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.

Upvotes: 6

Related Questions