You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在appsettings.json中为NLog Webservice Target指定Json布局

问题原因

WebService目标配置JsonPost协议时发起的请求体为空{},核心原因是未指定请求体对应的Json布局规则,NLog没有可序列化的日志字段映射,就会输出空对象。

解决方案

在dabomb目标节点下补充body配置,自定义JsonLayout结构即可,完整可用配置如下:

"NLog": {
  "targets": {
    "allfile":{
      "type":"File",
      "fileName":"/tmp/nlog-all-${shortdate}.log",
      "layout":"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"
    },
    "dabomb": {
      "type": "webservice",
      "url": "http://localhost:9990/api/foo/",
      "protocol": "JsonPost",
      "body": {
        "type": "JsonLayout",
        "attributes": [
          {
            "name": "timestamp",
            "layout": "${longdate}"
          },
          {
            "name": "level",
            "layout": "${level:uppercase=true}"
          },
          {
            "name": "logger",
            "layout": "${logger}"
          },
          {
            "name": "message",
            "layout": "${message}"
          },
          {
            "name": "eventId",
            "layout": "${event-properties:item=EventId_Id}"
          },
          {
            "name": "exception",
            "layout": "${exception:format=tostring}",
            "encode": false
          }
        ]
      }
    }
  },
  "rules": [
    {
      "logger": "*",
      "minLevel": "Debug",
      "writeTo": "dabomb"
    }
  ]
}
配置说明
  • JsonLayout下的attributes数组对应最终POST请求体Json的各个字段:name为Json键名,layout为对应字段的取值规则,使用NLog内置的布局渲染器语法即可,可以根据接口实际需要增删字段。
  • 如果不需要自定义字段结构,想直接输出全量结构化日志内容,可以将body节点替换为"layout": "${json:includeEventProperties=true}",这种方式配置更简单,但灵活度较低。
  • 如果是ASP.NET Core项目,确保项目已引入对应版本的NLog.Web.AspNetCore包,避免布局渲染器加载异常。

内容的提问来源于stack exchange,提问作者LiteWait

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 06:39:27