Getting NLog to send out JSON with proper headers?

别等时光非礼了梦想. 提交于 2019-12-04 03:15:46

Looking at the HttpNetworkSender source, I don't see an obvious way to pass in a content type to the WebRequest.

I think you will have to create a custom target based on the NetworkTarget which uses a custom HttpNetworkSender, and include config to set the content-type on the WebRequest Appropriately.

In case someone still stumble on this, here is simple demo for custom http target (NLog v4.x.x).

public class WebPostTarget : Target
{
    public string ServerUrl { get; set; }
    private readonly HttpClient _client = new HttpClient();

    protected override void Write(LogEventInfo logEvent)
    {
        PostData(new [] { logEvent.AsLogModel() }); 
    }

    protected override void Write(AsyncLogEventInfo[] logEvents)
    {
        var data = logEvents.Select(x => x.LogEvent.AsLogModel()).ToArray();
        PostData(data);
    }

    private void PostData(object data)
    {
        if (!ServerUrl.IsNullOrEmpty())
        {
            // add your custom headers to the client if you need to 
            _client.PostJsonAsync(ServerUrl, data).FireAndForget();
        }
    }
}
// HttpClientExtensions
public static async Task<HttpResponseMessage> PostJsonAsync(this HttpClient client, string url, object data)
{
    return await client.PostAsync(url, new StringContent(data.ToJson(), Encoding.UTF8, "application/json"));
}

From configuration code:

var asyncWebTarget = new AsyncTargetWrapper()
{
    Name = "web_batch_logServer",
    BatchSize = 100,
    TimeToSleepBetweenBatches = 1000,
    OverflowAction = AsyncTargetWrapperOverflowAction.Grow,
    WrappedTarget = new WebPostTarget { ServerUrl = logServerUrl }
};

NLog ver. 4.5 WebService Target has the ability to configure custom headers.

<target xsi:type="WebService"
         name="CouchDB"
         url="http://127.0.0.1:5984/logger/"
         protocol="JsonPost"
         encoding="utf-8">
      <parameter layout="FileLayout" />
      <header name="Content-Type" layout="application/json" />
</target>

See also https://github.com/nlog/NLog/wiki/WebService-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!