gpt4 book ai didi

c# - PostSharp - il 编织 - 想法

转载 作者:可可西里 更新时间:2023-11-01 08:58:00 27 4
gpt4 key购买 nike

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

最佳答案

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

编辑

好的,这是基本的拦截器代码,虽然基本不合格,但它可以满足我的所有需求。有两个拦截器,一个记录所有内容,另一个允许您定义方法名称以允许更细粒度的日志记录。此解决方案不依赖于 CaSTLe Windsor

抽象基类

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);
}
}
}

关于c# - PostSharp - il 编织 - 想法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/91635/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com