1. Yii have its own method to save error logs in DB, follow the steps below in config/main.php Make new db connection (Separate db to save logs)
'log_db'=>array( 'class'=>'CDbConnection', 'connectionString' => 'mysql:host=localhost;dbname=db_name', 'emulatePrepare' => true, 'username' => 'root', 'password' => '', 'charset' => 'utf8', ),2. We can use yii default class to save logs in db "CDbLogRoute"
'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( /**/array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), // uncomment the following to show log messages on web pages array( 'class'=>'CWebLogRoute', ), array( 'class'=>'CDbLogRoute', 'connectionID'=>'log_db', 'logTableName'=>'yii_logs', //log table name //'categories'=>'error, warning', 'levels'=>'error, warning', //'autoCreateLogTable'=>true, ), ), ),3. Yii default table structure to save logs. (It will created automatically if 'autoCreateLogTable'=>true) )
CREATE TABLE IF NOT EXISTS `yii_logs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `level` varchar(128) DEFAULT NULL, `category` varchar(128) DEFAULT NULL, `logtime` int(11) DEFAULT NULL, `message` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;Table snapshot with real data
4. You can save custom fields in Yiilog For this you can make your own class and extend to CDbLogRoute (save in protected\components folder) Like this
createCommand()->createTable($tableName, array( 'id'=>'pk', 'level'=>'varchar(128)', 'category'=>'varchar(128)', 'logtime'=>'integer', 'message'=>'text', 'users_id'=>'int(11)', 'ip'=>'varchar(50)', 'error_code_id'=>'INT(11)', 'output_variable'=>'varchar(225)', 'exception_id'=>'varchar(45)', 'exception_category'=>'ENUM("CApplication", "CDbException", "CHttpException", "BException")', 'updated_date'=>'timestamp', 'created_date'=>'timestamp', )); } protected function processLogs($logs) { $command=$this->getDbConnection()->createCommand(); foreach($logs as $log) { $clog = explode("::", $log[0]); $elog=CJSON::decode($clog[0]); $command->insert($this->logTableName,array( 'level'=>$log[1], 'category'=>$log[2], 'logtime'=>(int)$log[3], 'message'=>$log[0], 'users_id'=>Yii::app()->user->getId(), 'ip'=>Core::getIP(), 'error_code_id'=>$elog['error_code_id'], 'exception_id'=>$elog['exception_id'], 'exception_category'=>$elog['exception_category'], 'output_variable'=>$elog['output_variable'], )); } }and also some change in main .php
'class'=>'application.components.ELog', 'connectionID'=>'log_db', //'logTableName'=>'yii_logs', //'categories'=>'error, warning', //'levels'=>'error, warning', 'levels'=>'elog', 'autoCreateLogTable'=>true, )In controller you can call it like this
Yii::log(CJSON::encode(array('exception_id'=>00001','error_code_id'=>'1','output_variable'=>'user_id','exception_category'=>'BException'))."::", 'elog');