Search code examples
phprestler

How to log all requests in PHP Restler 3?


I have created an API with Luracast Restler 3 RC 6 (https://github.com/Luracast/Restler/tree/3.0.0-RC6) and now I want to create a logging into my API so that every request made for the API will be logged. I've tried to search for the answer pretty much everywhere, without luck. So my question is:

How can I create a logging class/function into Restler 3, which gets called everytime when a request is made? Should it be somehow implemented into routing, or what? I need something like:

logging($route, $http_method, $format, $api_key, $parameters);

This function/class should get every possible information of the request being made and insert it into logging table, something like this:

+----+---------------------+------------+----------+----------------+--------+---------------------------+
| id | log_time            | ip_address | api_key  | route          | method | parameters                |
+----+---------------------+------------+----------+----------------+--------+---------------------------+
|  1 | 2015-08-06 14:32:54 |  127.0.0.1 | ASDFasdf | /v1/users/list |    GET | all_given_parameters_here |
+----+---------------------+------------+----------+----------------+--------+---------------------------+

I'm not asking you to create me a function/class for logging, I just need some kind of a guidance on how and where should I do this, or is it even possible?

EDIT: Forgot to mention I need to log Method also, that which method is being used for the given route: GET, POST, PUT, PATCH or DELETE. Maybe also the format being used (JSON or XML).

EDIT: I assume I should extend Luracast\Restler\Routes.php Routes->find() somehow somewhere, but how and where?


Solution

  • You can use the event handler (at call stage) for this. See the following example

    use Luracast\Restler\Restler;
    use Luracast\Restler\User;
    
    $r = new Restler();
    $r->onCall(function () use ($r) {
        // Don't log Luracast Restler Explorer recources calls
        if (!preg_match('/resources/', $r->url)) {
            $info = array(
                'base'    => $r->getBaseUrl(),
                'method'  => $r->requestMethod,
                'url'     => $r->url,
                'route'   => $r->apiMethodInfo->className.'::'.$r->apiMethodInfo->methodName,
                'version' => $r->getRequestedApiVersion(),
                'data'    => $r->getRequestData(),
                'ip'      => User::getIpAddress(),
            );
            print_r($info);
        }
    });
    $r->addAPIClass('Say');
    $r->handle();
    

    Replace print_r with your logging function