コード例 #1
0
ファイル: LoggerFilterTest.cs プロジェクト: z77ma/runtime
        public void PreferFullNameOverDefaultForFiltering()
        {
            // Arrange
            var json =
                @"{
  ""Logging"": {
    ""LogLevel"": {
      ""Microsoft"": ""Critical""
    },
    ""TestLogger"": {
      ""LogLevel"": {
        ""Microsoft"": ""Trace""
      }
    }
  }
}";
            var config = TestConfiguration.Create(() => json);

            var loggerProvider = new TestLoggerProvider(new TestSink(), isEnabled: true);
            var factory        = TestLoggerBuilder.Create(builder => builder
                                                          .AddConfiguration(config.GetSection("Logging"))
                                                          .AddProvider(loggerProvider));

            var logger = factory.CreateLogger("Microsoft");

            // Act
            logger.LogTrace("Message");

            // Assert
            var writes = loggerProvider.Sink.Writes;

            Assert.Single(writes);
        }
コード例 #2
0
        public void ScopesAreNotCreatedInIScopeProviderWhenScopesAreDisabled()
        {
            var provider = new Mock <ILoggerProvider>();
            var logger   = new Mock <ILogger>();

            IExternalScopeProvider externalScopeProvider = null;

            provider.Setup(loggerProvider => loggerProvider.CreateLogger(It.IsAny <string>()))
            .Returns(logger.Object);
            provider.As <ISupportExternalScope>().Setup(scope => scope.SetScopeProvider(It.IsAny <IExternalScopeProvider>()))
            .Callback((IExternalScopeProvider scopeProvider) => externalScopeProvider = scopeProvider);

            var factory = TestLoggerBuilder.Create(
                builder => {
                builder.AddProvider(provider.Object);
                builder.Services.Configure <LoggerFilterOptions>(options => options.CaptureScopes = false);
            });

            var newLogger  = factory.CreateLogger("Logger");
            int scopeCount = 0;

            using (newLogger.BeginScope("Scope"))
            {
                externalScopeProvider.ForEachScope <object>((_, __) => scopeCount++, null);
            }

            provider.Verify(p => p.CreateLogger("Logger"), Times.Once);
            logger.Verify(l => l.BeginScope(It.IsAny <object>()), Times.Never);
            Assert.Equal(0, scopeCount);
        }
コード例 #3
0
ファイル: LoggerFilterTest.cs プロジェクト: z77ma/runtime
        public void AddFilterForMatchingProviderFilters()
        {
            var provider = new TestLoggerProvider(new TestSink(), isEnabled: true);
            var factory  = TestLoggerBuilder.Create(builder => builder
                                                    .AddProvider(provider)
                                                    .AddFilter((name, cat, level) =>
            {
                if (string.Equals("Microsoft.Extensions.Logging.Test.TestLoggerProvider", name))
                {
                    if (string.Equals("Test", cat))
                    {
                        return(level >= LogLevel.Information);
                    }
                }

                return(true);
            }));

            var logger = factory.CreateLogger("Test");

            logger.LogInformation("Message");

            var writes = provider.Sink.Writes;

            Assert.Single(writes);

            logger.LogTrace("Message");

            Assert.Single(writes);
        }
コード例 #4
0
        public static void DiagnosticsScope_PushesAndPops_LogicalOperationStack()
        {
            // Arrange
            var baseState = "base";

            Trace.CorrelationManager.StartLogicalOperation(baseState);
            var state = "1337state7331";

            var factory = TestLoggerBuilder.Create(builder =>
                                                   builder.AddTraceSource(new SourceSwitch("TestSwitch"), new ConsoleTraceListener()));

            var logger = factory.CreateLogger("Test");

            // Act
            var a     = Trace.CorrelationManager.LogicalOperationStack.Peek();
            var scope = logger.BeginScope(state);
            var b     = Trace.CorrelationManager.LogicalOperationStack.Peek();

            scope.Dispose();
            var c = Trace.CorrelationManager.LogicalOperationStack.Peek();

            // Assert
            Assert.Same(a, c);
            Assert.Same(state, b);
        }
コード例 #5
0
ファイル: LoggerFilterTest.cs プロジェクト: z77ma/runtime
        public void AddFilterLastWins()
        {
            var provider = new TestLoggerProvider(new TestSink(), isEnabled: true);
            var factory  = TestLoggerBuilder.Create(builder => builder
                                                    .AddProvider(provider)
                                                    .AddFilter((name, cat, level) => level >= LogLevel.Warning)
                                                    .AddFilter((name, cat, level) => string.Equals(cat, "NotTest")));

            var logger = factory.CreateLogger("Test");

            logger.LogWarning("Message");

            var writes = provider.Sink.Writes;

            Assert.Empty(writes);

            logger = factory.CreateLogger("NotTest");

            logger.LogInformation("Message");

            Assert.Single(writes);

            logger.LogError("Message");

            Assert.Equal(2, writes.Count);
        }
コード例 #6
0
        public static void Log_Shoud_Add_Exception_To_Message_Whether_Formatter_Is_Null_Or_Not(bool shouldFormatterBeNull)
        {
            // Arrange
            Mock <TraceListener> traceListener = new Mock <TraceListener>();
            SourceSwitch         sourceSwitch  = new SourceSwitch("TestSwitch")
            {
                Level = SourceLevels.All
            };

            ILoggerFactory factory = TestLoggerBuilder.Create(builder => builder.AddTraceSource(sourceSwitch, traceListener.Object));
            ILogger        logger  = factory.CreateLogger("Test");

            const LogLevel logLevel  = LogLevel.Information;
            EventId        eventId   = new EventId(1);
            const string   message   = "some log message";
            Exception      exception = new Exception("Some error occurred");
            Func <string, Exception, string> formatter = shouldFormatterBeNull ? (Func <string, Exception, string>)null : (value, passedException) => value;

            string expectedMessage = $"{message} {exception}";

            // Act
            logger.Log(logLevel, eventId, message, exception, formatter);

            // Assert
            traceListener.Verify(listener => listener.TraceEvent(It.IsAny <TraceEventCache>(), It.IsAny <string>(), It.IsAny <TraceEventType>(), It.IsAny <int>(), expectedMessage), Times.Once);
        }
コード例 #7
0
ファイル: LoggerFilterTest.cs プロジェクト: z77ma/runtime
        public void CanFilterOnNamedProviders()
        {
            // Arrange
            var json =
                @"{
  ""Logging"": {
    ""Microsoft.Extensions.Logging.Test.TestLoggerProvider"": {
      ""LogLevel"": {
        ""Microsoft"": ""Information""
      }
    }
  }
}";
            var config = TestConfiguration.Create(() => json);

            var loggerProvider = new TestLoggerProvider(new TestSink(), isEnabled: true);
            var factory        = TestLoggerBuilder.Create(builder => builder
                                                          .AddConfiguration(config.GetSection("Logging"))
                                                          .AddProvider(loggerProvider));

            var logger = factory.CreateLogger("Microsoft");

            // Act
            logger.LogTrace("Message");

            // Assert
            var writes = loggerProvider.Sink.Writes;

            Assert.Empty(writes);
        }
コード例 #8
0
ファイル: LoggerFilterTest.cs プロジェクト: z77ma/runtime
        public void DefaultCategoryNameIsUsedIfNoneMatch()
        {
            // Arrange
            var json =
                @"{
  ""Logging"": {
    ""Microsoft.Extensions.Logging.Test.TestLoggerProvider"": {
      ""LogLevel"": {
        ""Default"": ""Information"",
        ""Microsoft"": ""Warning""
      }
    }
  }
}";
            var config = TestConfiguration.Create(() => json);

            var loggerProvider = new TestLoggerProvider(new TestSink(), isEnabled: true);
            var factory        = TestLoggerBuilder.Create(builder => builder
                                                          .AddConfiguration(config.GetSection("Logging"))
                                                          .AddProvider(loggerProvider));

            var logger = factory.CreateLogger("Microsoft");

            // Act
            logger.LogTrace("Message");

            // Assert
            var writes = loggerProvider.Sink.Writes;

            Assert.Empty(writes);

            // No config value for 'None' so should use 'Default'
            logger = factory.CreateLogger("None");

            // Act
            logger.LogTrace("Message");

            // Assert
            Assert.Empty(writes);

            // Act
            logger.LogInformation("Message");

            // Assert
            Assert.Single(writes);
        }
コード例 #9
0
ファイル: LoggerFilterTest.cs プロジェクト: z77ma/runtime
        public void ChangingConfigReloadsDefaultFilter()
        {
            // Arrange
            var json =
                @"{
  ""Logging"": {
    ""LogLevel"": {
      ""Microsoft"": ""Information""
    }
  }
}";
            var config         = TestConfiguration.Create(() => json);
            var loggerProvider = new TestLoggerProvider(new TestSink(), isEnabled: true);

            var factory = TestLoggerBuilder.Create(builder => builder
                                                   .AddConfiguration(config.GetSection("Logging"))
                                                   .AddProvider(loggerProvider));

            var logger = factory.CreateLogger("Microsoft");

            // Act
            logger.LogTrace("Message");

            // Assert
            var writes = loggerProvider.Sink.Writes;

            Assert.Empty(writes);

            json =
                @"{
  ""Logging"": {
    ""LogLevel"": {
      ""Microsoft"": ""Trace""
    }
  }
}";
            config.Reload();

            // Act
            logger.LogTrace("Message");

            // Assert
            writes = loggerProvider.Sink.Writes;
            Assert.Single(writes);
        }
コード例 #10
0
ファイル: LoggerFilterTest.cs プロジェクト: z77ma/runtime
        public void AddFilterWithProviderNameAndCategoryFilterFuncFiltersCorrectly()
        {
            var provider = new TestLoggerProvider(new TestSink(), isEnabled: true);
            var factory  = TestLoggerBuilder.Create(builder => builder
                                                    .AddProvider(provider)
                                                    .AddFilter <TestLoggerProvider>((c, l) => l >= LogLevel.Warning));

            var logger = factory.CreateLogger("Sample.Test");

            logger.LogInformation("Message");

            var writes = provider.Sink.Writes;

            Assert.Empty(writes);

            logger.LogWarning("Message");

            Assert.Single(writes);
        }
コード例 #11
0
        public void AddFilterWithProviderNameCategoryNameAndMinLevelFiltersCorrectly()
        {
            var provider = new TestLoggerProvider(new TestSink(), isEnabled: true);
            var factory  = TestLoggerBuilder.Create(builder => builder
                                                    .AddProvider(provider)
                                                    .AddFilter <TestLoggerProvider>("Sample", LogLevel.Warning));

            var logger = factory.CreateLogger("Sample.Test");

            logger.LogInformation("Message");

            var writes = provider.Sink.Writes;

            Assert.Equal(0, writes.Count);

            logger.LogWarning("Message");

            Assert.Equal(1, writes.Count);
        }
コード例 #12
0
        public void Logs_Nothing_IfNotEnabled()
        {
            using (var testListener = new TestEventListener())
            {
                // No call to factory.AddEventSourceLogger();
                var factory = TestLoggerBuilder.Create(builder => builder
                                                       .SetMinimumLevel(LogLevel.Trace));

                var listenerSettings = new TestEventListener.ListenerSettings();
                listenerSettings.Keywords   = EventKeywords.None;
                listenerSettings.FilterSpec = null;
                listenerSettings.Level      = default(EventLevel);
                testListener.EnableEvents(listenerSettings);

                LogStuff(factory);

                VerifyEvents(testListener); // No verifiers = 0 events expected
            }
        }
コード例 #13
0
        public static void IsEnabledReturnsCorrectValue()
        {
            // Arrange
            var testSwitch = new SourceSwitch("TestSwitch", "Level will be set to warning for this test");

            testSwitch.Level = SourceLevels.Warning;

            var factory = TestLoggerBuilder.Create(builder => builder.AddTraceSource(testSwitch));

            // Act
            var logger = factory.CreateLogger("Test");

            // Assert
            Assert.True(logger.IsEnabled(LogLevel.Critical));
            Assert.True(logger.IsEnabled(LogLevel.Error));
            Assert.True(logger.IsEnabled(LogLevel.Warning));
            Assert.False(logger.IsEnabled(LogLevel.Information));
            Assert.False(logger.IsEnabled(LogLevel.Debug));
            Assert.False(logger.IsEnabled(LogLevel.Trace));
        }
コード例 #14
0
        public static void MultipleLoggers_IsEnabledReturnsCorrectValue(SourceLevels first, SourceLevels second, bool expected)
        {
            // Arrange
            var firstSwitch = new SourceSwitch("FirstSwitch", "First Test Switch");

            firstSwitch.Level = first;

            var secondSwitch = new SourceSwitch("SecondSwitch", "Second Test Switch");

            secondSwitch.Level = second;

            // Act
            var factory = TestLoggerBuilder.Create(builder => builder
                                                   .AddTraceSource(firstSwitch)
                                                   .AddTraceSource(secondSwitch));

            var logger = factory.CreateLogger("Test");

            // Assert
            Assert.Equal(expected, logger.IsEnabled(LogLevel.Information));
        }
コード例 #15
0
        public void CaptureScopesIsReadFromConfiguration()
        {
            var provider = new Mock <ILoggerProvider>();
            var logger   = new Mock <ILogger>();
            var json     = @"{ ""CaptureScopes"": ""false"" }";

            var config = TestConfiguration.Create(() => json);
            IExternalScopeProvider externalScopeProvider = null;

            provider.Setup(loggerProvider => loggerProvider.CreateLogger(It.IsAny <string>()))
            .Returns(logger.Object);
            provider.As <ISupportExternalScope>().Setup(scope => scope.SetScopeProvider(It.IsAny <IExternalScopeProvider>()))
            .Callback((IExternalScopeProvider scopeProvider) => externalScopeProvider = scopeProvider);

            var factory = TestLoggerBuilder.Create(
                builder => {
                builder.AddProvider(provider.Object);
                builder.AddConfiguration(config);
            });

            var newLogger  = factory.CreateLogger("Logger");
            int scopeCount = 0;

            using (newLogger.BeginScope("Scope"))
            {
                externalScopeProvider.ForEachScope <object>((_, __) => scopeCount++, null);
                Assert.Equal(0, scopeCount);
            }

            json = @"{ ""CaptureScopes"": ""true"" }";
            config.Reload();

            scopeCount = 0;
            using (newLogger.BeginScope("Scope"))
            {
                externalScopeProvider.ForEachScope <object>((_, __) => scopeCount++, null);
                Assert.Equal(1, scopeCount);
            }
        }
コード例 #16
0
        public void Log_AggregatesExceptionsFromMultipleLoggers()
        {
            // Arrange
            var store         = new List <string>();
            var loggerFactory = TestLoggerBuilder.Create(builder => builder
                                                         .AddProvider(new CustomLoggerProvider("provider1", ThrowExceptionAt.Log, store))
                                                         .AddProvider(new CustomLoggerProvider("provider2", ThrowExceptionAt.Log, store)));

            var logger = loggerFactory.CreateLogger("Test");

            // Act
            var aggregateException = Assert.Throws <AggregateException>(() => logger.LogInformation("Hello!"));

            // Assert
            Assert.Empty(store);
            Assert.NotNull(aggregateException);
            Assert.StartsWith("An error occurred while writing to logger(s).", aggregateException.Message);
            var exceptions = aggregateException.InnerExceptions;

            Assert.Equal(2, exceptions.Count);
            Assert.Equal("provider1.Test-Error occurred while logging data.", exceptions[0].Message);
            Assert.Equal("provider2.Test-Error occurred while logging data.", exceptions[1].Message);
        }
コード例 #17
0
        public void ScopesAreNotCreatedWhenScopesAreDisabled()
        {
            var provider = new Mock <ILoggerProvider>();
            var logger   = new Mock <ILogger>();

            provider.Setup(loggerProvider => loggerProvider.CreateLogger(It.IsAny <string>()))
            .Returns(logger.Object);

            var factory = TestLoggerBuilder.Create(
                builder => {
                builder.AddProvider(provider.Object);
                builder.Services.Configure <LoggerFilterOptions>(options => options.CaptureScopes = false);
            });

            var newLogger = factory.CreateLogger("Logger");

            using (newLogger.BeginScope("Scope"))
            {
            }

            provider.Verify(p => p.CreateLogger("Logger"), Times.Once);
            logger.Verify(l => l.BeginScope(It.IsAny <object>()), Times.Never);
        }
コード例 #18
0
ファイル: LoggerFilterTest.cs プロジェクト: z77ma/runtime
        public void AddFilterForNonMatchingProviderDoesNotFilter()
        {
            var provider = new TestLoggerProvider(new TestSink(), isEnabled: true);
            var factory  = TestLoggerBuilder.Create(builder => builder
                                                    .AddProvider(provider)
                                                    .AddFilter((name, cat, level) =>
            {
                if (string.Equals("None", name))
                {
                    return(level >= LogLevel.Error);
                }

                return(true);
            }));

            var logger = factory.CreateLogger("Test");

            logger.LogInformation("Message");

            var writes = provider.Sink.Writes;

            Assert.Single(writes);
        }
コード例 #19
0
        public void BeginScope_IgnoresExceptionInIntermediateLoggersAndThrowsAggregateException()
        {
            // Arrange
            var store         = new List <string>();
            var loggerFactory = TestLoggerBuilder.Create(builder => builder
                                                         .AddProvider(new CustomLoggerProvider("provider1", ThrowExceptionAt.None, store))
                                                         .AddProvider(new CustomLoggerProvider("provider2", ThrowExceptionAt.BeginScope, store))
                                                         .AddProvider(new CustomLoggerProvider("provider3", ThrowExceptionAt.None, store)));

            var logger = loggerFactory.CreateLogger("Test");

            // Act
            var aggregateException = Assert.Throws <AggregateException>(() => logger.BeginScope("Scope1"));

            // Assert
            Assert.Equal(new[] { "provider1.Test-Scope1", "provider3.Test-Scope1" }, store);
            Assert.NotNull(aggregateException);
            Assert.StartsWith("An error occurred while writing to logger(s).", aggregateException.Message);
            Assert.Single(aggregateException.InnerExceptions);
            var exception = aggregateException.InnerExceptions[0];

            Assert.Equal("provider2.Test-Error occurred while creating scope.", exception.Message);
        }
コード例 #20
0
        public void IsEnabled_IgnoresExceptionInIntermediateLoggers()
        {
            // Arrange
            var store         = new List <string>();
            var loggerFactory = TestLoggerBuilder.Create(builder => builder
                                                         .AddProvider(new CustomLoggerProvider("provider1", ThrowExceptionAt.None, store))
                                                         .AddProvider(new CustomLoggerProvider("provider2", ThrowExceptionAt.IsEnabled, store))
                                                         .AddProvider(new CustomLoggerProvider("provider3", ThrowExceptionAt.None, store)));

            var logger = loggerFactory.CreateLogger("Test");

            // Act
            var aggregateException = Assert.Throws <AggregateException>(() => logger.LogInformation("Hello!"));

            // Assert
            Assert.Equal(new[] { "provider1.Test-Hello!", "provider3.Test-Hello!" }, store);
            Assert.NotNull(aggregateException);
            Assert.StartsWith("An error occurred while writing to logger(s).", aggregateException.Message);
            Assert.Single(aggregateException.InnerExceptions);
            var exception = aggregateException.InnerExceptions[0];

            Assert.Equal("provider2.Test-Error occurred while checking if logger is enabled.", exception.Message);
        }
コード例 #21
0
ファイル: LoggerFilterTest.cs プロジェクト: z77ma/runtime
        public void ProviderLevelIsPreferredOverGlobalFilter()
        {
            // Arrange
            var json =
                @"{
  ""Logging"": {
    ""TestLogger"": {
      ""LogLevel"": {
        ""Test"": ""Debug""
      }
    }
  }
}";
            var config         = TestConfiguration.Create(() => json);
            var loggerProvider = new TestLoggerProvider(new TestSink(), isEnabled: true);

            var factory = TestLoggerBuilder.Create(builder => builder
                                                   .AddConfiguration(config.GetSection("Logging"))
                                                   .AddProvider(loggerProvider)
                                                   .AddFilter((name, cat, level) => level < LogLevel.Critical));

            var logger = factory.CreateLogger("Test");

            var writes = loggerProvider.Sink.Writes;

            logger.LogTrace("Message");

            Assert.Empty(writes);

            logger.LogInformation("Message");

            Assert.Single(writes);

            logger.LogCritical("Message");

            Assert.Equal(2, writes.Count);
        }
コード例 #22
0
        public void ScopesAreNotCreatedForDisabledLoggers()
        {
            var provider = new Mock <ILoggerProvider>();
            var logger   = new Mock <ILogger>();

            provider.Setup(loggerProvider => loggerProvider.CreateLogger(It.IsAny <string>()))
            .Returns(logger.Object);

            var factory = TestLoggerBuilder.Create(
                builder => {
                builder.AddProvider(provider.Object);
                // Disable all logs
                builder.AddFilter(null, LogLevel.None);
            });

            var newLogger = factory.CreateLogger("Logger");

            using (newLogger.BeginScope("Scope"))
            {
            }

            provider.Verify(p => p.CreateLogger("Logger"), Times.Once);
            logger.Verify(l => l.BeginScope(It.IsAny <object>()), Times.Never);
        }
コード例 #23
0
 private static ILoggerFactory CreateLoggerFactory()
 {
     return(TestLoggerBuilder.Create(builder => builder
                                     .AddEventSourceLogger()
                                     .SetMinimumLevel(LogLevel.Trace)));
 }