From 276f50a25539d9d58fe157dcadf5461912be87d1 Mon Sep 17 00:00:00 2001 From: GeWuYou <95328647+GeWuYou@users.noreply.github.com> Date: Sat, 14 Feb 2026 19:14:38 +0800 Subject: [PATCH] =?UTF-8?q?perf(cqrs):=20=E4=BC=98=E5=8C=96LoggingBehavior?= =?UTF-8?q?=E6=80=A7=E8=83=BD=E5=B9=B6=E6=94=B9=E8=BF=9B=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加Stopwatch用于精确测量请求处理时间 - 将Handle方法改为异步方法并正确await next调用 - 在成功和失败情况下都记录详细的耗时信息 - 添加对OperationCanceledException的特殊处理和日志记录 - 改进异常处理逻辑以包含执行时间信息 --- .../cqrs/behaviors/LoggingBehavior.cs | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/GFramework.Core/cqrs/behaviors/LoggingBehavior.cs b/GFramework.Core/cqrs/behaviors/LoggingBehavior.cs index d6bbd7a..e8d9fe7 100644 --- a/GFramework.Core/cqrs/behaviors/LoggingBehavior.cs +++ b/GFramework.Core/cqrs/behaviors/LoggingBehavior.cs @@ -11,6 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Diagnostics; using GFramework.Core.Abstractions.logging; using GFramework.Core.logging; using Mediator; @@ -37,22 +38,34 @@ public sealed class LoggingBehavior : IPipelineBehavior下一个处理委托,用于继续管道执行 /// 取消令牌,用于取消操作 /// 处理结果的ValueTask - public ValueTask Handle(TRequest message, MessageHandlerDelegate next, + public async ValueTask Handle( + TRequest message, + MessageHandlerDelegate next, CancellationToken cancellationToken) { var requestName = typeof(TRequest).Name; + var start = Stopwatch.GetTimestamp(); _logger.Debug($"Handling {requestName}"); try { - var response = next(message, cancellationToken); - _logger.Debug($"Handled {requestName} successfully"); + var response = await next(message, cancellationToken); + + var elapsed = Stopwatch.GetElapsedTime(start); + _logger.Debug($"Handled {requestName} successfully in {elapsed.TotalMilliseconds} ms"); + return response; } + catch (OperationCanceledException) + { + _logger.Warn($"Handling {requestName} was cancelled"); + throw; + } catch (Exception ex) { - _logger.Error($"Error handling {requestName}", ex); + var elapsed = Stopwatch.GetElapsedTime(start); + _logger.Error($"Error handling {requestName} after {elapsed.TotalMilliseconds} ms", ex); throw; } }