You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否用PostSharp 6.5.3为.NET Framework 4.6.1实现方法日志及耗时统计?

问题解答:PostSharp 6.5.3试用版在.NET Framework 4.6.1下实现方法日志与耗时统计
  • 完全可以实现需求
    PostSharp 6.5.3的试用版对.NET Framework 4.6.1提供完整支持,核心的AOP切面功能在试用版中无功能限制(仅存在试用期限或水印类提示,不影响功能使用),足以实现方法调用的进出日志记录与耗时统计。

  • 实现思路(基于PostSharp的AOP特性)

    • 创建自定义切面类,继承PostSharp.Aspects.OnMethodBoundaryAspect
    • 重写OnEntry方法:记录方法进入时间、方法全名、参数信息等日志
    • 重写OnExit或OnSuccess方法:计算当前时间与进入时间的差值,记录方法退出日志及耗时
    • 通过特性标记的方式,将切面应用到需要监控的方法、类或整个程序集上
  • 简单代码示例

using PostSharp.Aspects;
using System;
using System.Diagnostics;
using System.Linq;

[Serializable]
public class MethodLoggingAspect : OnMethodBoundaryAspect
{
    private Stopwatch _stopwatch;

    public override void OnEntry(MethodExecutionArgs args)
    {
        _stopwatch = Stopwatch.StartNew();
        var paramStr = string.Join(", ", args.Arguments.Select(a => a?.ToString() ?? "null"));
        Console.WriteLine($"[ENTRY] {DateTime.Now:yyyy-MM-dd HH:mm:ss} 方法 {args.Method.DeclaringType.FullName}.{args.Method.Name} 被调用,参数:{paramStr}");
    }

    public override void OnExit(MethodExecutionArgs args)
    {
        _stopwatch.Stop();
        Console.WriteLine($"[EXIT] {DateTime.Now:yyyy-MM-dd HH:mm:ss} 方法 {args.Method.DeclaringType.FullName}.{args.Method.Name} 执行完成,耗时:{_stopwatch.ElapsedMilliseconds}ms");
    }
}

// 使用示例:给目标类/方法添加特性标记
[MethodLoggingAspect]
public class BusinessService
{
    public void HandleOrder(string orderId, int quantity)
    {
        // 模拟业务逻辑耗时
        System.Threading.Thread.Sleep(200);
    }
}

内容的提问来源于stack exchange,提问作者Niraj Modi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 15:55:14