Last active
April 16, 2021 12:21
-
-
Save ChristopherHaws/66a54220e0cb288918e86de16396e44e to your computer and use it in GitHub Desktop.
DisposingLoggerScopeFactory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Used to create logging scopes that will live for the lifetime of the service providers scope. | |
/// </summary> | |
public interface ILoggerScopeFactory | |
{ | |
void BeginScope<TState>(TState state); | |
void BeginScope(String messageFormat, params Object[] args); | |
} | |
public class DisposingLoggerScopeFactory : ILoggerScopeFactory, IDisposable | |
{ | |
private readonly ILogger<DisposingLoggerScopeFactory> logger; | |
private readonly ConcurrentStack<IDisposable> scopes = new ConcurrentStack<IDisposable>(); | |
public DisposingLoggerScopeFactory(ILogger<DisposingLoggerScopeFactory> logger) => this.logger = logger; | |
public void BeginScope<TState>(TState state) => this.scopes.Push(this.logger.BeginScope(state)); | |
public void BeginScope(String messageFormat, params object[] args) => this.scopes.Push(this.logger.BeginScope(messageFormat, args)); | |
public void Dispose() | |
{ | |
while (scopes.TryPop(out var scope)) | |
{ | |
scope?.Dispose(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var services = new ServiceCollection(); | |
services.AddLogging(logging => | |
{ | |
logging.AddConsole(x => x.IncludeScopes = true); | |
}); | |
services.AddScoped<ILoggerScopeFactory, DisposingLoggerScopeFactory>(); | |
using var root = services.BuildServiceProvider(); | |
using (var scope = root.CreateScope()) | |
{ | |
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Object>>(); | |
var scopeFactory = scope.ServiceProvider.GetRequiredService<ILoggerScopeFactory>(); | |
try | |
{ | |
CreateScopeAndThrow(scopeFactory); | |
} | |
catch (Exception ex) | |
{ | |
logger.LogError(ex, "Unhandled exception :("); | |
} | |
} | |
} | |
public void CreateScopeAndThrow(ILoggerScopeFactory scopeFactory) | |
{ | |
scopeFactory.BeginScope("Scope"); | |
throw new Exception("Oh no!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment