namespace log\processor;
use Request;
class RequestProcessor
{
public function __invoke($record)
{
$extra = [
'method' => Request::method(),
'path' => Request::pathinfo()
];
if (Request::header('X-Request-ID')) {
$extra['uid'] = Request::header('X-Request-ID');
} else {
$extra['uid'] = app('requestId');
}
$record['extra'] = $extra;
return $record;
}
}
app(‘requestId’); 是将 请求方式写到了 app 容器中,也就是全局里
创建 requestId
use Monolog\Processor\UidProcessor;
'requestId' => function () {
return (new UidProcessor(32))->getUid();
},
在请求日志中添加
use Monolog\Formatter\JsonFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\PsrLogMessageProcessor;
use log\processor\RequestProcessor;
\Psr\Log\LoggerInterface::class => function () {
$date = date_create();
$folder = Env::get('MONOLOG_PATH') . $date->format('Ym');
$day = $date->format('d');
$hour = $date->format('H');
$seg = $day . '.' . ceil($hour / 6);
if (PHP_SAPI === 'cli') {
$suffix = '_cli';
} else {
$suffix = '';
}
$logFileName = $folder . '/' . $seg . $suffix . '.log';
$handler = new StreamHandler($logFileName);
$handler->setFormatter(new JsonFormatter());
$handlers = [
$handler
];
$processors = [
new RequestProcessor(),
new PsrLogMessageProcessor()
];
$logger = new Logger('jsboss3', $handlers, $processors);
return $logger;
},
|