This commit is contained in:
Pavel Krymets 2018-10-30 11:13:25 -07:00 коммит произвёл GitHub
Родитель 937fccc01b
Коммит 7c6a5235ec
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
8 изменённых файлов: 159 добавлений и 39 удалений

Просмотреть файл

@ -14,6 +14,9 @@ namespace Microsoft.Extensions.Logging.Performance
[Params(true, false)]
public bool HasISupportLoggingScopeLogger { get; set; } = false;
[Params(true, false)]
public bool CaptureScopes { get; set; } = false;
// Baseline as this is the fastest way to do nothing
[Benchmark(Baseline = true)]
public void FilteredByLevel()
@ -59,6 +62,8 @@ namespace Microsoft.Extensions.Logging.Performance
services.AddSingleton<ILoggerProvider, LoggerProvider<NoopLogger>>();
}
services.Configure<LoggerFilterOptions>(options => options.CaptureScopes = CaptureScopes);
_logger = services.BuildServiceProvider().GetService<ILoggerFactory>().CreateLogger("Logger");
}

Просмотреть файл

@ -30,6 +30,8 @@ namespace Microsoft.Extensions.Logging
return;
}
options.CaptureScopes = _configuration.GetValue<bool>(nameof(options.CaptureScopes));
foreach (var configurationSection in _configuration.GetChildren())
{
if (configurationSection.Key.Equals(LogLevelKey, StringComparison.OrdinalIgnoreCase))

Просмотреть файл

@ -38,6 +38,8 @@ namespace Microsoft.Extensions.Logging
}
}
public bool CaptureScopes { get; set; }
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var loggers = Loggers;
@ -124,7 +126,7 @@ namespace Microsoft.Extensions.Logging
{
var loggers = Loggers;
if (loggers == null)
if (loggers == null || !CaptureScopes)
{
return NullScope.Instance;
}

Просмотреть файл

@ -58,6 +58,7 @@ namespace Microsoft.Extensions.Logging
ApplyRules(loggerInformation, categoryName, 0, loggerInformation.Length);
logger.Value.Loggers = loggerInformation;
logger.Value.CaptureScopes = filterOptions.CaptureScopes;
}
}
}
@ -75,7 +76,8 @@ namespace Microsoft.Extensions.Logging
{
logger = new Logger(this)
{
Loggers = CreateLoggers(categoryName)
Loggers = CreateLoggers(categoryName),
CaptureScopes = _filterOptions.CaptureScopes
};
_loggers[categoryName] = logger;
}

Просмотреть файл

@ -7,6 +7,11 @@ namespace Microsoft.Extensions.Logging
{
public class LoggerFilterOptions
{
/// <summary>
/// Gets or sets value indicating whether logging scopes are being captured. Defaults to <c>true</c>
/// </summary>
public bool CaptureScopes { get; set; } = true;
/// <summary>
/// Gets or sets the minimum level of log messages if none of the rules match.
/// </summary>

Просмотреть файл

@ -1,12 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.Options;
@ -28,7 +25,7 @@ namespace Microsoft.Extensions.Logging.Test
}
}
}";
var config = CreateConfiguration(() => json);
var config = TestConfiguration.Create(() => json);
var loggerProvider = new TestLoggerProvider(new TestSink(), isEnabled: true);
var factory = TestLoggerBuilder.Create(builder => builder
@ -74,7 +71,7 @@ namespace Microsoft.Extensions.Logging.Test
}
}
}";
var config = CreateConfiguration(() => json);
var config = TestConfiguration.Create(() => json);
var loggerProvider = new TestLoggerProvider(new TestSink(), isEnabled: true);
var factory = TestLoggerBuilder.Create(builder => builder
.AddConfiguration(config.GetSection("Logging"))
@ -121,7 +118,7 @@ namespace Microsoft.Extensions.Logging.Test
}
}
}";
var config = CreateConfiguration(() => json);
var config = TestConfiguration.Create(() => json);
var loggerProvider = new TestLoggerProvider(new TestSink(), isEnabled: true);
var factory = TestLoggerBuilder.Create(builder => builder
@ -155,7 +152,7 @@ namespace Microsoft.Extensions.Logging.Test
}
}
}";
var config = CreateConfiguration(() => json);
var config = TestConfiguration.Create(() => json);
var loggerProvider = new TestLoggerProvider(new TestSink(), isEnabled: true);
var factory = TestLoggerBuilder.Create(builder => builder
@ -187,7 +184,7 @@ namespace Microsoft.Extensions.Logging.Test
}
}
}";
var config = CreateConfiguration(() => json);
var config = TestConfiguration.Create(() => json);
var loggerProvider = new TestLoggerProvider(new TestSink(), isEnabled: true);
var factory = TestLoggerBuilder.Create(builder => builder
@ -315,7 +312,7 @@ namespace Microsoft.Extensions.Logging.Test
}
}
}";
var config = CreateConfiguration(() => json);
var config = TestConfiguration.Create(() => json);
var loggerProvider = new TestLoggerProvider(new TestSink(), isEnabled: true);
var factory = TestLoggerBuilder.Create(builder => builder
@ -426,7 +423,7 @@ namespace Microsoft.Extensions.Logging.Test
.Build())
)
.BuildServiceProvider();
var options = serviceProvider.GetRequiredService<IOptions<LoggerFilterOptions>>();
Assert.Null(options.Value.Rules.Single().CategoryName);
@ -584,32 +581,5 @@ namespace Microsoft.Extensions.Logging.Test
("Category.Sub", LogLevel.Trace, true, false)
},
};
internal ConfigurationRoot CreateConfiguration(Func<string> getJson)
{
var provider = new TestConfiguration(new JsonConfigurationSource { Optional = true }, getJson);
return new ConfigurationRoot(new List<IConfigurationProvider> { provider });
}
private class TestConfiguration : JsonConfigurationProvider
{
private Func<string> _json;
public TestConfiguration(JsonConfigurationSource source, Func<string> json)
: base(source)
{
_json = json;
}
public override void Load()
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(_json());
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
Load(stream);
}
}
}
}

Просмотреть файл

@ -149,6 +149,103 @@ namespace Microsoft.Extensions.Logging.Test
logger.Verify(l => l.BeginScope(It.IsAny<object>()), Times.Never);
}
[Fact]
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);
}
[Fact]
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);
}
[Fact]
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);
}
}
private class CustomLoggerProvider : ILoggerProvider
{
private readonly string _providerName;

Просмотреть файл

@ -0,0 +1,37 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
namespace Microsoft.Extensions.Logging.Test
{
internal class TestConfiguration : JsonConfigurationProvider
{
private Func<string> _json;
public TestConfiguration(JsonConfigurationSource source, Func<string> json)
: base(source)
{
_json = json;
}
public override void Load()
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(_json());
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
Load(stream);
}
public static ConfigurationRoot Create(Func<string> getJson)
{
var provider = new TestConfiguration(new JsonConfigurationSource { Optional = true }, getJson);
return new ConfigurationRoot(new List<IConfigurationProvider> { provider });
}
}
}