PostSharp - 记录器作为方面参数
PostSharp - logger as an aspect argument
想要将 PostSharp 诊断与封装在库程序集中的异常处理方面结合使用。
同时尝试在该诊断库的消费者程序集中设置和初始化 Serilog 记录器。
[AspectTypeDependency(AspectDependencyAction.Order, AspectDependencyPosition.After,
typeof(AddContextOnExceptionAttribute))]
[PSerializable]
public sealed class ReportAndSwallowExceptionAttribute : OnExceptionAspect
{
public ILogger TheLogger { get; set; }
public ReportAndSwallowExceptionAttribute(ILogger logger)
{
TheLogger = logger;
}
public override void OnException(MethodExecutionArgs args)
{
TheLogger.Error("Error happened ...");
}
}
主要class:
class Program
{
// below line is the critical part which seems ILogger is not allowed
[ReportAndSwallowException(Log.Logger)]
public static void TryExceptionMethod()
{
throw new NotImplementedException();
}
static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.File(@"HERE\Logs\log-x.log",
rollingInterval: RollingInterval.Day)
.CreateLogger();
Console.WriteLine("Hello World!");
TryExceptionMethod();
}
}
似乎将 ILogger
传递给该属性是非法的,我该如何实现这种情况?
当前错误:
Error CS0181: Attribute constructor parameter 'logger' has type 'ILogger', which is not a valid attribute parameter type
认为这个错误需要一个常量来解决,但主要问题是如何实现这种情况:在消费者项目中有记录器,在库中有方面。
此处最简单的选择是您的方面直接引用 Log.Logger。
这里记录了其他几个更复杂的选项:https://doc.postsharp.net/consuming-dependencies