尝试将对象的属性放入记录器时出错,NLog

Error when trying to put a attribute of an object to logger, NLog

当我尝试使用 NLog 放置应用程序日志以查看对象的属性时,它给我错误

_logger.Info("token :{0}, Object:{1}", "token", Object.Select(y => new { y.Id, y.Name, y.Charge})); 

这个显示错误"System.Linq.Enumerable+WhereSelectListIterator".

然后我尝试将其转换为 List as:

_logger.Info("token :{0}, Object:{1}", "token", Object.Select(y => new { y.Id, y.Name, y.Charge}).ToList()); 

然后错误显示为"System.Collections.Generic.List`1[<>f__AnonymousType1]"。

我似乎无法记录这个对象。有帮助吗?

如果你只想 stringify 对象你可以使用 @

_logger.Info("token :{0}, Object:{@1}", "token", Object.Select(y => new { y.Id, y.Name, y.Charge}).ToList()); 

但是我建议切换到结构化日志记录:https://github.com/NLog/NLog/wiki/How-to-use-structured-logging

_logger.Info("token :{token}, Object:{object}", "token", Object.Select(y => new { y.Id, y.Name, y.Charge})); 

根据上述文档,它应该正确地呈现 匿名对象集合。否则,您只需添加 @ 即可将对象序列化为 JSON 表示形式。