关于收集此次所有日志的问题
问题描述
laravel框架5.8
先看一下现在的日志吧
{"log_times":"2022-11-09 00:15:44","request_id":771070115,"client_ip":"127.0.0.1","request_path":"product/test","message":"token----------------------eyJpZCI6IjEiLCJuYW1lIjoiQWRtaW4iLCJjb2RlIjoiYWRtaW4iLCJyb2xlIjpudWxsLCJpYXQiOjE2Njc4Mjc2MDEsImV4cCI6MTY3MzAxMTYwMSwicGxhdGZvcm1UeXBlIjpudWxsLCJwbGF0Zm9ybURhdGEiOnsiaWQiOiIxIiwibmFtZSI6ImFkbWluIiwic3VwZXIiOiIwMDAwIn19.5ad2744c3f4b4e7a123176567092a31d"}
{"log_times":"2022-11-09 00:15:44","request_id":843106128,"client_ip":"127.0.0.1","request_path":"product/test","message":"客户端验证--- "}
{"log_times":"2022-11-09 00:15:44","request_id":550717236,"client_ip":"127.0.0.1","request_path":"product/test","message":"test"}
{"log_times":"2022-11-09 00:15:45","request_id":124240686,"client_ip":"127.0.0.1","request_path":"product/test","message":"回滚错误日志--SQLSTATE[42S22]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]列名 'aaaa' 无效。 (SQL: insert into [spd_aatest1] ([name], [aaaa]) values (1290, xxx))"}
{"log_times":"2022-11-09 00:15:45","request_id":213659193,"client_ip":"127.0.0.1","request_path":"product/test","message":"Err::数据错误,请联系管理员!, code::9999"}
{"log_times":"2022-11-09 00:15:45","request_id":672435311,"client_ip":"127.0.0.1","request_path":"product/test","message":"数据错误,请联系管理员!"}
{"log_times":"2022-11-09 00:15:45","request_id":406119165,"client_ip":"127.0.0.1","request_path":"product/test","message":"api_request_finished"}
现在请求一次API,会产品这么行日志,从token
开始,到messaes
为api_request_finished
时结束
过程中的路由位置、SQL执行的语句等都做了处理,所以才会这么多
但是这种方式并不方便后期查看,一天的log文件就得10几MB
预想的结果
在写入log的地方做个断点,先将每次打印的信息收集起来,等到本次API完全结束时,序列化所有的信息在写入,这样就能一个API对应一条LOG了,但是不清楚怎么判断本次API请求结束
public function format(array $record)
{
$request = app('request');
$rand = rand(100000000,999999999);
// 收集到每次的日志信息并存放在一个地方
$newRecord = [
'log_times' => $record['datetime']->format('Y-m-d H:i:s'),
'request_id' => $rand,
'client_ip' =>$request->getClientIp(),
'request_path' => $request->path(),
'message' => $record['message'],
];
if (!empty($record['context'])){
$newRecord = array_merge($newRecord,$record['context']);
}
/**
* 请求结束,最后统一写入
*/
$json = $this->toJson($this->normalize($newRecord), true) . ($this->appendNewline ? "\n" : '');
return $json;
}
不知道这种方式可不可取,或是有没有更好的方法
推荐文章: