如何在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
相关产品推荐
相关产品推荐

