我正在考虑使用 Postsharp 框架来减轻应用程序方法日志记录的负担。它基本上允许我用日志记录属性装饰方法,并在编译时将所需的日志记录代码注入 il.我喜欢这个解决方案,因为它可以将噪音排除在设计时间代码环境之外。有什么想法、经验或更好的选择吗?

有帮助吗?

解决方案

我使用 Castle Windsor DynamicProxies 通过 AOP 来应用日志记录。我已经在使用 Castle 作为 IoC 容器,因此将它用于 AOP 对我来说是阻力最小的路径。如果您想了解更多信息,请告诉我,我正在整理代码,以便将其作为博客文章发布

编辑

好的,这是基本的拦截器代码,虽然基本失败,但它可以完成我需要的一切。有两个拦截器,一个记录所有内容,另一个允许您定义方法名称以允许更细粒度的日志记录。该解决方案失败依赖于温莎城堡

抽象基类

namespace Tools.CastleWindsor.Interceptors
{
using System;
using System.Text;
using Castle.Core.Interceptor;
using Castle.Core.Logging;

public abstract class AbstractLoggingInterceptor : IInterceptor
{
    protected readonly ILoggerFactory logFactory;

    protected AbstractLoggingInterceptor(ILoggerFactory logFactory)
    {
        this.logFactory = logFactory;
    }

    public virtual void Intercept(IInvocation invocation)
    {
        ILogger logger = logFactory.Create(invocation.TargetType);

        try
        {
            StringBuilder sb = null;

            if (logger.IsDebugEnabled)
            {
                sb = new StringBuilder(invocation.TargetType.FullName).AppendFormat(".{0}(", invocation.Method);

                for (int i = 0; i < invocation.Arguments.Length; i++)
                {
                    if (i > 0)
                        sb.Append(", ");

                    sb.Append(invocation.Arguments[i]);
                }

                sb.Append(")");

                logger.Debug(sb.ToString());
            }

            invocation.Proceed();

            if (logger.IsDebugEnabled && invocation.ReturnValue != null)
            {
                logger.Debug("Result of " + sb + " is: " + invocation.ReturnValue);
            }
        }
        catch (Exception e)
        {
            logger.Error(string.Empty, e);
            throw;
        }
    }
}
}

完整日志记录实施

namespace Tools.CastleWindsor.Interceptors
{
using Castle.Core.Logging;

public class LoggingInterceptor : AbstractLoggingInterceptor
{
    public LoggingInterceptor(ILoggerFactory logFactory) : base(logFactory)
    {
    }
}
}

方法记录

namespace Tools.CastleWindsor.Interceptors
{
using Castle.Core.Interceptor;
using Castle.Core.Logging;
using System.Linq;

public class MethodLoggingInterceptor : AbstractLoggingInterceptor
{
    private readonly string[] methodNames;

    public MethodLoggingInterceptor(string[] methodNames, ILoggerFactory logFactory) : base(logFactory)
    {
        this.methodNames = methodNames;
    }

    public override void Intercept(IInvocation invocation)
    {
        if ( methodNames.Contains(invocation.Method.Name) )
            base.Intercept(invocation);
    }
}
}

其他提示

+1 后锐利。已经用于多种用途(包括一些向 C# 代码添加前置条件和后置条件的尝试),并且不知道如果没有它我将如何实现......

这在一定程度上取决于您将开发和支持该项目多长时间。当然,IL 编织是一项很好的技术,但是如果 IL 和/或程序集元数据格式再次发生更改(如 1.1 和 2.0 之间的情况)并且这些更改使该工具与新格式不兼容,会发生什么情况。

如果您依赖该工具,那么它会阻止您升级技术,直到该工具支持它。由于对此没有任何保证(甚至开发将继续,尽管看起来确实有可能),那么我对在长期项目中使用它会非常谨慎。

短期来看,没问题。

已经用它来做到这一点。效果很好!我强烈推荐它!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top