mirror of
https://github.com/GeWuYou/GFramework.git
synced 2026-03-22 10:34:30 +08:00
perf(cqrs): 优化LoggingBehavior性能并改进错误处理
- 添加Stopwatch用于精确测量请求处理时间 - 将Handle方法改为异步方法并正确await next调用 - 在成功和失败情况下都记录详细的耗时信息 - 添加对OperationCanceledException的特殊处理和日志记录 - 改进异常处理逻辑以包含执行时间信息
This commit is contained in:
parent
35d05a46fa
commit
276f50a255
@ -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<TRequest, TResponse> : IPipelineBehavior<TRe
|
||||
/// <param name="next">下一个处理委托,用于继续管道执行</param>
|
||||
/// <param name="cancellationToken">取消令牌,用于取消操作</param>
|
||||
/// <returns>处理结果的ValueTask</returns>
|
||||
public ValueTask<TResponse> Handle(TRequest message, MessageHandlerDelegate<TRequest, TResponse> next,
|
||||
public async ValueTask<TResponse> Handle(
|
||||
TRequest message,
|
||||
MessageHandlerDelegate<TRequest, TResponse> 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;
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user