Salih H.
Salih H.

Reputation: 102

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

Upvotes: 0

Views: 1026

Answers (1)

Salih H.
Salih H.

Reputation: 102

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

Upvotes: 1

Related Questions