LogOutgoingBehavior(ConvertHeader convertHeader) { this.convertHeader = convertHeader; var templateParser = new MessageTemplateParser(); messageTemplate = templateParser.Parse("Sent message {OutgoingMessageType} {OutgoingMessageId}."); }
private bool LogCompletion(HttpRequestMessage request, DiagnosticContextCollector collector, HttpStatusCode statusCode, long elapsedTicks) { var logger = Log.ForContext <RequestLoggingHandler>(); if (!logger.IsEnabled(LogLevelDefault)) { return(false); } if (!collector.TryComplete(out var collectedProperties)) { collectedProperties = NoProperties; } var clientType = Type.GetType(_clientName); var name = clientType != null ? clientType.Name : _clientName; // Last-in (correctly) wins... var properties = collectedProperties.Concat(new[] { new LogEventProperty("HttpClient", new ScalarValue(name)), new LogEventProperty("RequestMethod", new ScalarValue(request.Method)), new LogEventProperty("RequestPath", new ScalarValue(request.RequestUri.AbsolutePath)), new LogEventProperty("StatusCode", new ScalarValue((int)statusCode)), new LogEventProperty("Elapsed", new ScalarValue(TimeSpan.FromTicks(elapsedTicks).TotalMilliseconds)) }); var messageTemplate = new MessageTemplateParser().Parse(DefaultRequestCompletionMessageTemplate); var evt = new LogEvent(DateTimeOffset.Now, LogLevelDefault, null, messageTemplate, properties); logger.Write(evt); return(false); }
public void Should_format_message_with_source_context() { var properties = new List <LogEventProperty> { new LogEventProperty("SourceContext", new ScalarValue(@"Test.Cont""ext")) }; var template = new MessageTemplateParser().Parse("This is a test message"); var warnEvent = new LogEvent(this.timestamp, LogEventLevel.Warning, null, template, properties); var formatted = this.formatter.FormatMessage(warnEvent); Console.WriteLine("RFC3164 with source context: " + formatted); var match = this.regex.Match(formatted); match.Success.ShouldBeTrue(); match.Groups["pri"].Value.ShouldBe("<12>"); match.Groups["timestamp"].Value.ShouldBe("Dec 19 04:01:02"); match.Groups["host"].Value.ShouldBe(Host); match.Groups["proc"].Value.ToInt().ShouldBeGreaterThan(0); // Spaces and anything other than printable ASCII should have been removed, and should have // been truncated to 32 chars match.Groups["app"].Value.ShouldBe("TestAppWithAVeryLongNameThatShou"); // Ensure that we busted the source context out of its enclosing quotes, and that we unescaped // any other quotes match.Groups["msg"].Value.ShouldBe("[Test.Cont\"ext] This is a test message"); }
public void MatchFormat() { var stream = new MemoryStream(); TextWriter writer = new StreamWriter(stream); var config = new RedisConfiguration(); config.MetaProperties.Add("_index_name", "MyIndex"); var formatter = new RedisCompactJsonFormatter(new FormatterConfiguration(), config); var template = new MessageTemplateParser().Parse("{Song}++ @{Complex}"); var dt = new DateTimeOffset(2001, 2, 3, 4, 5, 6, TimeSpan.Zero); var properties = new List <LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) }; var logEvent = new LogEvent(dt, LogEventLevel.Information, null, template, properties); formatter.Format(logEvent, writer); writer.Flush(); stream.Position = 0; var reader = new StreamReader(stream); var result = reader.ReadToEnd(); this.Assent(result); }
public void WhenUsingConnectionStringInCtorInternalDocumentStoreIsCreated() { var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10)); var exception = new ArgumentException("Mládek"); const LogEventLevel level = LogEventLevel.Information; const string messageTemplate = "{Song}++"; var properties = new List <LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) }; var events = new Dictionary <string, LogEvent>(); using (var store = Raven.Embedded.EmbeddedServer.Instance.GetDocumentStore(nameof(WhenUsingConnectionStringInCtorInternalDocumentStoreIsCreated))) { store.OnBeforeStore += (sender, e) => events[e.DocumentId] = (LogEvent)e.Entity; store.Initialize(); using (var ravenSink = new RavenDBSink(store, 2, TinyWait, null)) { var template = new MessageTemplateParser().Parse(messageTemplate); var logEvent = new Events.LogEvent(timestamp, level, exception, template, properties); ravenSink.Emit(logEvent); } Assert.AreEqual(1, events.Count); var single = events.First().Value; Assert.AreEqual(messageTemplate, single.MessageTemplate); Assert.AreEqual("\"New Macabre\"++", single.RenderedMessage); Assert.AreEqual(timestamp, single.Timestamp); Assert.AreEqual(level, single.Level); Assert.AreEqual(1, single.Properties.Count); Assert.AreEqual("New Macabre", single.Properties["Song"]); Assert.AreEqual(exception.Message, single.Exception.Message); } }
string GetJsonEventFile(Event <LogEventData> evt, string issueNumber) { var parser = new MessageTemplateParser(); var properties = (evt.Data.Properties ?? new Dictionary <string, object>()).Select( kvp => CreateProperty(kvp.Key, kvp.Value)); var logEvent = new LogEvent( evt.Data.LocalTimestamp, (Serilog.Events.LogEventLevel)Enum.Parse(typeof(Serilog.Events.LogEventLevel), evt.Data.Level.ToString()), evt.Data.Exception != null ? new WrappedException(evt.Data.Exception) : null, parser.Parse(evt.Data.MessageTemplate), properties); string logFilePath = Path.Combine(App.StoragePath, string.Format($"SeqAppYouTrack-{issueNumber}.json")); using (var jsonSink = new FileSink(logFilePath, new JsonFormatter(), null)) { var logger = new LoggerConfiguration().WriteTo.Sink(jsonSink, Serilog.Events.LogEventLevel.Verbose) .CreateLogger(); logger.Write(logEvent); } return(logFilePath); }
public ReceiveMessageBehavior(LogBuilder logBuilder) { var templateParser = new MessageTemplateParser(); messageTemplate = templateParser.Parse("Receive message {MessageType} {MessageId}."); logger = logBuilder.GetLogger("NServiceBus.Serilog.MessageReceived"); }
public SendMessageBehavior(LogBuilder logBuilder) { var templateParser = new MessageTemplateParser(); logger = logBuilder.GetLogger("NServiceBus.Serilog.MessageSent"); messageTemplate = templateParser.Parse("Sent message {MessageType} {MessageId}."); }
public async Task UsesCustomPropertyNames() { try { await this.ThrowAsync(); } catch (Exception e) { var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10)); var messageTemplate = "{Song}++"; var template = new MessageTemplateParser().Parse(messageTemplate); using (var sink = new ElasticsearchSink(_options)) { var properties = new List <LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")), new LogEventProperty("Complex", new ScalarValue(new { A = 1, B = 2 })) }; var logEvent = new LogEvent(timestamp, LogEventLevel.Information, e, template, properties); //one off sink.Emit(logEvent); sink.Emit(logEvent); logEvent = new LogEvent(timestamp.AddDays(2), LogEventLevel.Information, e, template, properties); sink.Emit(logEvent); } var bulkJsonPieces = this.AssertSeenHttpPosts(_seenHttpPosts, 4); bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-2013.05.28"); bulkJsonPieces[1].Should().Contain("New Macabre"); bulkJsonPieces[1].Should().NotContain("Properties\""); bulkJsonPieces[1].Should().Contain("fields\":{"); bulkJsonPieces[1].Should().Contain("@timestamp"); bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-2013.05.30"); } }
private static MessageTemplate CreateTemplate() { var parser = new MessageTemplateParser(); var parsed = parser.Parse("{Message}"); return(parsed); }
public async Task WhenABatchLoggerWritesToTheSinkItStoresAllTheEntriesInDifferentPartitions() { var storageAccount = CloudStorageAccount.DevelopmentStorageAccount; var tableClient = storageAccount.CreateCloudTableClient(); var table = tableClient.GetTableReference("LogEventEntity"); await table.DeleteIfExistsAsync(); using (var sink = new AzureBatchingTableStorageWithPropertiesSink(storageAccount, null, 1000, TimeSpan.FromMinutes(1))) { var messageTemplate = "Some text"; var template = new MessageTemplateParser().Parse(messageTemplate); var properties = new List <LogEventProperty>(); for (int k = 0; k < 4; ++k) { var timestamp = new DateTimeOffset(2014, 12, 01, 1 + k, 42, 20, 666, TimeSpan.FromHours(2)); for (int i = 0; i < 2; ++i) { sink.Emit(new Events.LogEvent(timestamp, LogEventLevel.Information, null, template, properties)); } } } var result = await TableQueryTakeDynamicAsync(table, takeCount : 9); Assert.Equal(8, result.Count); }
public void WnenAnErrorEventIsWrittenWithExpirationItHasProperMetadata() { using (var documentStore = Raven.Embedded.EmbeddedServer.Instance.GetDocumentStore(nameof(WhenErrorExpirationSetToInfiniteErrorsDontExpire))) { documentStore.Initialize(); var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10)); var errorExpiration = TimeSpan.FromDays(1); var expiration = TimeSpan.FromMinutes(15); var targetExpiration = DateTime.UtcNow.Add(errorExpiration); var exception = new ArgumentException("Mládek"); const LogEventLevel level = LogEventLevel.Error; const string messageTemplate = "{Song}++"; var properties = new List <LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) }; using (var ravenSink = new RavenDBSink(documentStore, 2, TinyWait, null, expiration: expiration, errorExpiration: errorExpiration)) { var template = new MessageTemplateParser().Parse(messageTemplate); var logEvent = new Events.LogEvent(timestamp, level, exception, template, properties); ravenSink.Emit(logEvent); } using (var session = documentStore.OpenSession()) { var logEvent = session.Query <LogEvent>().Customize(x => x.WaitForNonStaleResults()).First(); var metaData = session.Advanced.GetMetadataFor(logEvent)[RavenDBSink.RavenExpirationDate].ToString(); var actualExpiration = Convert.ToDateTime(metaData).ToUniversalTime(); Assert.GreaterOrEqual(actualExpiration, targetExpiration, "The document should expire on or after {0} but expires {1}", targetExpiration, actualExpiration); } } }
static LoggerAdapter() { var parser = new MessageTemplateParser(); _traceEnterTemplate = parser.Parse("Entered into {MethodName} ({CallingParameters})."); _traceLeaveTemplate = parser.Parse("Returned from {MethodName} ({ReturnValue}). Time taken: {TimeTaken:0.00} ms."); }
public void Should_format_message_with_structured_data() { const string testVal = "A Value"; var properties = new List <LogEventProperty> { new LogEventProperty("AProperty", new ScalarValue(testVal)), new LogEventProperty("AnotherProperty", new ScalarValue("AnotherValue")), new LogEventProperty("SourceContext", new ScalarValue(SOURCE_CONTEXT)) }; var template = new MessageTemplateParser().Parse("This is a test message with val {AProperty}"); var ex = new ArgumentException("Test"); var warnEvent = new LogEvent(this.timestamp, LogEventLevel.Warning, ex, template, properties); var formatted = this.formatter.FormatMessage(warnEvent); this.output.WriteLine($"RFC5424 with structured data: {formatted}"); var match = this.regex.Match(formatted); match.Success.ShouldBeTrue(); match.Groups["pri"].Value.ShouldBe("<12>"); match.Groups["ver"].Value.ShouldBe("1"); match.Groups["timestamp"].Value.ShouldBe($"2013-12-19T04:01:02.357852{this.timestamp:zzz}"); match.Groups["app"].Value.ShouldBe(APP_NAME); match.Groups["host"].Value.ShouldBe(Host); match.Groups["proc"].Value.ToInt().ShouldBeGreaterThan(0); match.Groups["msgid"].Value.ShouldBe(SOURCE_CONTEXT); match.Groups["sd"].Value.ShouldNotBe(NILVALUE); match.Groups["msg"].Value.ShouldBe($"This is a test message with val \"{testVal}\""); }
public void Should_clean_invalid_strings() { var properties = new List <LogEventProperty> { new LogEventProperty("安森Test", new ScalarValue(@"test")), new LogEventProperty("APropertyNameThatIsLongerThan32Characters", new ScalarValue(@"A value \contain]ing ""quotes"" to test")), new LogEventProperty("SourceContext", new ScalarValue("安森 A string that is longer than 32 characters")) }; var template = new MessageTemplateParser().Parse("This is a test message"); var infoEvent = new LogEvent(this.timestamp, LogEventLevel.Information, null, template, properties); var formatted = this.formatter.FormatMessage(infoEvent); this.output.WriteLine($"RFC5424: {formatted}"); var match = this.regex.Match(formatted); match.Success.ShouldBeTrue(); match.Groups["msgid"].Value.Length.ShouldBe(32); // Spaces and anything other than printable ASCII should have been removed match.Groups["msgid"].Value.ShouldStartWith("Astringthatis"); // '"', '\' and ']' in property values should have been escaped with a backslash '\' Regex.IsMatch(match.Groups["sd"].Value, @"\\\\contain\\]ing\s\\""quotes\\""").ShouldBeTrue(); // Property names have had spaces and anything other than printable ASCII should have been removed, // and should have been truncated to 32 chars Regex.IsMatch(match.Groups["sd"].Value, @"APropertyNameThatIsLongerThan32C="".*""\s").ShouldBeTrue(); }
public void Should_format_message_without_structured_data() { var template = new MessageTemplateParser().Parse("This is a test message"); var infoEvent = new LogEvent(this.timestamp, LogEventLevel.Information, null, template, Enumerable.Empty <LogEventProperty>()); var formatted = this.formatter.FormatMessage(infoEvent); this.output.WriteLine($"RFC5424 without structured data: {formatted}"); var match = this.regex.Match(formatted); match.Success.ShouldBeTrue(); match.Groups["pri"].Value.ShouldBe("<14>"); match.Groups["ver"].Value.ShouldBe("1"); match.Groups["timestamp"].Value.ShouldBe($"2013-12-19T04:01:02.357852{this.timestamp:zzz}"); match.Groups["app"].Value.ShouldBe(APP_NAME); match.Groups["host"].Value.ShouldBe(Host); match.Groups["proc"].Value.ToInt().ShouldBeGreaterThan(0); match.Groups["msgid"].Value.ShouldBe(NILVALUE); match.Groups["sd"].Value.ShouldBe(NILVALUE); match.Groups["msg"].Value.ShouldBe("This is a test message"); this.output.WriteLine($"FORMATTED: {formatted}"); }
public void CreateEntityWithPropertiesShouldSupportAzureTableTypesForDictionary() { var messageTemplate = "{Dictionary}"; var dict1 = new DictionaryValue(new List <KeyValuePair <ScalarValue, LogEventPropertyValue> > { new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d1k1"), new ScalarValue("d1k1v1")), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d1k2"), new ScalarValue("d1k2v2")), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d1k3"), new ScalarValue("d1k3v3")), }); var dict2 = new DictionaryValue(new List <KeyValuePair <ScalarValue, LogEventPropertyValue> > { new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d2k1"), new ScalarValue("d2k1v1")), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d2k2"), new ScalarValue("d2k2v2")), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d2k3"), new ScalarValue("d2k3v3")), }); var dict0 = new DictionaryValue(new List <KeyValuePair <ScalarValue, LogEventPropertyValue> > { new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d1"), dict1), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d2"), dict2), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d0"), new ScalarValue(0)) }); var properties = new List <LogEventProperty> { new LogEventProperty("Dictionary", dict0) }; var template = new MessageTemplateParser().Parse(messageTemplate); var logEvent = new Events.LogEvent(DateTime.Now, LogEventLevel.Information, null, template, properties); var entity = AzureTableStorageEntityFactory.CreateEntityWithProperties(logEvent, null, null, new PropertiesKeyGenerator()); Assert.Equal(3 + properties.Count, entity.Properties.Count); Assert.Equal("[(\"d1\": [(\"d1k1\": \"d1k1v1\"), (\"d1k2\": \"d1k2v2\"), (\"d1k3\": \"d1k3v3\")]), (\"d2\": [(\"d2k1\": \"d2k1v1\"), (\"d2k2\": \"d2k2v2\"), (\"d2k3\": \"d2k3v3\")]), (\"d0\": 0)]", entity.Properties["Dictionary"].StringValue); }
public void CreateEntityWithPropertiesShouldGenerateValidRowKey() { var timestamp = new DateTimeOffset(2014, 12, 01, 18, 42, 20, 666, TimeSpan.FromHours(2)); var exception = new ArgumentException("Some exceptional exception happened"); var level = LogEventLevel.Information; var additionalRowKeyPostfix = "POSTFIX"; var postLength = additionalRowKeyPostfix.Length + 1 + Guid.NewGuid().ToString().Length; var messageSpace = 1024 - (level.ToString().Length + 1) - (1 + postLength); // Message up to available space, plus some characters (Z) that will be removed var messageTemplate = new string('x', messageSpace - 4) + "ABCD" + new string('Z', 20); var template = new MessageTemplateParser().Parse(messageTemplate); var properties = new List <LogEventProperty>(); var logEvent = new Events.LogEvent(timestamp, level, exception, template, properties); var entity = AzureTableStorageEntityFactory.CreateEntityWithProperties(logEvent, null, additionalRowKeyPostfix, new PropertiesKeyGenerator()); // Row Key var expectedRowKeyWithoutGuid = "Information|" + new string('x', messageSpace - 4) + "ABCD|POSTFIX|"; var rowKeyWithoutGuid = entity.RowKey.Substring(0, expectedRowKeyWithoutGuid.Length); var rowKeyGuid = entity.RowKey.Substring(expectedRowKeyWithoutGuid.Length); Assert.Equal(1024, entity.RowKey.Length); Assert.Equal(expectedRowKeyWithoutGuid, rowKeyWithoutGuid); Guid.Parse(rowKeyGuid); Assert.Equal(Guid.Parse(rowKeyGuid).ToString(), rowKeyGuid); Assert.DoesNotContain("Z", entity.RowKey); }
public void WhenErrorExpirationSetToInfiniteErrorsDontExpire() { using (var documentStore = Raven.Embedded.EmbeddedServer.Instance.GetDocumentStore(nameof(WhenErrorExpirationSetToInfiniteErrorsDontExpire))) { documentStore.Initialize(); var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10)); var errorExpiration = Timeout.InfiniteTimeSpan; var targetExpiration = DateTime.UtcNow.Add(errorExpiration); var exception = new ArgumentException("Mládek"); const LogEventLevel level = LogEventLevel.Information; const string messageTemplate = "{Song}++"; var properties = new List <LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) }; using (var ravenSink = new RavenDBSink(documentStore, 2, TinyWait, null, errorExpiration: errorExpiration)) { var template = new MessageTemplateParser().Parse(messageTemplate); var logEvent = new Events.LogEvent(timestamp, level, exception, template, properties); ravenSink.Emit(logEvent); } using (var session = documentStore.OpenSession()) { var logEvent = session.Query <LogEvent>().Customize(x => x.WaitForNonStaleResults()).First(); Assert.IsFalse(session.Advanced.GetMetadataFor(logEvent).ContainsKey(RavenDBSink.RavenExpirationDate), "No expiration set"); } } }
public void WhenNoExpirationIsProvidedMessagesDontExpire() { const string databaseName = nameof(WhenNoExpirationIsProvidedMessagesDontExpire); using (var documentStore = Raven.Embedded.EmbeddedServer.Instance.GetDocumentStore(databaseName)) { documentStore.Initialize(); var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10)); var exception = new ArgumentException("Mládek"); const LogEventLevel level = LogEventLevel.Error; const string messageTemplate = "{Song}++"; var properties = new List <LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) }; using (var ravenSink = new RavenDBSink(documentStore, 2, TinyWait, null)) { var template = new MessageTemplateParser().Parse(messageTemplate); var logEvent = new Events.LogEvent(timestamp, level, exception, template, properties); ravenSink.Emit(logEvent); } using (var session = documentStore.OpenSession()) { var logEvent = session.Query <LogEvent>().Customize(x => x.WaitForNonStaleResults()).First(); Assert.False(session.Advanced.GetMetadataFor(logEvent).ContainsKey(Constants.Documents.Metadata.Expires), "No expiration set"); } documentStore.Maintenance.Server.Send(new DeleteDatabasesOperation(databaseName, hardDelete: true, fromNode: null, timeToWaitForConfirmation: null)); } }
public override void Log(LogLevel level, Exception exception, string message, params object[] parameters) { var parser = new MessageTemplateParser(); var template = parser.Parse(message); var format = new StringBuilder(); var index = 0; foreach (var tok in template.Tokens) { if (tok is TextToken) { format.Append(tok); } else { format.Append("{" + index++ + "}"); } } var netStyle = format.ToString(); Console.WriteLine($"[{level}] {string.Format(netStyle, parameters)}"); if (exception != null) { Console.WriteLine($"\t {exception}"); } }
public async Task UsesCustomPropertyNames() { try { await new HttpClient().GetStringAsync("http://i.do.not.exist"); } catch (Exception e) { var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10)); var messageTemplate = "{Song}++"; var template = new MessageTemplateParser().Parse(messageTemplate); using (var sink = new ElasticsearchSink(_options)) { var properties = new List <LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")), new LogEventProperty("Complex", new ScalarValue(new { A = 1, B = 2 })) }; var logEvent = new LogEvent(timestamp, LogEventLevel.Information, e, template, properties); sink.Emit(logEvent); logEvent = new LogEvent(timestamp.AddDays(2), LogEventLevel.Information, e, template, properties); sink.Emit(logEvent); } _seenHttpPosts.Should().NotBeEmpty().And.HaveCount(1); var json = _seenHttpPosts.First(); var bulkJsonPieces = json.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); bulkJsonPieces.Should().HaveCount(4); bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-2013.05.28"); bulkJsonPieces[1].Should().Contain("New Macabre"); bulkJsonPieces[1].Should().NotContain("Properties\""); bulkJsonPieces[1].Should().Contain("fields\":{"); bulkJsonPieces[1].Should().Contain("@timestamp"); bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-2013.05.30"); } }
public MessageTemplateCache(MessageTemplateParser innerParser) { if (innerParser == null) { throw new ArgumentNullException("innerParser"); } _innerParser = innerParser; }
static IEnumerable <LogEventProperty> Capture(string messageTemplate, params object[] properties) { var mt = new MessageTemplateParser().Parse(messageTemplate); var binder = new PropertyBinder( new PropertyValueConverter(10, 1000, 1000, Enumerable.Empty <Type>(), Enumerable.Empty <IDestructuringPolicy>(), false)); return(binder.ConstructProperties(mt, properties).Select(p => new LogEventProperty(p.Name, p.Value))); }
public CaptureSagaStateBehavior(LogBuilder logBuilder) { var templateParser = new MessageTemplateParser(); messageTemplate = templateParser.Parse("Saga execution '{SagaType}' '{SagaId}'."); logger = logBuilder.GetLogger("NServiceBus.Serilog.SagaAudit"); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //loggerFactory // .AddConsole(Configuration.GetSection("Logging")) // .AddDebug(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.ColoredConsole(LogEventLevel.Verbose, "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{OzzyEvent}") .CreateLogger(); var listener = new ObservableEventListener(); listener.EnableEvents(OzzyLogger <ICommonEvents> .LogEventSource, EventLevel.LogAlways); listener.EnableEvents(OzzyLogger <IDomainModelTracing> .LogEventSource, EventLevel.Informational); listener.EnableEvents(OzzyLogger <IDistibutedLockEvents> .LogEventSource, EventLevel.LogAlways); var log = loggerFactory.CreateLogger <OzzyLoggerValue>(); var parser = new MessageTemplateParser(); listener.Subscribe(new SimpleEventObserver(e => { var logEntry = new LogEvent(DateTime.UtcNow, GetSerilogLevel(e.Level), null, new MessageTemplate(new MessageTemplateToken[] { new TextToken(string.Format(e.Message, e.Payload.ToArray()), 0) }), e.Payload.Select((p, i) => new LogEventProperty(e.PayloadNames[i], new ScalarValue(p))).Append(new LogEventProperty("OzzyEvent", new OzzyDictionaryValue(e))) ); Log.Logger.Write(logEntry); //log.Log(LogLevel.Information, new EventId(e.EventId), e, null, (s, ex) => string.Format(s.Message, s.Payload.ToArray())); })); //if (env.IsDevelopment()) //{ // app.UseDeveloperExceptionPage(); // app.UseBrowserLink(); //} //else //{ // app.UseExceptionHandler("/Home/Error"); //} //app.UseStaticFiles(); app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseOzzy().Start(); }
public static Action ProcessContext( [NotNull] HighlightingProlongedLifetime prolongedLifetime, [NotNull][ContextKey(typeof(ContextHighlighterPsiFileView.ContextKey))] IPsiDocumentRangeView psiDocumentRangeView, MessageTemplateParser messageTemplate) { return(new TemplateFormatItemAndMatchingArgumentHighlighter(messageTemplate).GetDataProcessAction( prolongedLifetime, psiDocumentRangeView)); }
public void MessageTemplatesAreRendered() { const string format = "Hello, {Name}!"; var mt = new MessageTemplateParser().Parse(format); var lv = new SerilogLogValues(mt, new Dictionary <string, LogEventPropertyValue> { ["Name"] = new ScalarValue("World") }); Assert.Equal("Hello, \"World\"!", lv.ToString()); }
public void Should_format_message() { const string message = "This is a test message"; var template = new MessageTemplateParser().Parse(message); var infoEvent = new LogEvent(DateTimeOffset.Now, LogEventLevel.Information, null, template, Enumerable.Empty<LogEventProperty>()); var formatted = this.formatter.FormatMessage(infoEvent); formatted.ShouldBe(message); }
public void OriginalFormatIsExposed() { const string format = "Hello, {Name}!"; var mt = new MessageTemplateParser().Parse(format); var lv = new SerilogLogValues(mt, new Dictionary <string, LogEventPropertyValue>()); var kvp = lv.Single(); Assert.Equal("{OriginalFormat}", kvp.Key); Assert.Equal(format, kvp.Value); }
public MessageTemplateParserTests() { _kernel = A.Fake<IKernel>(); _messageTemplateParser = new MessageTemplateParser(_kernel); }