Skip to content

Pass registered logger to DiagnosticContext #53

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 17 additions & 17 deletions src/Serilog.Extensions.Hosting/SerilogHostBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,13 @@ public static IHostBuilder UseSerilog(
collection.AddSingleton<ILoggerFactory>(services => new SerilogLoggerFactory(logger, dispose));
}

ConfigureServices(collection, logger);
if (logger != null)
{
// This won't (and shouldn't) take ownership of the logger.
collection.AddSingleton(logger);
}
bool useRegisteredLogger = logger != null;
ConfigureDiagnosticContext(collection, useRegisteredLogger);
});

return builder;
Expand Down Expand Up @@ -221,32 +227,26 @@ public static IHostBuilder UseSerilog(

return factory;
});

// Null is passed here because we've already (lazily) registered `ILogger`
ConfigureServices(collection, null);

ConfigureDiagnosticContext(collection, preserveStaticLogger);
});

return builder;
}

static void ConfigureServices(IServiceCollection collection, ILogger logger)
static void ConfigureDiagnosticContext(IServiceCollection collection, bool useRegisteredLogger)
{
if (collection == null) throw new ArgumentNullException(nameof(collection));

if (logger != null)
{
// This won't (and shouldn't) take ownership of the logger.
collection.AddSingleton(logger);
}

// Registered to provide two services...
var diagnosticContext = new DiagnosticContext(logger);

// Registered to provide two services...
// Consumed by e.g. middleware
collection.AddSingleton(diagnosticContext);

collection.AddSingleton(services =>
{
ILogger logger = useRegisteredLogger ? services.GetRequiredService<RegisteredLogger>().Logger : null;
return new DiagnosticContext(logger);
});
// Consumed by user code
collection.AddSingleton<IDiagnosticContext>(diagnosticContext);
collection.AddSingleton<IDiagnosticContext>(services => services.GetRequiredService<DiagnosticContext>());
}
}
}