我试图将PostgreSQL的connectionString和我的Log目录传递给Main方法中的nlog.config文件,我该如何实现?
我目前正在做this之类的事情 在Startup.cs中:
NLog.LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("databaseConnectionString");
NLog.LogManager.Configuration.Variables["configDir"] = Configuration.GetValue<string>("Logging:LogFilePath");
我遇到的唯一问题是,如果我尝试在Main方法中记录某些内容,那么在此数据库记录正常工作之后:
Error when writing to database. Exception: System.ArgumentException: Host can't be null
at Npgsql.NpgsqlConnector.d__145.MoveNext() ---从抛出异常的先前位置开始的堆栈跟踪结束--- 在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在Npgsql.ConnectorPool.d__24.MoveNext()
答案 0 :(得分:1)
我找到了在Main方法中加载Configuration的方法,如果有人需要它,这是一种方式:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json");
Configuration = builder.Build();
然后我使用NLog.ConfigurationManager来设置connectionString和Log目录:
NLog.LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("databaseConnectionString");
NLog.LogManager.Configuration.Variables["configDir"] = Configuration.GetValue<string>("Logging:LogFilePath");