我创建了自己的自定义日志提供程序FileLogerProviderr来将日志保存到文件中。
我在程序中添加了自定义文件记录器提供程序.cs:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddProvider(new FileLoggerProvider(Path.Combine(Directory.GetCurrentDirectory(), "logger.txt")));
logging.SetMinimumLevel(LogLevel.None);
})
.UseStartup<Startup>();
为了测试我添加了登录控制器:
public class HomeController : Controller
{
private ILogger<HomeController> logger;
public HomeController(ILogger<HomeController> log)
{
logger = log;
}
public IActionResult Index()
{
logger.LogDebug($"test index path!!!");
return View();
}
}
工作,但是在除测试索引路径之外的文件中,我看到了许多其他信息。我不需要这些信息。我只需要将控制器中的日志保存在文件中。
Request starting HTTP/1.1 GET http://localhost:44339/
Route matched with {action = "Index", controller = "Home", page = "", area = ""}. Executing action LoggingTest.Controllers.HomeController.Index (LoggingTest)
Executing action method LoggingTest.Controllers.HomeController.Index (LoggingTest) - Validation state: Valid
test index path!!!
Executed action method LoggingTest.Controllers.HomeController.Index (LoggingTest), returned result Microsoft.AspNetCore.Mvc.ViewResult in 11.8159ms.
Executing ViewResult, running view Index.
Executed ViewResult - view Index executed in 43.4928ms.
Executed action LoggingTest.Controllers.HomeController.Index (LoggingTest) in 224.1184ms
Request finished in 400.2906ms 200 text/html; charset=utf-8
Request starting HTTP/1.1 GET http://localhost:44339/favicon.ico
Sending file. Request path: '/favicon.ico'. Physical path: 'C:UsersdborovskyprojectsLoggingTestLoggingTestwwwrootfavicon.ico'
Request finished in 39.8394ms 200 image/x-icon
我该如何解决这个问题?谢谢
更新appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "CONSTRING"
},
"Logging": {
"LogLevel": {
"Default": "None",
"System": "None",
"Microsoft": "None"
}
},
"AllowedHosts": "*"
}
也许您希望使用配置来防止记录所有事件。
我建议您在配置服务(.从程序配置日志记录.cs至少你想记录虚拟主机事件(:
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging(loggers=>
{
loggers.AddConsole();
loggers.AddDebug();
loggers.AddProvider(new FileLoggerProvider(Path.Combine(Directory.GetCurrentDirectory(), "logger.txt")));
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
然后,您可以按如下方式进行配置(确保您已正确配置环境变体(:
{
"ConnectionStrings": {
"DefaultConnection": "CONSTRING"
},
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "None",
"Microsoft": "None"
}
},
"AllowedHosts": "*"
}
和实现:
public class HomeController : Controller
{
private ILogger<HomeController> logger;
public HomeController(ILogger<HomeController> log)
{
logger = log;
}
public IActionResult Index()
{
logger.LogDebug($"test index path!!!");
return View();
}
}
这是Microsoft关于日志记录的非常好的文章:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2