ILogger 访问函数 Log<TState>(LogLevel logLevel

doo*_*man 7 c# .net-core asp.net-core

我正在 .Net Core 3.1 中实现自定义 ILogger。类需要执行以下合约

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) 
Run Code Online (Sandbox Code Playgroud)

我触发 LogDebug 函数并传递元组(键,值)参数列表,如下所示:

logger.LogDebug("MyDebugMessage", ("arg1Key", "arg2Value"), ("arg2Key", "arg2Value"), ("arg3Key", "arg3Value"));
Run Code Online (Sandbox Code Playgroud)

ILogger 日志函数被触发,第一个参数消息“MyDebugMessage”被传递到状态参数中。但是,ILogger 函数中的参数列表没有变量。我如何访问参数列表?

Hug*_*ugo 7

到目前为止,我发现唯一的方法是使用反射来获取 TState 状态的 _values 私有成员。

  public class ApiLogger : ILogger
  {
       // more code 

       public async void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
       {  
               
           FieldInfo[] fieldsInfo = state.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
           FieldInfo props = fieldsInfo.FirstOrDefault(o => o.Name == "_values");
           object[] values = (object[])props?.GetValue(state);

           // more code 
       }

       // more code 
}
Run Code Online (Sandbox Code Playgroud)