ILogger accessing params args in the function Log<TState>(LogLevel logLevel

Viewed 2486

I am implementing a custom ILogger in .Net Core 3.1. The class needs to implement the following contract

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) 

I am triggering the LogDebug function and passing a list of tuple (key, value) arguments like this:

logger.LogDebug("MyDebugMessage", ("arg1Key", "arg2Value"), ("arg2Key", "arg2Value"), ("arg3Key", "arg3Value"));

The ILogger Log function is triggered and the first parameter the message "MyDebugMessage" is passed into the state parameter. However there is no variable for the list of arguments in the ILogger function. How can I access the list of arguments?

2 Answers

So far I've found that the only way is to use reflection to get the _values private member of TState state.

  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 
}
Related