Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Intercepting log messages with a wrapping logger provider
public class ChangeLevelLoggerProvider : InterceptingLoggerProvider
{
private readonly Func<LogLevel, LogLevel> _changeLevel;
public ChangeLevelLoggerProvider(ILoggerProvider provider, Func<LogLevel, LogLevel> changeLevel)
: base(provider)
{
_changeLevel = changeLevel ?? throw new ArgumentNullException(nameof(changeLevel));
}
protected override void Log<TState>(
ILogger logger,
LogLevel logLevel,
EventId eventId,
TState state,
Exception exception,
Func<TState, Exception, string> formatter) =>
base.Log(logger, _changeLevel(logLevel), eventId, state, exception, formatter);
}
public abstract class InterceptingLoggerProvider : ILoggerProvider
{
private readonly ILoggerProvider _provider;
public InterceptingLoggerProvider(ILoggerProvider provider)
{
_provider = provider ?? throw new ArgumentNullException(nameof(provider));
}
public ILogger CreateLogger(string categoryName) =>
new InterceptingLogger(this, _provider.CreateLogger(categoryName));
public void Dispose() => _provider.Dispose();
protected virtual void Log<TState>(
ILogger logger,
LogLevel logLevel,
EventId eventId,
TState state,
Exception exception,
Func<TState, Exception, string> formatter) =>
logger.Log(logLevel, eventId, state, exception, formatter);
private class InterceptingLogger : ILogger
{
private readonly InterceptingLoggerProvider _provider;
private readonly ILogger _logger;
public InterceptingLogger(InterceptingLoggerProvider provider, ILogger logger)
{
_provider = provider ?? throw new ArgumentNullException(nameof(provider));
_logger = logger ?? throw new ArgumentNullException(nameof(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) =>
_provider.Log(_logger, logLevel, eventId, state, exception, formatter);
}
}
// ...
_host = new WebHostBuilder()
.ConfigureLogging(loggingBuilder =>
{
loggingBuilder.AddProvider(
new ChangeLevelLoggerProvider(
myWrappedProvider, level => level == LogLevel.Information ? LogLevel.Debug : level));
})
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment