Search code examples
logging.net-corenlog

NLog HttpTarget in .net core 6


I have a rest Api who needs to send the logs to a central api. I am using NLog for logging in .netcore 6, and Http Target to send the logs to the central logging api:


This is how i have adapted Http target in app.config.json

"Http": { "type": "HTTP", "URL": "https://localhost:7217/Log/*", "IgnoreSslErrors": "true", "layout": { "type": "JsonLayout", "attribute": [ { "sourcetype": "_json" }, { "host": "${machinename}" }, { "event": { "type": "JsonLayout", "attribute": [ { "level": "${level:upperCase=true}" }, { "source": "${logger}" }, { "thread": "${threadid}" }, { "message": "${message}" }, { "utc": "${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss.fff}" } ] } } ] } } },


In the central service i have created the method, to receive the logs:

    [HttpPost("LogsEntry")]
    [Consumes(MediaTypeNames.Application.Json)]

    public async Task<ActionResult> PostLogsEntryAsync([FromBody] Event rt)
    {
      ...
    }

What is the c# object(Event) i must expect in the central Api method?How to catch the event logs sent by Http Target with NLog, what properties should my Event object have? Cant find much info about HttpTarget in Nlog.


Solution

  • what properties should my Event object have?

    The answer is: It's up to you. The HTTP target does not send a fixed message in a format determined by NLog. Instead, you define yourself in the layout property the fields that your log messages have.

    Example

    Let's assume our target configuration looks like this:

    "http": {
      "type": "HTTP",
      "url": "https://localhost:7065/Log",
      "IgnoreSslErrors": "true",
      "contentType": "application/json",
      "layout": {
        "type": "JsonLayout",
        "attributes": [
          {
            "name": "level",
            "layout": "${level:upperCase=true}"
          },
          {
            "name": "source",
            "layout": "${logger}"
          },
          {
            "name": "thread",
            "layout": "${threadid}"
          },
          {
            "name": "message",
            "layout": "${message}"
          },
          {
            "name": "utc",
            "layout": "${date:universalTime=true:format=yyyy-MM-dd HH\\:mm\\:ss.fff}"
          }
        ]
      }
    }
    

    Then the corresponding Event model would look like this:

    public class Event
    {
        public string Level { get; set; }
    
        public string Source { get; set; }
    
        public string Thread { get; set; }
    
        public string Message { get; set; }
    
        public string Utc { get; set; }
    }