PHP增加X_REQUEST_ID

近项目中需记录每个请求的request_id,从nginx追踪到php

这里使用nginx内置的变量$request_id(nginx 1.11.0 版本新增加的feature)

修改fastcgi_params增加

fastcgi_param X_REQUEST_ID $request_id;

这时通过打印全局变量$_SERVER即可看到我们刚刚定义的X_REQUEST_ID

获得X_REQUEST_ID后就可以用在具体的业务场景中了,比如我用Laravel记录日志,其中保存X_REQUEST_ID

截取部分代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$logger = new Logger('mango');
// 额外增加x_request_id
$logger->pushProcessor(function ($record) {
    $record['extra']['x_request_id'] = app('request')->server('X_REQUEST_ID');
    return $record;
});

$w = new Writer($logger);
$w->useDailyFiles(storage_path()."/logs/".$file.'.log');
$w->info($message = $addr, $context = $info);

补充:

如果要给laravel默认错误日志也加上X_REQUEST_ID,可以参考以下代码,路径:/bootstrap/app.php laravel5.5

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/

// 日志增加x_request_id
$app->configureMonologUsing(function($monolog) {
    $monolog->pushProcessor(function ($record) {
        $record['extra']['x_request_id'] = app('request')->server('X_REQUEST_ID');
        return $record;
    });

    $filename = storage_path('/logs/laravel.log');
    $monolog->pushHandler(new Monolog\Handler\RotatingFileHandler($filename));
});

return $app;
updatedupdated2018-08-232018-08-23
Load Comments?