Skip to content

Commit 712f8d0

Browse files
committed
Cleanup on dispose
1 parent 76cd9b0 commit 712f8d0

File tree

2 files changed

+78
-45
lines changed

2 files changed

+78
-45
lines changed

sample/Serilog.Sinks.Splunk.Sample/Program.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ namespace Serilog.Sinks.Splunk.Sample
88
{
99
class Program
1010
{
11+
public static string EventCollectorToken = "DC279305-1816-44D6-9D7A-6CBB70F0A049";
12+
1113
static void Main(string[] args)
1214
{
1315
var stub = new Stub();
@@ -26,7 +28,7 @@ static void Main(string[] args)
2628

2729
stub.Run();
2830

29-
var range = Enumerable.Range(0, 10000);
31+
var range = Enumerable.Range(0, 100);
3032

3133
foreach (var i in range)
3234
{
@@ -45,7 +47,7 @@ public void Configure()
4547

4648
Log.Logger = new LoggerConfiguration()
4749
.WriteTo.LiterateConsole()
48-
.WriteTo.SplunkViaEventCollector("https://mysplunk:8088/services/collector", "685546AE-0278-4786-97C4-5971676D5D70",
50+
.WriteTo.SplunkViaEventCollector("https://mysplunk:8088/services/collector", Program.EventCollectorToken,
4951
renderTemplate:false,
5052
batchSizeLimit:150,
5153
batchIntervalInSeconds:5)
@@ -65,7 +67,7 @@ public void Configure()
6567
Log.Logger = new LoggerConfiguration()
6668
.WriteTo.LiterateConsole()
6769
.WriteTo.SplunkViaEventCollector("https://mysplunk:8088/services/collector",
68-
"685546AE-0278-4786-97C4-5971676D5D70",
70+
Program.EventCollectorToken,
6971
"Serilog",
7072
"",
7173
Environment.MachineName,

src/Serilog.Sinks.Splunk/Sinks/Splunk/EventCollectorSink.cs

Lines changed: 73 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public class EventCollectorSink : ILogEventSink, IDisposable
4141
private readonly int _batchSizeLimitLimit;
4242
private readonly SplunkJsonFormatter _jsonFormatter;
4343
private readonly ConcurrentQueue<LogEvent> _queue;
44-
private readonly EventCollectorClient _httpClient;
44+
private readonly EventCollectorClient _httpClient;
4545

4646
/// <summary>
4747
/// Taken from Splunk.Logging.Common
@@ -69,21 +69,24 @@ public EventCollectorSink(
6969
int batchSizeLimit = 100,
7070
IFormatProvider formatProvider = null,
7171
bool renderTemplate = true
72-
)
72+
)
7373
{
7474
_splunkHost = splunkHost;
7575
_eventCollectorToken = eventCollectorToken;
7676
_queue = new ConcurrentQueue<LogEvent>();
7777
_jsonFormatter = new SplunkJsonFormatter(renderMessage: true, formatProvider: formatProvider, renderTemplate: renderTemplate);
7878
_batchSizeLimitLimit = batchSizeLimit;
79+
7980
var batchInterval = TimeSpan.FromSeconds(batchIntervalInSeconds);
8081

8182
_httpClient = new EventCollectorClient(_eventCollectorToken);
8283

83-
//TODO: Implement handling similar to the Seq HTTP sink, including dispose flush
84-
85-
RepeatAction.OnInterval(batchInterval, () => ProcessQueue().Wait(), new CancellationToken());
84+
var cancellationToken = new CancellationToken();
8685

86+
RepeatAction.OnInterval(
87+
batchInterval,
88+
async () => await ProcessQueue(),
89+
cancellationToken);
8790
}
8891

8992
/// <summary>
@@ -153,56 +156,84 @@ private async Task ProcessQueue()
153156
if (events.Count == 0)
154157
return;
155158

156-
string allEvents = string.Empty;
159+
await Send(events);
157160

158-
foreach (var logEvent in events)
159-
{
160-
var sw = new StringWriter();
161-
_jsonFormatter.Format(logEvent, sw);
161+
} while (true);
162+
}
163+
catch (Exception ex)
164+
{
165+
SelfLog.WriteLine("Exception while emitting batch from {0}: {1}", this, ex);
166+
}
167+
}
162168

163-
var serialisedEvent = sw.ToString();
164-
165-
var splunkEvent = new SplunkEvent(serialisedEvent, _source, _sourceType, _host, _index);
169+
private async Task Send(IEnumerable<LogEvent> events)
170+
{
171+
string allEvents = string.Empty;
166172

167-
allEvents = $"{allEvents}{splunkEvent.Payload}";
173+
foreach (var logEvent in events)
174+
{
175+
var sw = new StringWriter();
176+
_jsonFormatter.Format(logEvent, sw);
168177

169-
}
170-
var request = new EventCollectorRequest(_splunkHost, allEvents);
171-
172-
var response = await _httpClient.SendAsync(request);
178+
var serialisedEvent = sw.ToString();
173179

174-
if (response.IsSuccessStatusCode)
175-
{ //Do Nothing?
176-
}
177-
else
178-
{
179-
//Application Errors sent via HTTP Event Collector
180-
if (HttpEventCollectorApplicationErrors.Any(x => x == response.StatusCode))
181-
{
182-
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);
183-
}
184-
else
185-
{
186-
//Put the item back in the queue & retry on next go
187-
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);
188-
189-
foreach (var logEvent in events)
190-
{
191-
_queue.Enqueue(logEvent);
192-
}
193-
}
194-
}
195-
} while (true);
180+
var splunkEvent = new SplunkEvent(serialisedEvent, _source, _sourceType, _host, _index);
181+
182+
allEvents = $"{allEvents}{splunkEvent.Payload}";
196183
}
197-
catch (Exception ex)
184+
var request = new EventCollectorRequest(_splunkHost, allEvents);
185+
186+
var response = await _httpClient.SendAsync(request);
187+
188+
if (response.IsSuccessStatusCode)
198189
{
199-
SelfLog.WriteLine("Exception while emitting batch from {0}: {1}", this, ex);
190+
//Do Nothing?
191+
}
192+
else
193+
{
194+
//Application Errors sent via HTTP Event Collector
195+
if (HttpEventCollectorApplicationErrors.Any(x => x == response.StatusCode))
196+
{
197+
SelfLog.WriteLine(
198+
"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.",
199+
response.StatusCode.ToString(), _splunkHost);
200+
}
201+
else
202+
{
203+
//Put the item back in the queue & retry on next go
204+
SelfLog.WriteLine(
205+
"A status code of {0} was received when attempting to send to {1}. The event has been placed back in the queue",
206+
response.StatusCode.ToString(), _splunkHost);
207+
208+
foreach (var logEvent in events)
209+
{
210+
_queue.Enqueue(logEvent);
211+
}
212+
}
200213
}
201214
}
202215

203216
/// <inheritdoc/>
204217
public void Dispose()
205218
{
219+
Dispose(true);
220+
}
221+
222+
/// <inheritdoc/>
223+
protected virtual void Dispose(bool disposing)
224+
{
225+
if (!disposing) return;
226+
227+
var remainingEvents = new List<LogEvent>();
228+
229+
while (!_queue.IsEmpty)
230+
{
231+
LogEvent next;
232+
_queue.TryDequeue(out next);
233+
remainingEvents.Add(next);
234+
}
235+
236+
Send(remainingEvents).Wait();
206237
_httpClient.Dispose();
207238
}
208239
}

0 commit comments

Comments
 (0)