Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 926
robsch Avatar asked Feb 12 '15 12:02

robsch


People also ask

How to create log in yii2?

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, ], ], ], ], ];

How to display error in yii2?

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', ], ] ];

How do I view Yii logs?

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);


2 Answers

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.

like image 62
Pavel Bariev Avatar answered Nov 15 '22 07:11

Pavel Bariev


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

like image 25
Qudratxo'ja Musayev Avatar answered Nov 15 '22 08:11

Qudratxo'ja Musayev