服务器日志加入请求数据

This commit is contained in:
2025-09-09 16:15:38 +08:00
parent 8076acc373
commit 61edc27509

View File

@@ -23,21 +23,37 @@ class ShelfWebServer implements WebServer {
ShelfWebServer(this.logger); ShelfWebServer(this.logger);
final String tag = "webserver"; final String tag = "webserver";
Stream<List<int>> encodeStream(
String data, {
Encoding encoding = utf8,
}) async* {
yield encoding.encode(data);
}
Future<String> decodeStream(Stream<List<int>> stream,
{Encoding encoding = utf8}) {
return encoding.decodeStream(stream);
}
// 中间件:记录请求日志 // 中间件:记录请求日志
Middleware logRequests() { Middleware logRequests() {
return (Handler innerHandler) { return (Handler innerHandler) {
return (Request request) async { return (Request request) async {
String body = await request.readAsString();
request = request.change(body: body);
final requestId = request.context['request_trace_id'] as String; final requestId = request.context['request_trace_id'] as String;
final requestSpanId = request.context['request_span_id'] as String; final requestSpanId = request.context['request_span_id'] as String;
final requestParentSpanId = final requestParentSpanId =
request.context['request_parent_span_id'] as String?; request.context['request_parent_span_id'] as String?;
logger.info('| 请求路径: ${request.method} ${request.requestedUri}',
logger.info('| 请求路径: ${request.method} ${request.requestedUri} $body',
tag: tag, tag: tag,
traceId: requestId, traceId: requestId,
spanId: requestSpanId, spanId: requestSpanId,
parentSpanId: requestParentSpanId); parentSpanId: requestParentSpanId);
// final stopwatch = Stopwatch()..start(); // final stopwatch = Stopwatch()..start();
final stopwatch = request.context["request_stop_watch"] as Stopwatch; final stopwatch = request.context["request_stop_watch"] as Stopwatch;
stopwatch.start(); stopwatch.start();
Response response; Response response;
try { try {