smashraid / NLog.Splunk

Splunk target to send logs in splunk
0 stars 1 forks source link

Use StreamContent instead of StringContent #4

Open snakefoot opened 6 years ago

snakefoot commented 6 years ago

https://github.com/smashraid/NLog.Splunk/blob/f51a01c4caf31cc08cb52ffd43bfa3bbf6a36b48/NLog.Splunk/NLog.Splunk/SplunkTarget.cs#L97

Write directly to MemoryStream, instead of first writing to StringBuilder and then allocating a complete string followed by a complete byte[] array, then this should improve performance:

var encoding = Encoding.UTF8;
var ms = new MemoryStream();
var jsonWriter = new StreamWriter(stream, encoding);
foreach (AsyncLogEventInfo item in logEvents)
{
  string json = BuildLog(item.LogEvent);
  jsonWriter.WriteLine(json);
}
jsonWriter.Flush();
ms.Position = 0;

var streamContent = new StreamContent(ms);
// TODO Consider caching the headerValue instead of allocating every time
var headerValue = new MediaTypeHeaderValue("text/plain") { CharSet = encoding.WebName };
streamContent.Headers.ContentType = headerValue;
var response = client.PostAsync(url, streamContent).Result;
snakefoot commented 6 years ago

Maybe consider changing from "text/plain" to "application/json"

snakefoot commented 6 years ago

Alternative consider moving to https://github.com/AlanBarber/NLog.Targets.Splunk, which supports batching and NetCore.