I've created a logger which should log anything during start of application run. And I wanted it to persist between Startup
and ConfigureServices
. I store it in the property similar to configuration
Here is the code
public Startup(IConfiguration configuration)
{
Configuration = configuration;
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.SetMinimumLevel(LogLevel.Error);
builder.AddEventLog(s =>
{
s.LogName = "MyLogName";
s.SourceName = "MySource";
});
// add some other persisting logger
});
StartupLogger = loggerFactory.CreateLogger<Startup>();
}
public IConfiguration Configuration { get; }
public ILogger StartupLogger { get; } // Logger exists here when breakpoint is in ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
StartupLogger.LogError("Failed to do something"); // <-- throws exception
}
This is the error I get. Looks like inner logger gets disposed in the process
Message: "An error occurred while writing to logger(s). (Cannot access a disposed object. Object name: 'EventLogInternal'.
Full stack
'StartupLogger.LogError("Failed to do something")' threw an exception of type 'System.AggregateException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: {"Cannot access a disposed object.\r\nObject name: 'EventLogInternal'."}
InnerExceptions: Count = 1
Message: "An error occurred while writing to logger(s). (Cannot access a disposed object.\r\nObject name: 'EventLogInternal'.)"
Source: "Microsoft.Extensions.Logging"
StackTrace: " at Microsoft.Extensions.Logging.Logger.ThrowLoggingError(List`1 exceptions)\r\n at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)\r\n at Microsoft.Extensions.Logging.Logger`1.Microsoft.Extensions.Logging.ILogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)\r\n at Microsoft.Extensions.Logging.LoggerExtensions.Log(ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, String message, Object[] args)\r\n at Microsoft.Extensions.Logging.LoggerExtensions.LogError(ILogger logger, String message, Object[] args)"
TargetSite: {Void ThrowLoggingError(System.Collections.Generic.List`1[System.Exception])}
Surely I have a wrong approach here. Appreciate some guidance.