feat: 自定日志处理实现request id
This commit is contained in:
55
app/admin/driver/Logger.php
Normal file
55
app/admin/driver/Logger.php
Normal file
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
namespace app\admin\driver;
|
||||
|
||||
use think\log\driver\File;
|
||||
|
||||
class Logger extends File
|
||||
{
|
||||
public function save(array $log): bool
|
||||
{
|
||||
if (!$this->config['json']) {
|
||||
$this->config['format'] = '[%s][%s][%s] %s';
|
||||
}
|
||||
|
||||
$destination = $this->getMasterLogFile();
|
||||
|
||||
$path = dirname($destination);
|
||||
!is_dir($path) && mkdir($path, 0755, true);
|
||||
|
||||
$info = [];
|
||||
|
||||
// 日志信息封装
|
||||
$time = \DateTime::createFromFormat('0.u00 U', microtime())->setTimezone(new \DateTimeZone(date_default_timezone_get()))->format($this->config['time_format']);
|
||||
|
||||
$request_id = $log['request_id'];
|
||||
unset($log['request_id']);
|
||||
|
||||
foreach ($log as $type => $val) {
|
||||
$message = [];
|
||||
foreach ($val as $msg) {
|
||||
if (!is_string($msg)) {
|
||||
$msg = var_export($msg, true);
|
||||
}
|
||||
|
||||
$message[] = $this->config['json'] ?
|
||||
json_encode(['time' => $time, 'type' => $type, 'request_id' => $request_id, 'msg' => $msg], $this->config['json_options']) :
|
||||
sprintf($this->config['format'], $time, $type, $request_id, $msg);
|
||||
}
|
||||
|
||||
if (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level'])) {
|
||||
// 独立记录的日志级别
|
||||
$filename = $this->getApartLevelFile($path, $type);
|
||||
$this->write($message, $filename);
|
||||
continue;
|
||||
}
|
||||
|
||||
$info[$type] = $message;
|
||||
}
|
||||
|
||||
if ($info) {
|
||||
return $this->write($info, $destination);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -3,4 +3,5 @@
|
||||
return [
|
||||
// 登录验证
|
||||
app\admin\middleware\v1\Auth::class,
|
||||
app\admin\middleware\v1\RequestId::class,
|
||||
];
|
||||
|
||||
25
app/admin/middleware/v1/RequestId.php
Normal file
25
app/admin/middleware/v1/RequestId.php
Normal file
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
declare (strict_types = 1);
|
||||
|
||||
namespace app\admin\middleware\v1;
|
||||
|
||||
use think\facade\Event;
|
||||
class RequestId
|
||||
{
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
// 生成request_id
|
||||
$request_id = bin2hex(random_bytes(8));
|
||||
|
||||
// 将request_id设置到请求属性中
|
||||
$request->request_id = $request_id;
|
||||
header('X-Request-ID: ' . $request_id);
|
||||
|
||||
Event::listen('think\event\LogWrite', function($event) use($request_id) {
|
||||
$event->log['request_id'] = $request_id;
|
||||
});
|
||||
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user