Sch*_*mmy 5 sql-server nlog asp.net-core
我一直在尝试让 ASP.NET Core 站点与 NLog 一起工作。它工作正常,直到我尝试写入 SQL 数据库。我试过本地数据库和 Azure 数据库 - 都遇到了同样的问题。我什至将 nlog 表添加到一个已知的数据库中,该站点已经连接到(使用 EF)。
我正在使用 nuget 包:NLog.Web.AspNetCore
无论如何,我得到以下信息:
写入数据库时出错。异常:System.Data.SqlClient.SqlException (0x80131904):建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。
这是我配置事物的方式(我尝试更改这些语句的顺序):
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog();
app.AddNLogWeb();
env.ConfigureNLog("nlog.config");
LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection");
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
//etc...
Run Code Online (Sandbox Code Playgroud)
这是我的 nlog 配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog();
app.AddNLogWeb();
env.ConfigureNLog("nlog.config");
LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection");
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
//etc...
Run Code Online (Sandbox Code Playgroud)
最后,这是我的 appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\projectsV13;Database=XXXX;Trusted_Connection=True;MultipleActiveResultSets=true",
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
Run Code Online (Sandbox Code Playgroud)
您没有在数据库目标中使用变量“connectionString”。
你还需要
<target name="db"
..
connectionString="${var:connectionString}"
>
Run Code Online (Sandbox Code Playgroud)
NLog 中的变量不会自动绑定到目标。您需要在配置中设置和使用它们。
更新
从 NLog.Web.AspNetCore 4.8(.NET Core 控制台程序的 NLog.Extensions.Logging 1.4)开始,您可以直接从 appSettings.json 读取
<target name="db"
..
connectionString="${configsetting:name=ConnectionStrings.DefaultConnection}"
>
Run Code Online (Sandbox Code Playgroud)
请参阅文档
| 归档时间: |
|
| 查看次数: |
1159 次 |
| 最近记录: |