Search code examples
phprestler

Using Restler3, how to log requests/responses


Is there currently any means of capturing an incoming request and response, and logging that? I see that there are 'preCall' and 'postCall' methods, however, some of my API methods are not strictly named by HTTP verbs.

For example, in my 'Players' class, I have 'get' method which returns one player for a given player_id, and 'getPlayers' which returns all players.


Solution

  • There sure is!

    Here is some code that I pieced together from some other SO questions:

    $r->onComplete(function () use ($r) {
    // Don't log Luracast Restler Explorer recources calls
    if ( ! preg_match('/resources/', $r->url)) {
        $success = $r->responseCode == 200;        
        $request = $r->getRequestData();
        $info = array(
            'base'              => $r->getBaseUrl(),
            'method'            => $r->requestMethod,
            'url'               => $r->url,
            'api_key'           => NULL,
            'route'             => $r->apiMethodInfo->className.'::'.$r->apiMethodInfo->methodName,
            'data'              => $request['request_data'],
            'ip'                => User::getIpAddress(),
            'referer'           => (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER']: ''),
            'http_status_code'  => $r->responseCode,
            'response'          => $success ? '' : $r->exception->getErrorMessage()
            );
            print_r($info); // replace with your logging function here
    
    }
    

    });