简体   繁体   中英

NLog pass Configuration values(ConnectionString and configDir) to nlog.config in Main method

I'm trying to pass connectionString for PostgreSQL and my Log directory to nlog.config file in Main method, how can I achieve this?

I'm currently doing something like this in Startup.cs:

NLog.LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("databaseConnectionString");
NLog.LogManager.Configuration.Variables["configDir"] = Configuration.GetValue<string>("Logging:LogFilePath");

Only problem I have is if I try to log something in Main method, after this DB logging is working fine:

Error when writing to database. Exception: System.ArgumentException: Host can't be null

at Npgsql.NpgsqlConnector.d__145.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Npgsql.ConnectorPool.d__24.MoveNext()

I found the way to load Configuration in Main method, here is a way if anyone ever needs it:

var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json");

        Configuration = builder.Build();

And then I use NLog.ConfigurationManager to setup connectionString and Log directory:

 NLog.LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("databaseConnectionString");
 NLog.LogManager.Configuration.Variables["configDir"] = Configuration.GetValue<string>("Logging:LogFilePath");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM