Skip to content

Instantly share code, notes, and snippets.

@mattwcole
Last active November 7, 2022 20:31
Show Gist options
  • Save mattwcole/a723ac0a505fa351074a7d7072f63d82 to your computer and use it in GitHub Desktop.
Save mattwcole/a723ac0a505fa351074a7d7072f63d82 to your computer and use it in GitHub Desktop.
Microsoft.Extensions.Logging.ILogger decorator that disables semantic logging
public sealed class DisableSemanticLoggingDecorator : ILogger
{
private readonly ILogger _logger;
public DisableSemanticLoggingDecorator(ILogger logger) => _logger = logger;
public IDisposable BeginScope<TState>(TState state) => _logger.BeginScope(state);
public bool IsEnabled(LogLevel logLevel) => _logger.IsEnabled(logLevel);
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
return;
// ReSharper disable once TemplateIsNotCompileTimeConstantProblem
_logger.Log(logLevel, eventId, exception, formatter(state, exception));
}
}
public sealed class CustomLoggerFactory : ILoggerFactory
{
private readonly ILoggerFactory _loggerFactory;
public CustomLoggerFactory(ILoggerFactory loggerFactory) => _loggerFactory = loggerFactory;
public void Dispose() => _loggerFactory.Dispose();
public void AddProvider(ILoggerProvider provider) => _loggerFactory.AddProvider(provider);
public ILogger CreateLogger(string categoryName) =>
new DisableSemanticLoggingDecorator(_loggerFactory.CreateLogger(categoryName));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment