Skip to content

Instantly share code, notes, and snippets.

@begriffs
Created January 22, 2012 16:56
Show Gist options
  • Save begriffs/1657662 to your computer and use it in GitHub Desktop.
Save begriffs/1657662 to your computer and use it in GitHub Desktop.
Aspect-Oriented PHP logger
<?php
// This class impersonates other objects and logs what they do.
class WithLogging {
// The parameter customMessage is a function that knows something about
// callee and can give extra interesting information about its state.
function __construct($callee, $customMessage = NULL) {
$this->callee = $callee;
$this->customMessage = $customMessage ?: function($obj) { return ''; };
}
// All method invocations of WithLogging go through here, and are
// forwarded to callee and logged appropriately.
function __call($method, $args) {
$fullName = get_class($this->callee) . "::{$method}";
if(!method_exists($this->callee, $method)) {
$trace = debug_backtrace();
trigger_error("Call to undefined method $fullName() in " .
"{$trace[0]['file']} on line {$trace[0]['line']}",
E_USER_ERROR);
}
echo "$fullName(" . implode(', ', $args) . ")\n\t";
$ret = call_user_func_array(array($this->callee, $method), $args);
echo call_user_func($this->customMessage, $this->callee) . "\n";
return $ret;
}
protected $callee;
protected $customMessage;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment