在 dotnet core 中使用 NLog 捕获控制器名称和方法名称

Capture controller name and method name using NLog in dotnet core

我正在尝试使用 NLog 库在 dotnet 核心应用程序中捕获控制器名称和方法名称。下面的一组代码在配置中用于捕获它们。我能够获取控制器和操作名称,但没有得到预期的结果。

Nlog 配置文件:

 <targets>   
  <target xsi:type="File" archiveAboveSize="10000000" archiveNumbering="DateAndSequence" name="eventLog" fileName="D:\MiningApp\Logs\MiningApp_Log_${shortdate}.log"
    layout="${longdate} | ${uppercase:${level}} | ${callsite} | ${logger} | ${message}" />
 </targets>

当前结果:

2021-07-21 15:34:17.1299 | INFO | MiningApp.Controllers.MasterController.GetUsers | MiningApp.Controllers.MasterController | Logging started for department
2021-07-21 15:34:17.2165 | INFO | MiningApp.Controllers.MasterController+<GetUsers>d__42.MoveNext | MiningApp.Controllers.MasterController | Logging ended for department

预期结果:

2021-07-21 15:34:17.1299 | INFO | ControllerName: MiningApp.Controllers.MasterController | MethodName : MiningApp.Controllers.MasterController.GetUsers | Logging started for department
2021-07-21 15:34:17.1376 | INFO | ControllerName: MiningApp.Controllers.MasterController | MethodName : MiningApp.Controllers.MasterController.GetUsers | Logging ended for department

我还需要将文件限制设置为 10MB,当文件达到该大小时,它应该创建一个新文件。文件名应类似于 Ex: MiningApp_Log_21.07.2021_01, MiningApp_Log_21.07.2021_02。非常感谢任何意见或建议。

对于您的预期结果,这应该有效:

<targets>   
<target xsi:type="File" archiveAboveSize="10000000" archiveNumbering="DateAndSequence" name="eventLog" fileName="D:\MiningApp\Logs\MiningApp_Log_${shortdate}.log"
  layout="${longdate} | ${uppercase:${level}} | ControllerName: ${callsite:methodName=false} | MethodName: ${callsite:includeSourcePath=false} | ${message}" />
</targets>

通过阅读文档进行配置:https://nlog-project.org/config/?tab=layout-renderers