예제 #1
0
        public void PureSeriLogger_LogContext_CreateLogScope()
        {
            var          pureSeriLogContext = new PureSeriLogContext();
            const string testProperty       = "Property";
            const string testValue          = "Value";
            const string testLogMsg         = "Test Message";

            var logPropertyList = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>(testProperty, testValue)
            };

            using (TestCorrelator.CreateContext())
                using (pureSeriLogContext.CreateLogScope(logPropertyList))
                {
                    _pureSeriLogger.LogDebug(testLogMsg);

                    var currentTestContext = TestCorrelator.GetLogEventsFromCurrentContext().ToList();

                    currentTestContext.Should().ContainSingle().Which.Properties.ContainsKey(testProperty).Should().BeTrue();
                    currentTestContext.Should().ContainSingle().Which.Properties[testProperty].ToString().Should().Be(testValue.ToDoubleQuoted());

                    currentTestContext.Should().ContainSingle().Which.MessageTemplate.Text.Should().Be(testLogMsg);
                }
        }
        public void MultipleValueLogEventsIncludesProperties()
        {
            using (TestCorrelator.CreateContext())
            {
                var options = new SerilogMetricsReporterOptions {
                    LogEventLevel = LogEventLevel.Verbose
                };
                var writer     = new SerilogMetricSnapshotWriter(options);
                var columns    = new [] { "A", "B", "C" };
                var values     = new object[] { 1, 2, 3 };
                var metricTags = MetricTags.FromSetItemString("foo:10,bar:20");

                writer.Write("context", "name", columns, values, metricTags, DateTime.UtcNow);

                var tagsProperty = metricTags.Keys.Zip(metricTags.Values, (key, value) =>
                                                       new KeyValuePair <ScalarValue, LogEventPropertyValue>(
                                                           new ScalarValue(key), new ScalarValue(value)));

                var properties = new Dictionary <string, LogEventPropertyValue>()
                {
                    { "context", new ScalarValue("context") },
                    { "name", new ScalarValue("name") },
                    { "A", new ScalarValue(1) },
                    { "B", new ScalarValue(2) },
                    { "C", new ScalarValue(3) },
                    { "tags", new DictionaryValue(tagsProperty) }
                };

                TestCorrelator.GetLogEventsFromCurrentContext()
                .Should().ContainSingle()
                .Which.Properties.Should().BeEquivalentTo(properties);
            }
        }
        public async Task Run_ThrowsOnMigrationStoredProcedureMessage()
        {
            // Arrange
            List<dynamic> sqlResult = new List<object> { new { ErrorMessage = "Divide by zero error encountered." } };
            const string serialisedResult = "[{\"ErrorMessage\":\"Divide by zero error encountered.\"}]";

            SetupRepositoryMethods(migrationReturnResult: sqlResult.AsEnumerable());

            Log.Logger = new LoggerConfiguration().WriteTo.TestCorrelator().CreateLogger();
            using (TestCorrelator.CreateContext())
            {
                // Act
                var exception = await Assert.ThrowsAsync<ApplicationException>(async () =>
                    await _reportingDataRefreshJob.Run(null));

                // Assert
                Assert.Equal("Stored procedure did not execute successfully as result has messages, check the logs",
                    exception.Message);
                AssertRepositoryMethodsCalled(reportingCalled: false, specimenMatchingCalled: false);

                var logEvents = TestCorrelator.GetLogEventsFromCurrentContext().ToList();

                AssertContainsInfoMessages(logEvents, new[]
                {
                    "Starting migration uspGenerate",
                    $"Result: {serialisedResult}"
                });
                Assert.Contains(logEvents,
                    logEvent => logEvent.Level == LogEventLevel.Error
                                && logEvent.RenderMessage() == "Error occured during reporting data refresh job");
                AssertDoesNotContainInfoMessages(logEvents, new[] { "Starting specimen-matching uspGenerate", "Starting reporting uspGenerate", "Finishing reporting data refresh job" });
            }
        }
예제 #4
0
        public async Task Run_ThrowsOnRepositoryException()
        {
            // Arrange
            var expectedException = new ApplicationException("Connection was unsuccessful");

            _externalStoredProcedureRepository
            .Setup(r => r.ExecutePopulateForestExtractStoredProcedure())
            .Throws(expectedException);

            Log.Logger = new LoggerConfiguration().WriteTo.TestCorrelator().CreateLogger();
            using (TestCorrelator.CreateContext())
            {
                // Act
                var actualException = await Assert.ThrowsAsync <ApplicationException>(async() =>
                                                                                      await _reportingDataProcessingJob.Run(null));

                // Assert
                Assert.Equal(expectedException, actualException);

                var logEvents = TestCorrelator.GetLogEventsFromCurrentContext().ToList();

                Assert.Contains(logEvents,
                                logEvent => logEvent.Level == LogEventLevel.Error &&
                                logEvent.RenderMessage() == "Error occured during reporting data processing job" &&
                                logEvent.Exception == expectedException);
            }
        }
예제 #5
0
        public async Task Run_LogsSuccess()
        {
            // Arrange
            _externalStoredProcedureRepository
            .Setup(r => r.ExecutePopulateForestExtractStoredProcedure())
            .Returns(Task.FromResult(Enumerable.Empty <dynamic>()));

            Log.Logger = new LoggerConfiguration().WriteTo.TestCorrelator().CreateLogger();
            using (TestCorrelator.CreateContext())
            {
                // Act
                await _reportingDataProcessingJob.Run(null);

                // Assert
                var logEvents = TestCorrelator.GetLogEventsFromCurrentContext().ToList();

                Assert.DoesNotContain(logEvents, logEvent => logEvent.Level > LogEventLevel.Information);
                Assert.Contains(logEvents,
                                logEvent => logEvent.Level == LogEventLevel.Information &&
                                logEvent.RenderMessage() == "Starting reporting data processing job");
                Assert.Contains(logEvents,
                                logEvent => logEvent.Level == LogEventLevel.Information &&
                                logEvent.RenderMessage() == "Finishing reporting data processing job");
            }
        }
        public void ShouldLogOutgoingRequest()
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo
                         .TestCorrelator()
                         .CreateLogger();

            IOptions <LogSettings> settings =
                Options.Create(new LogSettings
            {
                RequestLogging = new RequestLogging
                {
                    IncomingEnabled = true,
                    OutgoingEnabled = true
                }
            });

            var handler = new OutgoingRequestLogger <DummyServiceAgent>(settings);

            handler.InnerHandler = new HttpClientHandler();
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://jsonplaceholder.typicode.com/todos/1");
            var invoker            = new HttpMessageInvoker(handler);

            using (TestCorrelator.CreateContext())
            {
                var result = invoker.SendAsync(httpRequestMessage, new CancellationToken()).Result;

                Assert.NotNull(result);

                var logs = TestCorrelator.GetLogEventsFromCurrentContext();

                Assert.Single(logs);
                Assert.Contains(logs, l => l.MessageTemplate.Text == "Outgoing API call response");
            }
        }
예제 #7
0
        public async Task LoggingHandler_SendAsync_WritesDebugLogMessages()
        {
            HttpRequestMessage request = new(HttpMethod.Get, "http://example.com");

            request.Headers.Add("Authorization", "Bearer token-value");

            HttpResponseMessage response = new(HttpStatusCode.OK);

            response.Content          = new StringContent("{}", Encoding.UTF8, "application/json");
            response.Headers.Location = new Uri("http://example.com");

            var sut = CreateInvoker(response, LogEventLevel.Debug);

            // Act
            using var ctx = TestCorrelator.CreateContext();
            HttpResponseMessage result = await sut.SendAsync(request, default);

            // Assert
            result
            .Should().NotBeNull()
            .And.Be(response);

            // Assert
            List <string> actual = TestCorrelator.GetLogEventsFromCurrentContext().Select(FormatLogEvent).ToList();

            actual.Should().BeEquivalentTo(
                @"Debug: GET http://example.com/ HTTP/1.1
Authorization: Bearer token-value
 { SourceContext: ""Crip.AspNetCore.Logging.LoggingHandler.Foo"", EventName: ""HttpRequest"", Endpoint: ""http://example.com/"", HttpMethod: ""GET"" }",
                @"Debug: HTTP/1.1 200 OK
Location: http://example.com/
 { SourceContext: ""Crip.AspNetCore.Logging.LoggingHandler.Foo"", EventName: ""HttpResponse"", StatusCode: 200, Elapsed: 100, Endpoint: ""http://example.com/"", HttpMethod: ""GET"" }",
                "Information: GET http://example.com/ at 00:00:00:100 with 200 OK { SourceContext: \"Crip.AspNetCore.Logging.LoggingHandler.Foo\", EventName: \"HttpResponse\", StatusCode: 200, Elapsed: 100, Endpoint: \"http://example.com/\", HttpMethod: \"GET\" }"
                );
        }
        public async Task Run_LogsSuccess()
        {
            // Arrange
            SetupRepositoryMethods();

            Log.Logger = new LoggerConfiguration().WriteTo.TestCorrelator().CreateLogger();
            using (TestCorrelator.CreateContext())
            {
                // Act
                await _reportingDataRefreshJob.Run(null);

                // Assert
                var logEvents = TestCorrelator.GetLogEventsFromCurrentContext().ToList();

                Assert.DoesNotContain(logEvents, logEvent => logEvent.Level > LogEventLevel.Information);
                AssertContainsInfoMessages(logEvents, new[]
                {
                    "Starting reporting data refresh job",
                    "Starting specimen-matching uspGenerate",
                    "Starting reporting uspGenerate",
                    "Starting migration uspGenerate",
                    "Finishing reporting data refresh job"
                });
                AssertDoesNotContainInfoMessages(logEvents, new[] {"Error occured during reporting data refresh job"});
            }
        }
예제 #9
0
        public void PureSeriLogger_PushLogProperties_LogPropertyList_Include_True()
        {
            const string testProperty = "Property";
            const string testValue    = "Value";
            const string testLogMsg   = "Test Message";

            var logPropertyList = new List <IPureLogPropertyLevel>()
            {
                new PureLogPropertyLevel(new KeyValuePair <string, object>(testProperty, testValue), LogLevel.Debug)
            };


            using (TestCorrelator.CreateContext())
                using (_pureSeriLogger.PushLogProperties(logPropertyList, IncludeLogPropertyTrue))
                {
                    _pureSeriLogger.LogDebug(testLogMsg);

                    var currentTestContext = TestCorrelator.GetLogEventsFromCurrentContext().ToList();

                    currentTestContext.Should().ContainSingle().Which.Properties.ContainsKey(testProperty).Should().BeTrue();
                    currentTestContext.Should().ContainSingle().Which.Properties[testProperty].ToString().Should().Be(testValue.ToDoubleQuoted());

                    currentTestContext.Should().ContainSingle().Which.MessageTemplate.Text.Should().Be(testLogMsg);
                }
        }
예제 #10
0
        public void Add_correlation_token_to_log_context_and_Owin_context(string requestPath)
        {
            using (TestCorrelator.CreateContext())
            {
                AppFunc pipelineFunc(AppFunc next) => CorrelationToken.Middleware(next);

                var ctx = SetupOwinTestEnvironment(requestPath);

                var pipeline = pipelineFunc(m_TestModule(m_NoOp, m_Logger));
                var env      = ctx.Environment;
                pipeline(env);

                // m_Logger was enriched from the log context so it's properties should include CorrelationToken
                var tokenProp = TestCorrelator.GetLogEventsFromCurrentContext().Should().ContainSingle()
                                .Which.Properties.Should().ContainSingle();
                tokenProp.Which.Key.Should().Be("CorrelationToken");

                // the token was also saved in OwinContext with the same value
                tokenProp.Which.Value.ToString().Should().Equals(ctx.Get <string>("correlationToken"));

                // the token should be from request header if it is available there
                var tokenFromRequestHeader = ctx.Request.Headers["Correlation-Token"];
                if (!string.IsNullOrEmpty(tokenFromRequestHeader))
                {
                    tokenProp.Which.Value.ToString().Should().Equals(tokenFromRequestHeader);
                }
            }
        }
예제 #11
0
        private void ValidateTestLog(LogLevel logLevel, LoggableFormat loggableFormat)
        {
            var currentTestContext = TestCorrelator.GetLogEventsFromCurrentContext().ToList();

            if (logLevel <= LogLevel.Information)
            {
                currentTestContext.Should().ContainSingle().Which.Properties.ContainsKey(TestProperty).Should()
                .BeTrue();
                currentTestContext.Should().ContainSingle().Which.Properties[TestProperty].ToString().Should()
                .Be(TestValue.ToDoubleQuoted());
            }
            else
            {
                currentTestContext.Should().ContainSingle().Which.Properties.ContainsKey(TestProperty).Should()
                .BeFalse();
            }

            if (loggableFormat.IsWithParents() && logLevel <= LogLevel.Debug)
            {
                currentTestContext.Should().ContainSingle().Which.Properties.ContainsKey(TestPropertyParent).Should().BeTrue();
                currentTestContext.Should().ContainSingle().Which.Properties[TestPropertyParent].ToString().Should().Be(ParentTestValue.ToDoubleQuoted());
            }
            else
            {
                currentTestContext.Should().ContainSingle().Which.Properties.ContainsKey(TestPropertyParent).Should().BeFalse();
            }

            currentTestContext.Should().ContainSingle().Which.MessageTemplate.Text.Should().Be(TestLogMsg);
        }
예제 #12
0
        public async Task Test1()
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .WriteTo.TestCorrelator()
                         .WriteTo.File(@"C:\logs\test.txt")
                         .CreateLogger();
            using (TestCorrelator.CreateContext())
            {
                var hostBuilder = new WebHostBuilder();
                hostBuilder
                .UseSerilog()
                .UseStartup <TestCorrelatorControllerProblem.Startup>();

                var testAppServer = new TestServer(hostBuilder);
                var testAppClient = testAppServer.CreateClient();

                var results = await testAppClient.GetAsync("weatherforecast");

                var logEvent = TestCorrelator.GetLogEventsFromCurrentContext();
            }
        }
        public async Task PingServiceRx_PingDefaultGateway_TestLogger()
        {
            var ipAddressDefaultGateway = _commonServices.NetworkingSystem.GetDefaultGatewayAddress();

            ipAddressDefaultGateway.Should().NotBeNull().And.Subject.Should().NotBe(IPAddress.None);

            using (TestCorrelator.CreateContext())
            {
                var observable = _pingServiceRx.PingRequestAsync(ipAddressDefaultGateway);
                observable.Should().NotBeNull().And.Subject.Should().BeAssignableTo <IObservable <PingReply> >();

                using (var subscription =
                           observable.SubscribeTestLogger(Logger, "PingServiceRxIntegrationTests"))
                {
                    subscription.Should().NotBeNull().And.Subject.Should().BeAssignableTo <IDisposable>();

                    var pingReply = await observable.FirstAsync();

                    pingReply.Should().NotBeNull().And.Subject.Should().BeOfType <PingReply>()
                    .And.Subject.As <PingReply>().Status.Should()
                    .Match <IPStatus>(ips => ips == IPStatus.Success || ips == IPStatus.TimedOut);

                    // Give up time for Logging to Propagate
                    await Task.Delay(1000);

                    var logEventsList = TestCorrelator.GetLogEventsFromCurrentContext().ToList();

                    logEventsList.Should().HaveCount(2);
                    logEventsList.First().MessageTemplate.IsLogEventOnNext().Should().BeTrue();
                    logEventsList.Last().MessageTemplate.IsLogEventOnCompleted().Should().BeTrue();
                    logEventsList.Last().MessageTemplate.IsLogEventOnError().Should().BeFalse();
                }
            }
        }
예제 #14
0
        public void When_A_Request_Logger_Is_In_The_Pipeline()
        {
            using (TestCorrelator.CreateContext())
            {
                var myCommand = new MyCommand();

                var registry = new SubscriberRegistry();
                registry.Register <MyCommand, MyLoggedHandler>();

                var container = new TinyIoCContainer();
                container.Register <IHandleRequests <MyCommand>, MyLoggedHandler>();

                var handlerFactory = new TinyIocHandlerFactory(container);

                var commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry());

                commandProcessor.Send(myCommand);

                //_should_log_the_request_handler_call
                //_should_log_the_type_of_handler_in_the_call

                _output.WriteLine($"Logger Type: {Log.Logger}");
                foreach (var logEvent in TestCorrelator.GetLogEventsFromCurrentContext())
                {
                    _output.WriteLine(logEvent.MessageTemplate.Text);
                }

                //TestCorrelator.GetLogEventsFromCurrentContext().Should().HaveCount(3);
                TestCorrelator.GetLogEventsFromCurrentContext()
                .Should().Contain(x => x.MessageTemplate.Text.StartsWith("Logging handler pipeline call"))
                .Which.Properties["1"].ToString().Should().Be($"\"{typeof(MyCommand)}\"");
            }
        }
예제 #15
0
        public async Task Run_ThrowsOnStoredProcedureMessages()
        {
            // Arrange
            List <dynamic> sqlResult = new List <object> {
                new { ErrorMessage = "Divide by zero error encountered." }
            };
            const string serialisedResult = "[{\"ErrorMessage\":\"Divide by zero error encountered.\"}]";

            _externalStoredProcedureRepository
            .Setup(r => r.ExecutePopulateForestExtractStoredProcedure())
            .Returns(Task.FromResult(sqlResult.AsEnumerable()));

            Log.Logger = new LoggerConfiguration().WriteTo.TestCorrelator().CreateLogger();
            using (TestCorrelator.CreateContext())
            {
                // Act
                var exception = await Assert.ThrowsAsync <ApplicationException>(async() =>
                                                                                await _reportingDataProcessingJob.Run(null));

                // Assert
                Assert.Equal("Stored procedure did not execute successfully as result has messages, check the logs",
                             exception.Message);

                var logEvents = TestCorrelator.GetLogEventsFromCurrentContext().ToList();

                Assert.Contains(logEvents,
                                logEvent => logEvent.Level == LogEventLevel.Information &&
                                logEvent.RenderMessage() == $"Result: {serialisedResult}");
                Assert.Contains(logEvents,
                                logEvent => logEvent.Level == LogEventLevel.Error &&
                                logEvent.RenderMessage() == "Error occured during reporting data processing job");
            }
        }
        public async Task Run_ThrowsOnMigrationRepositoryException()
        {
            // Arrange
            SetupRepositoryMethods();

            var expectedException = new ApplicationException("Connection was unsuccessful");
            // Override migration with an exception
            _externalStoredProcedureRepository
                .Setup(r => r.ExecuteMigrationGenerateStoredProcedure())
                .Throws(expectedException);

            Log.Logger = new LoggerConfiguration().WriteTo.TestCorrelator().CreateLogger();
            using (TestCorrelator.CreateContext())
            {
                // Act
                var actualException = await Assert.ThrowsAsync<ApplicationException>(async () =>
                    await _reportingDataRefreshJob.Run(null));

                // Assert
                Assert.Equal(expectedException, actualException);
                AssertRepositoryMethodsCalled(reportingCalled: false, specimenMatchingCalled: false);

                var logEvents = TestCorrelator.GetLogEventsFromCurrentContext().ToList();

                AssertContainsInfoMessages(logEvents, new[]
                {
                    "Starting migration uspGenerate"
                });
                Assert.Contains(logEvents,
                    logEvent => logEvent.Level == LogEventLevel.Error
                                && logEvent.RenderMessage() == "Error occured during reporting data refresh job"
                                && logEvent.Exception == expectedException);
                AssertDoesNotContainInfoMessages(logEvents, new[] { "Starting specimen-matching uspGenerate", "Starting reporting uspGenerate", "Finishing reporting data refresh job" });
            }
        }
예제 #17
0
        public async Task MiddlewareCanDecorateLogContext()
        {
            // Arrange
            Log.Logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .WriteTo.TestCorrelator()
                         .CreateLogger();
            var requestDelegate = new RequestDelegate((innerContext) =>
            {
                Log.Information("Test event");
                return(Task.CompletedTask);
            });
            var middleware  = new ElmahIoSerilogMiddleware(requestDelegate);
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Path        = new PathString("/test");
            httpContext.Request.Method      = "GET";
            httpContext.Response.StatusCode = 404;
            httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, "User")
            }));
            httpContext.Request.Headers.Add("RequestKey", new StringValues("RequestValue"));

            // Act
            IEnumerable <LogEvent> logEvents = null;

            using (TestCorrelator.CreateContext())
            {
                await middleware.Invoke(httpContext);

                logEvents = TestCorrelator.GetLogEventsFromCurrentContext();
            }

            // Assert
            Assert.That(logEvents, Is.Not.Null);
            Assert.That(logEvents.Count(), Is.EqualTo(1));
            var logEvent = logEvents.First();

            Assert.That(logEvent.Properties.Count, Is.EqualTo(8));
            Assert.That(logEvent.Properties.ContainsKey("url"));
            Assert.That(((dynamic)logEvent.Properties["url"]).Value, Is.EqualTo("/test"));
            Assert.That(logEvent.Properties.ContainsKey("method"));
            Assert.That(((dynamic)logEvent.Properties["method"]).Value, Is.EqualTo("GET"));
            Assert.That(logEvent.Properties.ContainsKey("statuscode"));
            Assert.That(((dynamic)logEvent.Properties["statuscode"]).Value, Is.EqualTo(404));
            Assert.That(logEvent.Properties.ContainsKey("user"));
            Assert.That(((dynamic)logEvent.Properties["user"]).Value, Is.EqualTo("User"));
            Assert.That(logEvent.Properties.ContainsKey("servervariables"));
            var serverVariable = ((DictionaryValue)logEvent.Properties["servervariables"]).Elements.FirstOrDefault();

            Assert.That(serverVariable, Is.Not.Null);
            Assert.That(serverVariable.Key.Value, Is.EqualTo("RequestKey"));
            Assert.That(((dynamic)serverVariable.Value).Value, Is.EqualTo("RequestValue"));
            Assert.That(logEvent.Properties.ContainsKey("cookies"));
            Assert.That(logEvent.Properties.ContainsKey("form"));
            Assert.That(logEvent.Properties.ContainsKey("querystring"));
        }
예제 #18
0
        public void A_context_captures_all_LogEvents_emitted_to_a_TestCorrelatorContext_within_it()
        {
            using (TestCorrelator.CreateContext())
            {
                Log.Information("");

                TestCorrelator.GetLogEventsFromCurrentContext().Should().ContainSingle();
            }
        }
예제 #19
0
        public void A_context_captures_LogEvents_even_in_sub_methods()
        {
            using (TestCorrelator.CreateContext())
            {
                LogInformation();

                TestCorrelator.GetLogEventsFromCurrentContext().Should().ContainSingle();
            }
        }
        public void A_TestCorrelatorSink_writes_LogEvents_emited_to_it_to_a_TestCorrelator()
        {
            var logger = new LoggerConfiguration().WriteTo.Sink(new TestCorrelatorSink()).CreateLogger();

            using (TestCorrelator.CreateContext())
            {
                logger.Information("");

                TestCorrelator.GetLogEventsFromCurrentContext().Should().ContainSingle();
            }
        }
예제 #21
0
        private void AssertShouldContainProperty(string key, object value)
        {
            LogEventPropertyValue scalarPropertyValue = new ScalarValue(value);

            TestCorrelator.GetLogEventsFromCurrentContext()
            .Should().ContainSingle()
            .Which.Properties
            .Should().Contain(
                KeyValuePair.Create(key, scalarPropertyValue)
                );
        }
예제 #22
0
        public void A_context_does_not_enrich_LogEvents_emitted_within_it()
        {
            using (TestCorrelator.CreateContext())
            {
                Log.Information("");

                TestCorrelator.GetLogEventsFromCurrentContext()
                .Should().ContainSingle()
                .Which.Properties.Should().BeEmpty();
            }
        }
예제 #23
0
        public void A_context_captures_LogEvents_inside_the_same_logical_call_context()
        {
            using (TestCorrelator.CreateContext())
            {
                var logTask = Task.Run(() => { Log.Information(""); });

                Task.WaitAll(logTask);

                TestCorrelator.GetLogEventsFromCurrentContext().Should().ContainSingle();
            }
        }
예제 #24
0
        public void TestSampleLog()
        {
            using (TestCorrelator.CreateContext())
            {
                Log.Logger = new LoggerConfiguration().WriteTo.TestCorrelator().CreateLogger();

                Log.Information("My log message!");

                var logInfo = TestCorrelator.GetLogEventsFromCurrentContext();
                logInfo.Count().ShouldBe(1);
                logInfo.ElementAt(0).MessageTemplate.Text.ShouldBe("My log message!");
            }
        }
        public async Task When_A_Request_Logger_Is_In_The_Pipeline_Async()
        {
            using (TestCorrelator.CreateContext())
            {
                await _commandProcessor.SendAsync(_myCommand);

                //_should_log_the_request_handler_call
                //_should_log_the_type_of_handler_in_the_call
                TestCorrelator.GetLogEventsFromCurrentContext()
                .Should().Contain(x => x.MessageTemplate.Text.StartsWith("Logging handler pipeline call"))
                .Which.Properties["1"].ToString().Should().Be($"\"{typeof(MyCommand)}\"");
            }
        }
예제 #26
0
        A_context_does_not_capture_LogEvents_outside_the_same_logical_call_context_even_when_they_are_in_tasks_started_inside_of_it()
        {
            var logTask = new Task(() => { Log.Information(""); });

            using (TestCorrelator.CreateContext())
            {
                logTask.Start();

                Task.WaitAll(logTask);

                TestCorrelator.GetLogEventsFromCurrentContext().Should().BeEmpty();
            }
        }
예제 #27
0
        public void TestBaseLoggable_Logger_SourceContext()
        {
            Logger.Should().NotBeNull("initialized in constructor");

            using (TestCorrelator.CreateContext())
            {
                Logger.LogInformation("Test");

                TestCorrelator.GetLogEventsFromCurrentContext()
                .Should().ContainSingle()
                .Which.Properties["SourceContext"].ToString().Should()
                .Be(TypeNameHelper.GetTypeDisplayName(typeof(TestBaseLoggableUnitTests)).AddDoubleQuote());
            }
        }
예제 #28
0
        public void XunitSink_String_TestCorrelator()
        {
            var logger = CreatePureLogger(LogEventLevel.Debug);

            using (TestCorrelator.CreateContext())
            {
                logger.LogInformation("Test: XunitSink_String_TestCorrelator");

                TestCorrelator.GetLogEventsFromCurrentContext()
                .Should().ContainSingle()
                .Which.MessageTemplate.Text
                .Should().Be("Test: XunitSink_String_TestCorrelator");
            }
        }
        public void HasSourceContextProperty()
        {
            using (TestCorrelator.CreateContext())
            {
                var test = Container.Resolve <IAcceptsLogViaCtor>();
                test.CreateLog();

                var ctx = TestCorrelator.GetLogEventsFromCurrentContext().ToList();
                ctx.Count.ShouldBe(1);
                var logEvent = ctx.First();
                logEvent.Properties.ShouldContain(p => p.Key.Equals(SourceContextKey));
                logEvent.Properties[SourceContextKey].ToString().ShouldBe($"\"{typeof(AcceptsLogViaCtor).FullName}\"");
            }
        }
예제 #30
0
        public void TestBaseLoggable_Logger_TestCorrelator_String()
        {
            Logger.Should().NotBeNull("initialized in constructor");

            using (TestCorrelator.CreateContext())
            {
                Logger.LogInformation("Test: TestBaseLoggable_Logger");

                TestCorrelator.GetLogEventsFromCurrentContext()
                .Should().ContainSingle()
                .Which.MessageTemplate.Text
                .Should().Be("Test: TestBaseLoggable_Logger");
            }
        }