首页 > 解决方案 > 如何在 asp.net 核心日志记录和应用程序洞察中记录 json

问题描述

有没有办法在 asp.net core 2 中记录以下内容?

_logger.LogInformation("Someone did something! \r\n{detail}", new {
    SomeObject = someVariable,
    SomeOtherObject = someOtherVariable
});

我已经尝试使用序列化值,但生成的 json 似乎被截断了。

标签: asp.net-coreasp.net-core-logging

解决方案


您尝试使用的参数用于 args,通常用于消息的字符串插值。一些日志记录提供程序,例如 Serilog,会将这些 args 保存为 JSON,但是您依赖于特定的提供程序以及他们选择处理它的方式。

如果您的目标是简单地{detail}用 JSON 对象替换,那么直接在消息中执行此操作:

var detail = JsonConvert.SerializeObject(new
{
    SomeObject = someVariable,
    SomeOtherObject = someOtherVariable
});
_logger.LogInformation($"Someone did something! \r\n{detail}");

推荐阅读