0
votes

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()

1

1 Answers

1
votes

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");