Debugging & Logging in Yii2

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.


1. Yii Debug Toolbar

Yii Debug Toolbar is a built-in tool that provides detailed debugging information about the current request, including queries, logs, and request/response details.

1.1 Enabling the Debug Toolbar

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

1.2 Features of Yii Debug Toolbar

  • Database queries (execution time, slow queries)
  • Logs & profiling
  • Request & response headers
  • Session & cookies
  • Performance monitoring

2. Logging in Yii2

Yii2 uses the Yii::info(), Yii::warning(), and Yii::error() functions for logging. Logs can be stored in files, databases, emails, or syslog.

2.1 Writing Logs

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.

2.2 Configuring Log Targets

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.

2.3 Storing Logs in a Database

Instead of file logs, store logs in a database:

Step 1: Create the Log Table

Run the migration:

php yii migrate --migrationPath=@yii/log/migrations/

Step 2: Configure Database Logging

'components' => [
    'log' => [
        'targets' => [
            [
                'class' => 'yii\log\DbTarget',
                'levels' => ['error', 'warning'],
            ],
        ],
    ],
],

Logs will be stored in the log table.

2.4 Sending Logs via Email

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.


3. Error Handling in Yii2

3.1 Handling Errors with Custom Pages

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.

3.2 Handling 404 Errors

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.


4. Debugging with Yii2 Console Commands

4.1 Using Yii2 Console for Debugging

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 translations

Use php yii to interact with your app via CLI.


5. Debugging Database Queries

5.1 Enabling Query Logging

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.

5.2 Viewing Queries in Debug Toolbar

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.


6. Handling Exceptions in Yii2

6.1 Using Try-Catch for Error Handling

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.

6.2 Throwing Custom Exceptions

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.


7. Yii2 Logging Best Practices

  • Use different log levels (error, warning, info).
  • Enable query logging in development but disable in production.
  • Store critical logs in a database or email alerts.
  • Use debug toolbar for analyzing slow queries.
  • Implement custom error pages for better user experience.

Summary

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.