In Debug Log Messages in Yii2, the error log is displayed in JSON format, and the readability is too poor to check and analyze
1. In the Debug log messages in Yii2, the error log is displayed in JSON format, and the readability is too poor to check and analyze. as shown in Figure 1
2. Discover existing implementations as follows
api/config/main.php
return [
'components' => [
'errorHandler' => [
'errorAction' => 'site/error',
'class' => api\exception\ApiErrorHandler::class,
],
]
];
API/Exception/APIErrorHandler.php
<?php
namespace api\exception;
use Yii;
use yii\web\ErrorHandler;
use yii\web\Response;
use yii\web\UnauthorizedHttpException;
class ApiErrorHandler extends ErrorHandler
{
protected function renderException($exception)
{
if (Yii::$app->has('response')) {
$response = Yii::$app->getResponse();
// reset parameters of response to avoid interference with partially created response data
// in case the error occurred while sending the response.
$response->isSent = false;
$response->stream = null;
$response->data = null;
$response->content = null;
} else {
$response = new Response();
}
$response->format === Response::FORMAT_JSON;
$code = 10090;
$message = '系统错误';
if ($exception instanceof UnauthorizedHttpException) {
$message = '登录后才可访问';
$code = 11000;
} else {
Yii::error(['异常捕获', $exception->getMessage(), $exception->getFile(), $exception->getLine()]);
Yii::error($exception->getTrace(), 'application');
}
$response->data = [
'code' => $code,
'message' => $message,
'data' => [
'error_code' => $exception->getCode()
]
];
// $response->headers->add('Access-Control-Allow-Origin', '*');
// $response->headers->add('Access-Control-Allow-Headers', '*');
$response->send();
}
}
3. The error log is output by this line, yii::error($exception->getTrace(),Application), because $exception->getTrace() is an array, and yii defaults to writing it to the log after json_encode(), so you can see json in the debug module Format (arrays are converted to strings).
4. The final adjustment is as follows, the error log is no longer in the json format. as shown in Figure 2
API/Exception/APIErrorHandler.php
<?php
Yii::error($exception->getTraceAsString());
5. However, I found that the error application and the error error are roughly similar, and it is not necessary to record a $exception->getTraceAsString() .
6. Decide to adjust the configuration in the api/web/index.php, and then observe the generated logs again. Check app.log , and find that there is still no difference, and decide to delete yii::error($exception->getTraceAsString()); as shown in Figure 3
defined('YII_DEBUG') or define('YII_DEBUG', false);
defined('YII_ENV') or define('YII_ENV', 'prod');


