Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting NLog to send out JSON with proper headers?

Trying to use NLog to send JSON-encoded logs out of our C# app, to dump them into CouchDB. However, using the Network target, I can't seem to find a way to set the Content-Type header properly; and CouchDB won't have anything to do with my input otherwise.

CouchDB is out-of-the-box, Current NLog config:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="true">
    <variable name="FileLayout" value='{ "date":"${longdate}","level":"${level}","message":${message}}' />
    <targets>
      <target name="logfile" xsi:type="Network" address="http://127.0.0.1:5984/logger/" layout="${FileLayout}" />
    </targets>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="logfile" />
    </rules>
  </nlog>

And the raw HTTP (hostnames edited):

POST http://127.0.0.1:5984/logger/ HTTP/1.1
Host: 127.0.0.1:5984
Content-Length: 221
Expect: 100-continue

{ "date":"2011-08-12 13:38:06.4603","level":"Info","message":{"backlog":0, "too_busy":0, "io_threads":1000, "threads":32766, "messages_processed":0}, "ProcessName": "foobar"}
like image 538
acp Avatar asked Aug 12 '11 17:08

acp


2 Answers

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.

like image 152
Brook Avatar answered Nov 12 '22 11:11

Brook


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

like image 3
Rolf Kristensen Avatar answered Nov 12 '22 10:11

Rolf Kristensen