ILogger在函数Log< TState>(LogLevel logLevel中访问参数args [英] ILogger accessing params args in the function Log<TState>(LogLevel logLevel
问题描述
我正在.Net Core 3.1中实现自定义ILogger.该班需要执行以下合同
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)
我正在触发LogDebug函数并传递像这样的元组(键,值)参数列表:
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"));
触发ILogger日志功能,并且第一个参数消息"MyDebugMessage"被触发.传递给状态参数.但是,ILogger函数中的参数列表没有变量.如何访问参数列表?
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?
推荐答案
到目前为止,我发现唯一的方法是使用反射来获取TState状态的_values私有成员.
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
}
这篇关于ILogger在函数Log< TState>(LogLevel logLevel中访问参数args的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!