【问题标题】:Log All API request and response + Slim framework记录所有 API 请求和响应 + Slim 框架
【发布时间】:2019-10-04 14:01:07
【问题描述】:

我想记录 API 的每个请求和响应。

$app->hook('slim.after.router', function () use ($app) { 
    $request = $app->request; 
    $response = $app->response;
    echo "<pre>";print_r($response);die;

});

在这里我得到了正确的请求,但是当我尝试打印出响应时,我得到了

Slim\Http\Response Object
(
    [status:protected] => 200
    [headers] => Slim\Http\Headers Object
        (
            [data:protected] => Array
                (
                    [Content-Type] => application/json
                )

        )

    [cookies] => Slim\Http\Cookies Object
        (
            [defaults:protected] => Array
                (
                    [value] => 
                    [domain] => 
                    [path] => 
                    [expires] => 
                    [secure] => 
                    [httponly] => 
                )

            [data:protected] => Array
                (
                )

        )

    [body:protected] => 
    [length:protected] => 0
)

我能够在 API 响应中呈现正确的响应,但不能像在日志中那样。

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: php api slim


    【解决方案1】:

    使用slim.after 代替slim.after.router 已解决问题。

    documentation

    slim.after.router :- 这个钩子在路由器被调用后被调用 发送,在响应发送到客户端之前,之后 输出缓冲关闭。这个钩子在运行期间被调用一次 缩短应用程序生命周期。

    slim.after :- 在关闭输出缓冲和向客户端发送响应后调用此挂钩。这个钩子是 在 Slim 应用程序生命周期中调用一次。

    $app->hook('slim.after', function () use ($app) { 
        $request = $app->request; 
        $response = $app->response;
        echo "<pre>";print_r($request);die;
    });
    

    哪个输出:-

    Slim\Http\Response Object
    (
        [status:protected] => 200
        [headers] => Slim\Http\Headers Object
            (
                [data:protected] => Array
                    (
                        [Content-Type] => application/json
                    )
    
            )
    
        [cookies] => Slim\Http\Cookies Object
            (
                [defaults:protected] => Array
                    (
                        [value] => 
                        [domain] => 
                        [path] => 
                        [expires] => 
                        [secure] => 
                        [httponly] => 
                    )
    
                [data:protected] => Array
                    (
                    )
    
            )
    
        [body:protected] => {"data":{"Authorization":"786876866","user":{"id":"1","user_role":"1"}},"status":200,"success":true,"message":"user authentication successful"}
        [length:protected] => 577
    )
    

    当然你也会得到响应对象:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 2014-03-22
      • 1970-01-01
      • 2015-10-24
      相关资源
      最近更新 更多