2

Follow up questions for this solution: https://stackoverflow.com/a/31883204/3548238

  1. If i want to log the request in "onRespond()" event, how can i access to the status code? For example: if request responds with status code 200, i'd want to log "success = 1" and if its something else, then "success = 0"
  2. Can i somehow access the message, if my API throws exception with "throw new RestException(404, "Example not found");" or if auth failed or whatever the cause is.
  3. Can i/how can i make some of the requests so that they wont be logged in any situation? I know i should create some kind of annotation for it, but: how?

For example something like this:

/**
 *
 * @status      200
 *
 * @description Get all logs
 * @url         GET logs
 * @access      protected
 * @class       AccessControl {@requires admin}
 *
 * @log         false
 *
 * @throws RestException
 */
public function list_all_logs() {
...
...
Community
  • 1
  • 1
Kirbo
  • 381
  • 1
  • 12

1 Answers1

1

You should be using onComplete instead of onRespond

Why?

  • onRespond() - fired before sending response
  • onComplete() - fired after sending response

Here is the complete solution that answers all your questions, assuming you are adding @log false comment to the api method you want to exclude

use Luracast\Restler\Restler;
use Luracast\Restler\User;

$r = new Restler();
$r->onComplete(function () use ($r) {
    if (
        !isset($r->apiMethodInfo->metadata['log']) ||
        $r->apiMethodInfo->metadata['log'] == 'true'
    ) {
        $success = $r->responseCode == 200;
        $info = array(
            'success' => $success,
            'message' => $success ? '' : $r->exception->getErrorMessage()
        );
        print_r($info); //your logging function here!
    }
});
$r->addAPIClass('Say');
$r->handle();
Arul Kumaran
  • 983
  • 7
  • 23