Log Activity in DataBase

In this article i will explain how to customize log activity in database, Imaging you need to save IP user, Url request and user_name in database,But table created by default with Yii only have id,level,category,logtime and message

1: create class file in /protected/extensions/LogDb.php

class LogDb extends CDbLogRoute
{

    protected function createLogTable($db,$tableName)
    {
        $db->createCommand()->createTable($tableName, array(
            'id'=>'pk',
            'level'=>'varchar(128)',
            'category'=>'varchar(128)',
            'logtime'=>'timestamp with time zone', 
            'IP_User'=>'varchar(50)', //For IP 
            'user_name'=>'varchar(50)',
            'request_URL'=>'text',
            'message'=>'text',
        ));
    }
    protected function processLogs($logs)
    {
        $command=$this->getDbConnection()->createCommand();
        $logTime=date('Y-m-d H:i:s'); //Get Current Date

        foreach($logs as $log)
        {
            $command->insert($this->logTableName,array(
                'level'=>$log[1],
                'category'=>$log[2],
                'logtime'=>$logTime,
                'IP_User'=> Yii::app()->request->userHostAddress, //Get Ip 
                'user_name'=>Yii::app()->user->name , //Get name
                'request_URL'=>Yii::app()->request->url, // Get Url
                'message'=>$log[0]
            ));
        }
    }

}

and in config/main.php:

'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'error',
                    'categories'=>'system.*',
                ),
                array(
                    'class'=>'ext.LogDb',
                    'autoCreateLogTable'=>true,
                    'connectionID'=>'db',
                    'enabled'=>true,
                    'levels'=>'error',//You can replace trace,info,warning,error
                ),

                // uncomment the following to show log messages on web pages

                /*
                array(
                    'class'=>'CWebLogRoute',
                ),
                */
            ),
        ),
4 0
17 followers
Viewed: 22 094 times
Version: 1.1
Category: Tutorials
Written by: mahdi1986
Last updated by: mahdi1986
Created on: Jun 29, 2013
Last updated: 4 years ago
Update Article

Revisions

View all history

Related Articles