问题描述: 在Asp.Net Core Web Api项目中,我想从App.config文件中读取Nlog配置,但是无法加载目标。
解决方法: 在Asp.Net Core项目中,不再使用App.config文件作为配置文件,而是使用appsettings.json文件作为配置文件。因此,需要将Nlog配置从App.config文件迁移到appsettings.json文件中。
以下是解决方法的步骤:
创建一个名为appsettings.json的文件,将其添加到项目的根目录下。
在appsettings.json文件中添加Nlog的配置,例如:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"NLog": {
"AutoReload": true,
"ThrowConfigExceptions": true,
"InternalLogLevel": "Info",
"InternalLogFile": "Logs/internal-nlog.txt",
"Targets": {
"Console": {
"Name": "Console",
"Layout": "${longdate}|${level:uppercase=true}|${logger}|${message} ${exception}"
}
},
"Rules": [
{
"Name": "*",
"MinLevel": "Trace",
"WriteTo": "Console"
}
]
}
}
}
public void ConfigureServices(IServiceCollection services)
{
// ...
// 添加Nlog
services.AddLogging(loggingBuilder =>
{
loggingBuilder.AddNLog(Configuration.GetSection("Logging"));
});
// ...
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
webBuilder.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
});
})
.UseNLog();
private readonly ILogger _logger;
public HomeController(ILogger logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("Hello, Nlog!");
return View();
}
通过以上步骤,你就可以从appsettings.json文件中成功加载Nlog配置并进行日志记录了。