如何使用带有 Serilog 的 postsharp 来分离日志记录方面?

How to use postsharp with Serilog to separate logging aspect?

我是 AOP 的初学者,我尝试使用 PostSharpSeriLog 来记录我的 MVC application

所以我发现这个 sample 示例是一个开始,但我想知道在这个示例中它是否像那样明确地使用记录器:

activity.Write(LogLevel.Warning, "The entity {id} has been marked for deletion.", item.Id);

在业务中classQueueProcessor,那么这里的aspect有什么价值呢!我还在写日志代码加上业务代码!


有人可以帮助我使用以下方法分离 MVC 项目的注销吗 PostSharp.Patterns.Diagnostics.Backends.Serilog?

When you're using the LogAttribute aspect, PostSharp automatically generates code that emits log records before and after the execution of a method. But there are times when you will want to write your own records. For instance, you may want to log a custom error or warning. You may want this message to be displayed even when trace-level logging is disabled. But when it is enabled, you want this message to appear in the right context, with the proper indentation. For these scenarios, you can use the methods provided by the Logger class.

在示例class中,手动添加了一些关于业务逻辑的自定义日志。


首先,您必须从这里下载: https://www.postsharp.net/download

安装插件时,在visual studio中创建一个项目。 在解决方案资源管理器中,通过右键单击项目或在您的代码文件中,通过右键单击 class 或方法名称,您可以将 PostSharp 添加到您的项目中。

项目中添加默认配置和属性。 之后,您将更改配置、格式,并可能根据您的需要添加自定义方面 classes。

继续阅读这些文档将会很有用:

https://doc.postsharp.net/logging

https://doc.postsharp.net/serilog

你误解了这个例子,让我澄清一下。

示例代码中有两种日志记录方式。您找到了明显的 activity.Write(xxx)。使用像 PostSharp 这样的 AOP 框架不包括这种日志记录。这种日志记录可以看作是业务逻辑的一部分,因为它特定于正在发生的操作。

现在,另一方面:假设您要记录对应用程序中所有方法的每次调用。您想要记录何时调用该方法以及使用什么参数。此外,如果有返回值,您还想记录下来。

想象必须为每个方法编写这样的东西:

bool SomeMethod(int input)
{
    var sw = Stopwatch.StartNew();
    logger.Write($"Started executing {nameof(SomeMethod)} at {DateTime.Now}. Value of {nameof(input)}: {input})";

    ... // some work
    var returnValue = false;

    sw.Stop();
    logger.Write($"Finished executing {nameof(SomeMethod)}. It took {sw.ElapsedMilliseconds}ms. Returned value: {returnValue}");

    return returnValue;
}

现在 that 是一个横切关注点,that 就是示例所展示的内容。 PostSharp 通过在 program.cs:

中执行此操作来注入此管道代码
using PostSharp.Patterns.Diagnostics;
using PostSharp.Patterns.Diagnostics.Backends.Serilog;
using PostSharp.Samples.Logging.BusinessLogic;
using Serilog;

// Add logging to all methods of this project.
[assembly: Log]
    ...

更多详情here

现在,最后,让我们回到你的问题:

Could someone help me to separate the logging out of the MVC project using PostSharp.Patterns.Diagnostics.Backends.Serilog?

我不确定您对业务逻辑代码中自定义日志记录的任何 AOP 框架有何期望。你能扩展一下吗?还是以上说明就足够了?

编辑:解决您评论中的问题

  1. 我不认为 PostSharp 的示例是 DDD 示例。它们只是证明用于方面的记录器也可用于记录与业务相关的信息(实体已标记为删除。)在 DDD 中,如果此信息与某人或某物相关,则它将是可以使用方面记录的事件.
  2. 通过使用审计方面来捕获事件来创建审计跟踪当然是正确的方法。至于表示层,您可以使用一些中间件来记录请求和响应,例如演示 here 。在这种情况下,无需使用 PostSharp。根据您 DDD 应用程序中的事件代码,您也许能够在事件发送之前或之后拦截事件,因此您也可以在那里编写自己的日志记录,从而消除对 PostSharp 的需求。
  3. 您是否尝试过已标记为重复的问题的答案中所听的步骤?