customlogger

This is a custom logging class extended from CLogRoute to do dbLogging, filelLogging and emailLogging
3 followers
<?php
 
/**
 * CustomLogger class file.
 *
 * @author Winu Sebastian
 */
 
 
class CustomLogger extends CLogRoute {
 
    /**
     * @var integer maximum log file size
     */
    private $_maxFileSize = 1024; // in KB
    /**
     * @var integer number of log files used for rotation
     */
    private $_maxLogFiles = 5;
 
    /**
     * @var string directory storing log files
     */
    private $_logPath;
 
    /**
     * @var string log file name
     */
    private $_logFile = 'application.log';
 
    /**
     * @var boolean Whether to rotate primary log by copy and truncate
     * which is more compatible with log tailers. Defaults to false.
     * @since 1.1.14
     */
    public $rotateByCopy = false;
    /*
     * array used to get db details from config for db logging
     */
    public $DbLog = array();
    public $connectionID;
    private $_db;
    public $tableName;
 
    /**
     * Initializes the route.
     * This method is invoked after the route is created by the route manager.
     */
    public function init() {
        parent::init();
 
        if ($this->getLogPath() === null) {
            $this->setLogPath(Yii::app()->getRuntimePath());
        }
        if ($this->DbLog['status']) {
 
            $db = $this->getDbConnection();
            $table = $this->getTable();
            $this->createLogTable($db, $table);
        }
    }
 
    /**
     * @return CDbConnection the DB connection instance
     */
    public function getDbConnection() {
        $con = $this->DbLog['db']['connectionString'];
        $username = $this->DbLog['db']['username'];
        $password = $this->DbLog['db']['password'];
        $this->connectionID = new CDbConnection($con, $username, $password);
        $this->connectionID->active = true;
        return $this->_db = $this->connectionID;
    }
 
    /**
     * Creates the DB table for storing log messages.
     * @param CDbConnection $db the database connection
     * @param string $tableName the name of the table to be created
     */
    protected function createLogTable($db, $tableName) {
        $command = $this->_db->createCommand("CREATE TABLE IF NOT EXISTS {$tableName}(
                                `id` int(11) NOT NULL AUTO_INCREMENT,
                                `level` varchar(128) DEFAULT NULL,
                                `category` text NOT NULL,
                                `logtime` varchar(100) DEFAULT NULL,
                                `message` text,
                                PRIMARY KEY (`id`)
                              );");
        $command->execute();
    }
    /*
     * Creates table name
     */
    public function getTable() {
 
        $Year = date('Y');
        $Month = date('m');
        $Day = date('d');
 
        if (isset(Yii::app()->session['user_id'])) {
            $User = Yii::app()->session['user_id'];
        } else {
            $User = 'Admin';
        }
        if (isset(Yii::app()->session['profile_id'])) {
            $Profile = Yii::app()->session['profile_id'];
        } else {
            $Profile = '';
        }
 
        $this->tableName = $Year . '_' . $Month .'_'.$Day.'_' . $User . '_' . $Profile;
        return $this->tableName;
    }
 
    /**
     * Stores log messages into database.
     * @param array $logs list of log messages
     */
    public function processDbLogs($logs) {
 
        $command = $this->getDbConnection();
        foreach ($logs as $log){
            if($log[1] == 'info'){
        $sql = "insert into " . $this->tableName . "(level,category,logtime,message) values (:level,:category,:logtime, :message);";
        $parameters = array(":level" => $log[1],':category'=>  json_encode($log[2]), ':logtime' => date('Y-m-d H:i:s', $log[3]), ':message' => $log[0]);
        $command->createCommand($sql)->execute($parameters);
            }
        }
    }
 
    /**
     * @return string directory storing log files. Defaults to application runtime path.
     */
    public function getLogPath() {
        return $this->_logPath;
    }
 
    /**
     * @param string $value directory for storing log files.
     * @throws CException if the path is invalid
     */
    public function setLogPath($value) {
        $this->_logPath = realpath($value);
        if ($this->_logPath === false || !is_dir($this->_logPath) || !is_writable($this->_logPath))
            throw new CException(Yii::t('yii', 'AdlugeLogger.logPath "{path}" does not point to a valid directory. Make sure the directory exists and is writable by the Web server process.', array('{path}' => $value)));
    }
 
    /**
     * @return string log file name. Defaults to 'application.log'.
     */
    public function getLogFile() {
        return $this->_logFile;
    }
 
    /**
     * @param string $value log file name
     */
    public function setLogFile($value) {
        $this->_logFile = $value;
    }
 
    /**
     * @return integer maximum log file size in kilo-bytes (KB). Defaults to 1024 (1MB).
     */
    public function getMaxFileSize() {
        return $this->_maxFileSize;
    }
 
    /**
     * @param integer $value maximum log file size in kilo-bytes (KB).
     */
    public function setMaxFileSize($value) {
        if (($this->_maxFileSize = (int) $value) < 1)
            $this->_maxFileSize = 1;
    }
 
    /**
     * @return integer number of files used for rotation. Defaults to 5.
     */
    public function getMaxLogFiles() {
        return $this->_maxLogFiles;
    }
 
    /**
     * @param integer $value number of files used for rotation.
     */
    public function setMaxLogFiles($value) {
        if (($this->_maxLogFiles = (int) $value) < 1)
            $this->_maxLogFiles = 1;
    }
 
    /**
     * Saves log messages in files.
     * @param array $logs list of log messages
     */
    public function processLogs($logs) {
 
        if ($this->DbLog['status']) {
        $this->processDbLogs($logs);
        }
        $data = array();
 
        if (isset(Yii::app()->session['user_id'])) {
            $userName = 'winu';
            $User = Yii::app()->session['user_id'] . '_' . $userName;
        } else {
            $User = 'Unknown';
        }
        if (isset(Yii::app()->session['profile_id'])) {
            $Profile = Yii::app()->session['profile_id'];
        } else {
            $Profile = 'General';
        }
 
        if (is_array($logs[0][2])) {
            foreach ($logs[0][2] as $log) {
                array_push($data, $log);
            }
        }
        $count = count($data);
 
        if ($count == 3) {
            $Directory = $data[2];
            $this->setLogFile($data[1]);
        } else {
            $Directory = 'Logs/' . date('Y') . '/' . date('M') . '/' . date('j') . '/' . $User . '/' . $Profile . '/Error_Exception/';
            $this->setLogFile('Logs_' . $logs[0][1] . '_' . $logs[0][2] . '.log');
        }
 
        if (!is_dir($Directory)) {
            mkdir($Directory, 0777, true);
            $this->setLogPath($Directory);
        } else {
            $this->setLogPath($Directory);
        }
 
        $text = '';
        if ($count == 3) {
            foreach ($logs as $log)
                $text.=$this->formatLogMessage($log[0], $log[1], $log[2][0], $log[3]);
        } else {
            foreach ($logs as $log)
                $text.=$this->formatLogMessage($log[0], $log[1], $log[2], $log[3]);
        }
 
        $text.=PHP_EOL . '[############]' . PHP_EOL;
        $logFile = $this->getLogPath() . DIRECTORY_SEPARATOR . $this->getLogFile();
 
        $fp = @fopen($logFile, 'a');
        @flock($fp, LOCK_EX);
        if (@filesize($logFile) > $this->getMaxFileSize() * 1024) {
            $this->rotateFiles();
            @flock($fp, LOCK_UN);
            @fclose($fp);
            @file_put_contents($logFile, $text, FILE_APPEND | LOCK_EX);
        } else {
            @fwrite($fp, $text);
            @flock($fp, LOCK_UN);
            @fclose($fp);
        }
    }
 
    /**
     * Rotates log files.
     */
    protected function rotateFiles() {
        $file = $this->getLogPath() . DIRECTORY_SEPARATOR . $this->getLogFile();
        $max = $this->getMaxLogFiles();
        for ($i = $max; $i > 0; --$i) {
            $rotateFile = $file . '.' . $i;
            if (is_file($rotateFile)) {
                // suppress errors because it's possible multiple processes enter into this section
                if ($i === $max)
                    @unlink($rotateFile);
                else
                    @rename($rotateFile, $file . '.' . ($i + 1));
            }
        }
        if (is_file($file)) {
            // suppress errors because it's possible multiple processes enter into this section
            if ($this->rotateByCopy) {
                @copy($file, $file . '.1');
                if ($fp = @fopen($file, 'a')) {
                    @ftruncate($fp, 0);
                    @fclose($fp);
                }
            }
            else
                @rename($file, $file . '.1');
        }
    }
 
}

in main.php, add below code

'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                                    'class'=>'CustomLogger',
                                    'levels'=>'error, warning, info, test, sample',
                                    'logFile' => 'Log_' . date('Y-m-d') . '.log',
                                    'DbLog' =>array('status' => true,
                                        'db'=>array(
                                                'connectionString' => 'mysql:host=localhost;dbname=custom',
                                                'emulatePrepare' => true,
                                                'username' => 'root',
                                                'password' => '',
                                                'charset' => 'utf8',
                                                ),
                                                    ),
                                    ),
 
                // uncomment the following to show log messages on web pages
                /*
                array(
                    'class'=>'CWebLogRoute',
                ),
                */
            ),
        ),
/*
---
---
*/
      'params'=>array(
                'logMail' => array('status' => TRUE,
                        'to'=>'vinu@gmail.com',
                        'from'=>'sample@gamil.com',
                        'cc'=>'',
                        'bcc'=>'')
    ),

create a component as below

class Logger extends CustomLogger{
    /*
     * log static function
     * 
     * It is used to create log file,log path
     * Reads configuration and works based on log level
     * @param log level and log message
     */
 
        public static function log($level, $logData) {
 
        $Folder = 'Logs';
        $Year = date('Y');
        $Month = date('M');
        $Day = date('j');
 
        if(isset(Yii::app()->session['user_id'])){
            $userName = 'winu';
            $User = Yii::app()->session['user_id'].'_'.$userName;
        } else {
            $User = 'Unknown';
        }
 
        if (isset(Yii::app()->session['profile_id'])) {
            $Profile = Yii::app()->session['profile_id'];
        } else {
            $Profile = 'General';
        }
        $Message = PHP_EOL . $logData . PHP_EOL;
 
        $Directory = $Folder . '/' . $Year . '/' . $Month . '/' . $Day . '/' . $User . '/' . $Profile . '/';
 
        $logFile = 'Log_' . $level . '.log';
 
        /*
         * Reads configuration from config/main.php
         */
        $config = Yii::app()->params['logMail'];
 
        if (isset($config)) {
            if ($config['status'] == TRUE) {
 
                $to = isset($config['to']) ? $config['to'] : '';
                $from = isset($config['from']) ? $config['from'] : '';
                $cc = isset($config['cc']) ? $config['cc'] : '';
                $bcc = isset($config['bcc']) ? $config['bcc'] : '';
 
                // subject
                $subject = $level . ':' . $userName;
 
                // body
                $body = '
                        <html>
                        <head>
                          <title>Log:Mail</title>
                        </head>
                        <body>
                          <p>' . $logData . '</p>
                        </body>
                        </html>
                        ';
 
                // To send HTML mail, the Content-type header must be set
                $headers = 'MIME-Version: 1.0' . "\r\n";
                $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
 
                // Additional headers
                $headers .= 'To: Admin <' . $to . '>' . "\r\n";
                $headers .= 'From: <' . $from . '>' . "\r\n";
                $headers .= 'Cc: ' . $cc . "\r\n";
                $headers .= 'Bcc: ' . $bcc . "\r\n";
 
                // Mail it
                if (isset($to)) {
                    mail($to, $subject, $body, $headers);
                }
            }
        }
        /*
         * Set category eg:Log.user's name.info.IP
         */
        $category = 'Log.' . $userName . '.' . $level.'.IP=>'.$_SERVER['REMOTE_ADDR'];
 
        $log = array($category,$logFile,$Directory);
 
        Yii::log($Message, $level,$log);
    }
 
}

Use below code to add logs

Logger::log('info','hi all');

Be the first person to leave a comment

Please to leave your comment.

Create extension
Downloads
No downloadable files yet
  • Yii Version:
  • License: New BSD License
  • Developed by: winu
  • Category: Logging
  • Votes: +3
  • Downloaded: 0 times
  • Created on: Mar 31, 2014
  • Last updated: never
  • Tags: logging