Debugging and logging are essential for maintaining Yii2 applications, identifying errors, and tracking system behavior. Yii2 provides Yii Debug Toolbar, logging mechanisms, and error handling features to make debugging and monitoring efficient.
This tutorial covers debugging techniques, log configuration, error handling, and best practices for effective troubleshooting in Yii2.
Yii Debug Toolbar is a built-in tool that provides detailed debugging information about the current request, including queries, logs, and request/response details.
The debug toolbar is enabled by default in development mode. If it's missing, ensure debug is enabled in config/web.php:
if (YII_ENV_DEV) {
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
}Accessible at: http://your-app-url/index.php?r=debug
Yii2 uses the Yii::info(), Yii::warning(), and Yii::error() functions for logging. Logs can be stored in files, databases, emails, or syslog.
Yii::info('This is an informational message', 'application');
Yii::warning('This is a warning', 'application');
Yii::error('This is an error message', 'application');Use log levels (info, warning, error) to categorize logs.
Modify config/web.php to customize log storage:
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'logFile' => '@runtime/logs/app.log', // Log file location
],
],
],
],Logs are stored in runtime/logs/app.log by default.
Instead of file logs, store logs in a database:
Run the migration:
php yii migrate --migrationPath=@yii/log/migrations/'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\DbTarget',
'levels' => ['error', 'warning'],
],
],
],
],Logs will be stored in the log table.
To send critical logs via email:
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\EmailTarget',
'levels' => ['error'],
'message' => [
'to' => ['admin@example.com'],
'subject' => 'Application Error Logs',
],
],
],
],
],Sends an email whenever an error occurs.
To display a custom error page, configure errorHandler:
'components' => [
'errorHandler' => [
'errorAction' => 'site/error',
],
],Modify SiteController.php:
public function actionError()
{
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
return $this->render('error', ['exception' => $exception]);
}
}Create views/site/error.php:
<h1>Error <?= $exception->statusCode ?></h1>
<p><?= nl2br(Html::encode($exception->getMessage())) ?></p>Displays user-friendly error pages.
Modify urlManager to catch missing routes:
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],Redirects invalid URLs to the error page.
Yii2 console commands help diagnose issues:
php yii help # List all commands
php yii migrate # Check database migrations
php yii cache/flush # Clear cache
php yii message/config # Configure message translationsUse php yii to interact with your app via CLI.
To log SQL queries, modify db component in config/web.php:
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'enableLogging' => true,
'enableProfiling' => true,
],
],Logs all executed queries for debugging.
The Yii Debug Toolbar shows executed SQL queries and execution time.
Use \Yii::trace() to debug queries:
Yii::trace(User::find()->where(['status' => 1])->createCommand()->getRawSql());Outputs raw SQL query in logs.
Wrap risky code in a try-catch block to prevent fatal crashes:
try {
$user = User::findOne($id);
if (!$user) {
throw new NotFoundHttpException('User not found');
}
} catch (Exception $e) {
Yii::error('Error fetching user: ' . $e->getMessage());
}Prevents application crashes by catching errors.
Define a custom exception for business logic:
class CustomException extends \yii\base\Exception {}
throw new CustomException('This is a custom exception');Helps categorize errors for better debugging.
error, warning, info).Yii2 provides powerful debugging tools, logging mechanisms, and error handling features to help developers track issues effectively. By using Yii Debug Toolbar, query logging, custom error pages, and structured logs, you can quickly identify and resolve performance bottlenecks and application errors.
Sign in to join the discussion and post comments.
Sign in