/// <summary> /// Emit a batch of log events, running to completion synchronously. /// </summary> /// <param name="events">The events to emit.</param> /// <remarks>Override either <see cref="PeriodicBatchingSink.EmitBatch"/> or <see cref="PeriodicBatchingSink.EmitBatchAsync"/>, /// not both.</remarks> protected override void EmitBatch(IEnumerable <LogEvent> events) { var payload = new StringWriter(); payload.Write("{\"d\":["); var formatter = new SimpleJsonFormatter(true); var delimStart = "{"; foreach (var logEvent in events) { payload.Write(delimStart); formatter.Format(logEvent, payload); var renderedMessage = logEvent.RenderedMessage; payload.Write(",\"UtcTimestamp\":\"{0:u}\",\"RenderedMessage\":\"{1}\"}}", logEvent.Timestamp.ToUniversalTime().DateTime, SimpleJsonFormatter.Escape(renderedMessage)); delimStart = ",{"; } payload.Write("]}"); var bson = BsonDocument.Parse(payload.ToString()); var docs = bson["d"].AsBsonArray; GetLogCollection().InsertBatch(docs); }
/// <summary> /// Emit a batch of log events, running asynchronously. /// </summary> /// <param name="events">The events to emit.</param> /// <remarks>Override either <see cref="PeriodicBatchingSink.EmitBatch"/> or <see cref="PeriodicBatchingSink.EmitBatchAsync"/>, /// not both.</remarks> protected override async Task EmitBatchAsync(IEnumerable <LogEvent> events) { var payload = new StringWriter(); payload.Write("{\"docs\":["); var formatter = new SimpleJsonFormatter(true); var delimStart = "{"; foreach (var logEvent in events) { payload.Write(delimStart); formatter.Format(logEvent, payload); var renderedMessage = logEvent.RenderedMessage; payload.Write(",\"UtcTimestamp\":\"{0:u}\",\"RenderedMessage\":\"{1}\"}}", logEvent.Timestamp.ToUniversalTime().DateTime, SimpleJsonFormatter.Escape(renderedMessage)); delimStart = ",{"; } payload.Write("]}"); var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json"); var result = await _httpClient.PostAsync(BulkUploadResource, content); if (!result.IsSuccessStatusCode) { SelfLog.WriteLine("Received failed result {0}: {1}", result.StatusCode, result.Content.ReadAsStringAsync().Result); } }
public void WellKnownSpecialCharactersAreEscapedAsNormal() { const string s = "\\\"\t\r\n\f"; var escaped = SimpleJsonFormatter.Escape(s); Assert.AreEqual("\\\\\\\"\\t\\r\\n\\f", escaped); }
public void EmbeddedEscapesPreservePrefixAndSuffix() { const string s = "a\nb"; var escaped = SimpleJsonFormatter.Escape(s); Assert.AreEqual("a\\nb", escaped); }
public void UnprintableCharactersAreEscapedAsUnicodeSequences() { const string s = "\u0001"; var escaped = SimpleJsonFormatter.Escape(s); Assert.AreEqual("\\u0001", escaped); }
public void StringsWithoutSpecialCharactersAreUnchanged() { const string s = "Hello, world!"; var escaped = SimpleJsonFormatter.Escape(s); Assert.AreSame(s, escaped); }