如何在 asp.net 核心日志记录和应用程序洞察中记录 json

How to log json in asp.net core logging and application insights

有什么方法可以在 asp.net core 2 中记录类似下面的内容吗?

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

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

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

如果您的目标只是将 {detail} 替换为 JSON 对象,则直接在消息中执行此操作即可:

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