public void Send(Message message) { string?exception = null; if (message.Exception != null) { exception = ""; using StringReader reader = new StringReader(message.Exception.ToString()); for (string?line = reader.ReadLine(); line != null; line = reader.ReadLine()) { exception += line + "\n"; } } SplunkEvent splunkEvent = new SplunkEvent { Event = new Fields { { "Time", message.Time }, { "Level", message.Level.ToString() }, { "Text", message.Text }, { "Meta", message.Meta }, { "Exception", exception }, { "MemberName", message.MemberName }, { "SourceFilePath", message.SourceFilePath }, { "SourceLineNumber", message.SourceLineNumber } }, Host = Host, Index = Index, Source = Source, SourceType = SourceType }; string content = JsonConvert.SerializeObject(splunkEvent); HttpRequestMessage request = new HttpRequestMessage( HttpMethod.Post, _url ); request.Content = new StringContent(content, Encoding.UTF8, "application/json"); Task <HttpResponseMessage> task = _httpClient.SendAsync(request); HttpResponseMessage result = task.Result; if (task.Exception != null) { throw task.Exception; } if (!result.IsSuccessStatusCode) { Console.WriteLine("Failed to send message to Splunk: " + result.Content.ReadAsStringAsync().Result); } }
private async Task ProcessQueue() { try { do { var count = 0; var events = new Queue<LogEvent>(); LogEvent next; while (count < _batchSizeLimitLimit && _queue.TryDequeue(out next)) { count++; events.Enqueue(next); } if (events.Count == 0) return; string allEvents = string.Empty; foreach (var logEvent in events) { var sw = new StringWriter(); _jsonFormatter.Format(logEvent, sw); var serialisedEvent = sw.ToString(); var splunkEvent = new SplunkEvent(serialisedEvent, _source, _sourceType, _host, _index); allEvents = $"{allEvents}{splunkEvent.Payload}"; } var request = new EventCollectorRequest(_splunkHost, allEvents); var response = await _httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { //Do Nothing? } else { //Application Errors sent via HTTP Event Collector if (HttpEventCollectorApplicationErrors.Any(x => x == response.StatusCode)) { SelfLog.WriteLine("A status code of {0} was received when attempting to send to {1}. The event has been discarded and will not be placed back in the queue.", response.StatusCode.ToString(), _splunkHost); } else { //Put the item back in the queue & retry on next go SelfLog.WriteLine("A status code of {0} was received when attempting to send to {1}. The event has been placed back in the queue", response.StatusCode.ToString(), _splunkHost); foreach (var logEvent in events) { _queue.Enqueue(logEvent); } } } } while (true); } catch (Exception ex) { SelfLog.WriteLine("Exception while emitting batch from {0}: {1}", this, ex); } }