我正在考虑使用Postsharp框架来减轻应用程序方法日志的负担。它基本上允许我用日志属性修饰方法,并在编译时将所需的日志代码注入到il中。我喜欢这个解决方案,因为它将噪音排除在设计时间代码环境之外。有什么想法、经验或更好的选择吗?
发布于 2008-09-18 11:08:49
我使用Castle Windsor DynamicProxies将日志记录与面向方面编程结合起来。我已经使用Castle作为它的IoC容器,所以使用它作为面向方面编程对我来说是阻力最小的方法。如果你想要更多的信息,请让我知道,我正在整理代码,以便将其作为博客发布
编辑
好的,这是基本的拦截器代码,非常基本,但它能做我需要的一切。有两个拦截器,一个记录每件事,另一个允许您定义方法名称,以允许更细粒度的日志记录。这个解决方案完全依赖于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);
}
}
}发布于 2008-09-25 20:09:38
postsharp上的+1。我已经使用了很多东西(包括一些向C#代码添加前置条件和后置条件的尝试),如果没有它,我不知道怎么做……
发布于 2008-09-25 20:25:08
这在一定程度上取决于你将在多长时间内开发和支持该项目。当然,IL编织是一项很好的技术,但是如果IL和/或程序集元数据格式再次更改(就像在1.1和2.0之间一样),并且这些更改使工具与新格式不兼容,会发生什么情况。
如果你依赖这个工具,那么在这个工具支持之前,它会阻止你升级你的技术。如果没有关于这一点的保证(甚至开发将继续进行,尽管它看起来确实很有可能),那么我会对在长期项目中使用它非常谨慎。
不过,从短期来看,没有问题。
https://stackoverflow.com/questions/91635
复制相似问题