传递给您的函数的Func<TState, Exception, string> formatter 函数基本上只是一个实用函数,用于将状态转换为单个字符串消息。在您的记录器中,您基本上只需要调用formatter(state, exception) 来获取应该记录的格式化消息。
通常,除了调用它来获取格式化的消息之外,您不需要真正关心该函数,因此所有记录器通常都会这样做。对于 JSON 记录器,您可以完全忽略它,或者至少也导出格式化的消息,以便它作为可读字符串存在。
快速而肮脏的 JSON 记录器的 Log 方法实际上可能如下所示:
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var jsonLine = JsonConvert.SerializeObject(new {
logLevel,
eventId,
parameters = (state as IEnumerable<KeyValuePair<string, object>>)?.ToDictionary(i => i.Key, i => i.Value),
message = formatter(state, exception),
exception = exception?.GetType().Name
});
// store the JSON log message somewhere
Console.WriteLine(jsonLine);
}
如您所见,在这里生成 JSON 对象并没有那么神奇。