When recording business logs, we often need to add a unique identifier string
RequestId
for each log, so as to quickly aggregate and query First of all,
RequestId
is a singleton that runs through the entire request life cycle. If in the entire request processing process, including different service layers and modules, I need to pass RequestId
transparently or as a parameter to logger
, the code is simply Don't be too beautiful.
Monolog
is the most popular PHP
log component. If it can automatically fill RequestId
for each log, it is very comfortable to use.
Monolog
of pushProcessor
method can help us achieve this requirement, pushProcessor
in processor
will each log your records will be processed and returned.
In the initial stage of the request, a global RequestId
is generated for this request. I put it on the Request
object. Different frameworks Request
singleton object of the request session. It is good for everyone to understand. Or you can use a singleton object alone to maintain RequestId
, as long as you ensure that the current request is in singleton mode (it is best to DI Container
<?php
use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler::class;
use Monolog\Formatter\LineFormatter::class;
class Log
$logger = new Logger('default');
// 添加处理器
$rfHandler = new RotatingFileHandler(__DIR__ . '/app_default.log', Logger::DEBUG);
$format = "[%datetime%] %channel%.%level_name%: %extra% %message% %context%\n";
$dateFormat = 'Y-m-d H:i:s';
$lFormatter = new LineFormatter($format, $dateFormat, true);
$rfHandler->setFormatter($lFormatter)
$logger->pushHandler($rfHandler);
// 就是在这里做处理啦 $request->getRequestId 自己去实现
$logger->pushProcessor(function ($log) {
/** @var Request $request */
$request = \request();//webman的
$log['extra']['request-id'] = $request->getRequestId();
return $log;
});
<?php
// 现在你就可以用日志服务了
$logger->info('this is monolog example');
$logger->info('this is log will auto fill requestId');
Remember to RequestId
to the front end, so that the problem feedback can easily trace the request link.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。