archive “2010/10”

how to log methods call in php ?

by Hamid Reza Fahimi Madjd @ Oct 6, 2010

as you know there are a lot of logging api that you can use theme to follow users activity, errors and etc. but i needed a logging api that log methods call and their passed variable through them.

so i wrote a snip code using debug_backtrace function and ReflectionMethod class to do that, i made 2 tables named activity_log to save called method information and activity_log_param to save parameteres name and its (serialized) value:

class Log {
  protected function log($result, $message = null) {
    $activitySql = 'insert into activity_log(caller, class, method, method_type, result, message, ip, agent) '.
        'values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';

    $pure = next(debug_backtrace(false));
    // create a mysql query object and run the query using bind parameters and return generated autoincrement id
    $newOid = QueryBuilder::create($activitySql)->write(array(
        $pure['file'],
        $pure['class'],
        $pure['function'],
        $pure['type'],
        $result,
        $message,
        getIp(),
        getUserAgent()
      ),true);

    $paramsSql = 'insert into activity_log_param(fk_activity_log_oid, pname, pvalue, serialized) values ';

    $reflectionMethod = new ReflectionMethod($pure['class'] . '::' . $pure['function']);
    $pNames = $reflectionMethod->getParameters();
    $pValues = $pure['args'];
    $tmp = '';

    foreach($pNames as $idx=>$obj) {
      $pValue = null; $serialized = 'no';
      if(!isset($pValues[$idx])) {
        $pValue = null;
      }
      else {
        if(is_object($pValues[$idx])) {
          $pValue = serialize($pValues[$idx]);
          $serialized = 'yes';
        }
        elseif(is_array($pValues[$idx])) {
          $pValue = serialize($pValues[$idx]);
          $serialized = 'yes';
        }
        else {
          $pValue = $pValues[$idx];
        }
      }
      $tmp .= '(' . $newOid . ', '' . $obj->name . '', '' . $pValue . '', '' . $serialized . ''), ';
    }
    if(!empty($tmp)) {
      $paramsSql .= substr($tmp, 0, -2) . ';';
      return QueryBuilder::create($paramsSql)->write();
    }

  }
}

because debug_backtrace() function doesn't return parametere name, i used ReflectionMethod class to get parameters name.

how to use it? inherit your class from Log class and call log() method to log called method information:

CLass MyClass extends Log {
  public function foo($oid, array $sampleArray, Object $sampleObject) {
    parent::log(true, 'done');
  }
}

 

php comments no comment

last tweet

Developed withDeveloped with
Clicky Web Analytics