Parses message template strings into sequences of text or property tokens.
Inheritance: IMessageTemplateParser
Exemplo n.º 1
0
        public void WhenAnEventIsWrittenToTheSinkItIsRetrievableFromTheDocumentStore()
        {
            using (var documentStore = new EmbeddableDocumentStore {RunInMemory = true}.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.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))
                {
                    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 events = session.Query<LogEvent>().Customize(x => x.WaitForNonStaleResults()).ToList();
                    Assert.AreEqual(1, events.Count);
                    var single = events.Single();
                    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);
                }
            }
        }
        public void IndexDecider_EndsUpInTheOutput()
        {
            //DO NOTE that you cant send objects as scalar values through Logger.*("{Scalar}", {});
            var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
            const string messageTemplate = "{Song}++ @{Complex}";
            var template = new MessageTemplateParser().Parse(messageTemplate);
            _options.IndexDecider = (l, utcTime) => string.Format("logstash-{1}-{0:yyyy.MM.dd}", utcTime, l.Level.ToString().ToLowerInvariant());
            using (var sink = new ElasticsearchSink(_options))
            {
                var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };
                var e = new LogEvent(timestamp, LogEventLevel.Information, null, template, properties);
                sink.Emit(e);
                var exception = new ArgumentException("parameter");
                properties = new List<LogEventProperty>
                {
                    new LogEventProperty("Song", new ScalarValue("Old Macabre")),
                    new LogEventProperty("Complex", new ScalarValue(new { A  = 1, B = 2}))
                };
                e = new LogEvent(timestamp.AddYears(-2), LogEventLevel.Fatal, exception, template, properties);
                sink.Emit(e);
            }

            _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-information-2013.05.28");
            bulkJsonPieces[1].Should().Contain("New Macabre");
            bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-fatal-2011.05.28");
            bulkJsonPieces[3].Should().Contain("Old Macabre");

            //serilog by default simpy .ToString()'s unknown objects
            bulkJsonPieces[3].Should().Contain("Complex\":\"{");

        }
 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 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);

			// 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.AreEqual(1024, entity.RowKey.Length);
			Assert.AreEqual(expectedRowKeyWithoutGuid, rowKeyWithoutGuid);
			Assert.DoesNotThrow(() => Guid.Parse(rowKeyGuid));
			Assert.AreEqual(Guid.Parse(rowKeyGuid).ToString(), rowKeyGuid);
			Assert.False(entity.RowKey.Contains('Z'));
		}
        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");
            }
        }
Exemplo n.º 6
0
        public void PropertyTest()
        {
            var properties = new List<LogEventProperty>();

            properties.Add(new LogEventProperty("activity", new ScalarValue("Activity")));
            properties.Add(new LogEventProperty("body", new ScalarValue("Body")));
            properties.Add(new LogEventProperty("icon", new ScalarValue("http://tinyurl.com/pn46fgp")));
            properties.Add(new LogEventProperty("title", new ScalarValue("Title")));

            var messageTemplate = new MessageTemplateParser().Parse("The value of the 'body' property: {body}");

            var logEvent = new LogEvent(DateTimeOffset.Now, LogEventLevel.Information, null, messageTemplate, properties);

            _logger.Write(logEvent);
        }
		public void CreateEntityWithPropertiesShouldGenerateValidEntity()
		{
			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 messageTemplate = "Template {Temp} {Prop}";
			var template = new MessageTemplateParser().Parse(messageTemplate);
			var properties = new List<LogEventProperty> {
				new LogEventProperty("Temp", new ScalarValue("Temporary")),
				new LogEventProperty("Prop", new ScalarValue("Property"))
			};
			var additionalRowKeyPostfix = "Some postfix";

			var logEvent = new Events.LogEvent(timestamp, level, exception, template, properties);

			var entity = AzureTableStorageEntityFactory.CreateEntityWithProperties(logEvent, null, additionalRowKeyPostfix);

			// Partition key
			var expectedPartitionKey = "0" + new DateTime(logEvent.Timestamp.Year, logEvent.Timestamp.Month, logEvent.Timestamp.Day, logEvent.Timestamp.Hour, logEvent.Timestamp.Minute, 0).Ticks;
			Assert.AreEqual(expectedPartitionKey, entity.PartitionKey);

			// Row Key
			var expectedRowKeyWithoutGuid = "Information|Template {Temp} {Prop}|Some postfix|";
			var rowKeyWithoutGuid = entity.RowKey.Substring(0, expectedRowKeyWithoutGuid.Length);
			var rowKeyGuid = entity.RowKey.Substring(expectedRowKeyWithoutGuid.Length);

			Assert.AreEqual(expectedRowKeyWithoutGuid, rowKeyWithoutGuid);
			Assert.DoesNotThrow(() => Guid.Parse(rowKeyGuid));
			Assert.AreEqual(Guid.Parse(rowKeyGuid).ToString(), rowKeyGuid);

			// Timestamp
			Assert.AreEqual(logEvent.Timestamp, entity.Timestamp);

			// Properties
			Assert.AreEqual(6, entity.Properties.Count);

			Assert.AreEqual(new EntityProperty(messageTemplate), entity.Properties["MessageTemplate"]);
			Assert.AreEqual(new EntityProperty("Information"), entity.Properties["Level"]);
			Assert.AreEqual(new EntityProperty("Template \"Temporary\" \"Property\""), entity.Properties["RenderedMessage"]);
			Assert.AreEqual(new EntityProperty(exception.ToString()), entity.Properties["Exception"]);
			Assert.AreEqual(new EntityProperty("Temporary"), entity.Properties["Temp"]);
			Assert.AreEqual(new EntityProperty("Property"), entity.Properties["Prop"]);
		}
        public async Task WhenPassingASerializer_ShouldExpandToJson()
        {
            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);
                _options.Serializer = new ElasticsearchJsonNetSerializer();
                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, null, 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[2].Should().Contain(@"""_index"":""logstash-2013.05.30");

                //since we pass a serializer objects should serialize as json object and not using their
                //tostring implemenation
                //DO NOTE that you cant send objects as scalar values through Logger.*("{Scalar}", {});
                bulkJsonPieces[3].Should().Contain("Complex\":{");
                bulkJsonPieces[3].Should().Contain("exceptions\":[{");
            }
        }
        public async Task WhenPassingASerializer_ShouldExpandToJson()
        {
            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, null, 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[2].Should().Contain(@"""_index"":""logstash-2013.05.30");

                //since we pass a serializer objects should serialize as json object and not using their
                //tostring implemenation
                //DO NOTE that you cant send objects as scalar values through Logger.*("{Scalar}", {});
                bulkJsonPieces[3].Should().Contain("Complex\":{");
                bulkJsonPieces[3].Should().Contain("exceptions\":[{");
            }
        }
        public void CustomIndex_And_TypeName_EndsUpInTheOutput()
        {
            //DO NOTE that you cant send objects as scalar values through Logger.*("{Scalar}", {});
            var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
            const string messageTemplate = "{Song}++ @{Complex}";
            var template = new MessageTemplateParser().Parse(messageTemplate);
            _options.TypeName = "custom-event-type";
            _options.IndexFormat = "event-index-{0:yyyy.MM.dd}";
            using (var sink = new ElasticsearchSink(_options))
            {
                var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };
                var e = new LogEvent(timestamp, LogEventLevel.Information, null, template, properties);
                //one off
                sink.Emit(e);

                sink.Emit(e);
                var exception = new ArgumentException("parameter");
                properties = new List<LogEventProperty>
                {
                    new LogEventProperty("Song", new ScalarValue("Old Macabre")),
                    new LogEventProperty("Complex", new ScalarValue(new { A  = 1, B = 2}))
                };
                e = new LogEvent(timestamp.AddYears(-2), LogEventLevel.Fatal, exception, template, properties);
                sink.Emit(e);
            }

            var bulkJsonPieces = this.AssertSeenHttpPosts(_seenHttpPosts, 4);

            bulkJsonPieces.Should().HaveCount(4);
            bulkJsonPieces[0].Should().Contain(@"""_index"":""event-index-2013.05.28");
            bulkJsonPieces[0].Should().Contain(@"""_type"":""custom-event-type");
            bulkJsonPieces[1].Should().Contain("New Macabre");
            bulkJsonPieces[2].Should().Contain(@"""_index"":""event-index-2011.05.28");
            bulkJsonPieces[2].Should().Contain(@"""_type"":""custom-event-type");
            bulkJsonPieces[3].Should().Contain("Old Macabre");

            bulkJsonPieces[3].Should().Contain("Complex\":{");
        }
		public void CreateEntityWithPropertiesShouldSupportAzureTableTypesForScalar()
		{
			var messageTemplate = "{ByteArray} {Boolean} {DateTime} {DateTimeOffset} {Double} {Guid} {Int} {Long} {String}";
			var bytearrayValue = new byte[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 250, 251, 252, 253, 254, 255 };
			var booleanValue = true;
			var datetimeValue = DateTime.UtcNow;
			var datetimeoffsetValue = new DateTimeOffset(datetimeValue, TimeSpan.FromHours(0));
			var doubleValue = Math.PI;
			var guidValue = Guid.NewGuid();
			var intValue = int.MaxValue;
			var longValue = long.MaxValue;
			var stringValue = "Some string value";

			var properties = new List<LogEventProperty> {
				new LogEventProperty("ByteArray", new ScalarValue(bytearrayValue)),
				new LogEventProperty("Boolean", new ScalarValue(booleanValue)),
				new LogEventProperty("DateTime", new ScalarValue(datetimeValue)),
				new LogEventProperty("DateTimeOffset", new ScalarValue(datetimeoffsetValue)),
				new LogEventProperty("Double", new ScalarValue(doubleValue)),
				new LogEventProperty("Guid", new ScalarValue(guidValue)),
				new LogEventProperty("Int", new ScalarValue(intValue)),
				new LogEventProperty("Long", new ScalarValue(longValue)),
				new LogEventProperty("String", new ScalarValue(stringValue))
			};

			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);

			Assert.AreEqual(3 + properties.Count, entity.Properties.Count);

			Assert.IsInstanceOf(typeof(byte[]), entity.Properties["ByteArray"].BinaryValue);
			Assert.AreEqual(bytearrayValue, entity.Properties["ByteArray"].BinaryValue);
			Assert.AreEqual(booleanValue, entity.Properties["Boolean"].BooleanValue);
			Assert.AreEqual(datetimeValue, entity.Properties["DateTime"].DateTime);
			Assert.AreEqual(datetimeoffsetValue, entity.Properties["DateTimeOffset"].DateTimeOffsetValue);
			Assert.AreEqual(doubleValue, entity.Properties["Double"].DoubleValue);
			Assert.AreEqual(guidValue, entity.Properties["Guid"].GuidValue);
			Assert.AreEqual(intValue, entity.Properties["Int"].Int32Value);
			Assert.AreEqual(longValue, entity.Properties["Long"].Int64Value);
			Assert.AreEqual(stringValue, entity.Properties["String"].StringValue);
		}
		public void CreateEntityWithPropertiesShouldNotAddMoreThan252Properties()
		{
			var messageTemplate = string.Empty;

			var properties = new List<LogEventProperty>();

			for (var i = 0; i < 300; ++i)
			{
				var propName = "Prop" + i;
				properties.Add(new LogEventProperty(propName, new ScalarValue(i)));

				messageTemplate += string.Format("{{{0}}}", propName);
			};

			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);

			Assert.AreEqual(252, entity.Properties.Count);
			Assert.Contains("AggregatedProperties", entity.Properties.Keys.ToList());
		}
		public void CreateEntityWithPropertiesShouldSupportAzureTableTypesForSequence()
		{
			var messageTemplate = "{Sequence}";

			var sequence1 = new SequenceValue(new List<LogEventPropertyValue>
			{
				new ScalarValue(1),
				new ScalarValue(2),
				new ScalarValue(3),
				new ScalarValue(4),
				new ScalarValue(5)
			});

			var sequence2 = new SequenceValue(new List<LogEventPropertyValue>
			{
				new ScalarValue("a"),
				new ScalarValue("b"),
				new ScalarValue("c"),
				new ScalarValue("d"),
				new ScalarValue("e")
			});

			var sequence0 = new SequenceValue(new List<LogEventPropertyValue>
			{
				sequence1,
				sequence2
			});

			var properties = new List<LogEventProperty> {
				new LogEventProperty("Sequence", sequence0)
			};

			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);

			Assert.AreEqual(3 + properties.Count, entity.Properties.Count);
			Assert.AreEqual("[[1, 2, 3, 4, 5], [\"a\", \"b\", \"c\", \"d\", \"e\"]]", entity.Properties["Sequence"].StringValue);
		}
Exemplo n.º 14
0
        public void PropertyTokensWithoutFormatStringsAreNotIncludedAsRenderings()
        {
            var p = new MessageTemplateParser();
            var e = new LogEvent(Some.OffsetInstant(), LogEventLevel.Information, null,
                p.Parse("{AProperty}"), new[] { new LogEventProperty("AProperty", new ScalarValue(12)) });

            var d = FormatEvent(e);

            var rs = ((IEnumerable)d.Renderings);
            Assert.IsNull(rs);
        }
 static IEnumerable<LogEventProperty> Capture(string messageTemplate, params object[] properties)
 {
     var mt = new MessageTemplateParser().Parse(messageTemplate);
     var binder = new PropertyBinder(
         new PropertyValueConverter(10, Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false));
     return binder.ConstructProperties(mt, properties);
 }
Exemplo n.º 16
0
 static string Render(IFormatProvider formatProvider,
     string messageTemplate, params object[] properties)
 {
     var mt = new MessageTemplateParser().Parse(messageTemplate);
     var binder = new PropertyBinder(new PropertyValueConverter(10, Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>()));
     var props = binder.ConstructProperties(mt, properties);
     var output = new StringBuilder();
     var writer = new StringWriter(output);
     var dict = System.Collections.Generic.Net40ReadOnlyDictionaryExtensions
         .ToDictionary40(props, p => p.Name, p => p.Value);
     mt.Render(dict, writer, formatProvider);
     writer.Flush();
     return output.ToString();
 }
Exemplo n.º 17
0
        public void SequencesOfSequencesAreSerialized()
        {
            var p = new MessageTemplateParser();
            var e = new LogEvent(Some.OffsetInstant(), LogEventLevel.Information, null,
                p.Parse("{@AProperty}"), new[] { new LogEventProperty("AProperty", new SequenceValue(new[] { new SequenceValue(new[] { new ScalarValue("Hello") }) })) });

            var d = FormatEvent(e);

            var h = (string)d.Properties.AProperty[0][0];
            Assert.AreEqual("Hello", h);
        }
 public void Setup()
 {
     _parser = new MessageTemplateParser();
 }
Exemplo n.º 19
0
 public MessageTemplateCache(MessageTemplateParser innerParser)
 {
     if (innerParser == null) throw new ArgumentNullException("innerParser");
     _innerParser = innerParser;
 }
		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);

			Assert.AreEqual(3 + properties.Count, entity.Properties.Count);
			Assert.AreEqual("[(\"d1\": [(\"d1k1\": \"d1k1v1\"), (\"d1k2\": \"d1k2v2\"), (\"d1k3\": \"d1k3v3\")]), (\"d2\": [(\"d2k1\": \"d2k1v1\"), (\"d2k2\": \"d2k2v2\"), (\"d2k3\": \"d2k3v3\")]), (\"d0\": 0)]", entity.Properties["Dictionary"].StringValue);
		}
		public void WhenABatchLoggerWritesToTheSinkItStoresAllTheEntriesInLargeNumber()
		{
			var storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
			var tableClient = storageAccount.CreateCloudTableClient();
			var table = tableClient.GetTableReference("LogEventEntity");

			table.DeleteIfExists();

			using (var sink = new AzureBatchingTableStorageWithPropertiesSink(storageAccount, null, 1000, TimeSpan.FromMinutes(1)))
			{
				var timestamp = new DateTimeOffset(2014, 12, 01, 18, 42, 20, 666, TimeSpan.FromHours(2));
				var messageTemplate = "Some text";
				var template = new MessageTemplateParser().Parse(messageTemplate);
				var properties = new List<LogEventProperty>();
				for (int i = 0; i < 300; ++i)
				{
					sink.Emit(new Events.LogEvent(timestamp, LogEventLevel.Information, null, template, properties));
				}
			}

			var result = table.ExecuteQuery(new TableQuery());
			Assert.AreEqual(300, result.Count());
		}
Exemplo n.º 22
0
        public void PropertyTokensWithFormatStringsAreIncludedAsRenderings()
        {
            var p = new MessageTemplateParser();
            var e = new LogEvent(Some.OffsetInstant(), LogEventLevel.Information, null,
                p.Parse("{AProperty:000}"), new[] { new LogEventProperty("AProperty", new ScalarValue(12)) });

            var d = FormatEvent(e);

            var rs = ((IEnumerable)d.Renderings).Cast<dynamic>().ToArray();
            Assert.AreEqual(1, rs.Count());
            var ap = d.Renderings.AProperty;
            var fs = ((IEnumerable)ap).Cast<dynamic>().ToArray();
            Assert.AreEqual(1, fs.Count());
            Assert.AreEqual("000", (string)fs.Single().Format);
            Assert.AreEqual("012", (string)fs.Single().Rendering);
        }