- Yii2 Framework
-
Introduction & Setup
- Introduction to Yii2 Framework
- Installing Yii2 (Basic & Advanced Templates)
- Understanding Yii2 Directory Structure
- Yii2 Configuration Basics
- Routing & Pretty URLs in Yii2
-
Yii2 Core Concepts
- Yii2 Application Bootstrapping & Lifecycle
- Understanding Yii2 Request & Response Handling
- Working with Yii2 Components & Helpers
- Yii2 Widgets & Using Built-in Widgets
- Yii2 Helpers & Utility Classes
-
Models & Database Operations
- Yii2 Models, Active Record & Database Connections
- CRUD Operations in Yii2
- Yii2 Query Builder & DAO (Direct SQL Queries)
- Handling Relationships in Yii2 Active Record
- Yii2 Migrations & Seeding
-
Views, Layouts & Themes
- Yii2 Views & Layouts
- Yii2 Asset Bundles & Asset Management
- Integrating Bootstrap in Yii2
- Yii2 Theme Integration
- Yii2 Custom Widgets & Reusable Components
-
Forms, Validation & Data Presentation
- Yii2 Forms & Validation
- Using Yii2 GridView & ListView Widgets
- Yii2 Pagination & Sorting
- Yii2 File Uploads
-
Security & User Management
- User Authentication in Yii2
- Role-Based Access Control (RBAC) in Yii2
- Yii2 Security Features
-
Console Commands & Advanced Features
- Yii2 Console Commands
- Yii2 Events & Behaviors
- Yii2 RESTful API Development
- Consuming Third-Party APIs in Yii2
- Yii2 Background Jobs & Queue System
-
Performance Optimization & Caching
- Yii2 Caching Techniques
- Yii2 Performance Optimization
- Debugging & Logging in Yii2
-
Deployment & Best Practices
- Deploying Yii2 Applications
- Yii2 Best Practices & Large-Scale Application Structure
- Yii2 Multilingual & Localization Support
- Yii2 Module Development
- Integrating Yii2 with Frontend Frameworks (Angular/Vue/React)
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.
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- 5 Ways Use Jupyter Notebook Online Free of Cost
- AI in Cybersecurity: The Future of Digital Protection
- Avoiding the Beginner’s Trap: Key Python Fundamentals You Shouldn't Skip
- Top 10 Knowledge for Machine Learning & Data Science Students
- Datasets for Speech Recognition Analysis
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Career Guide: Natural Language Processing (NLP)
- Generative AI - The Future of Artificial Intelligence
- Deep Learning (DL): The Core of Modern AI
- What is YII? and How to Install it?
- The Ultimate Guide to Data Science: Everything You Need to Know
- Datasets for Natural Language Processing
- Quantum AI – The Future of AI Powered by Quantum Computing
- Python Challenging Programming Exercises Part 3
- The Ultimate Guide to Machine Learning (ML) for Beginners
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset