使用 ASP.Net Core 5.0 推出 Web API 服务,该服务作为自己的 Windows 服务运行。我试图弄清楚如何使用 Microsoft.Extensions.Logging 将日志写入文件。
我希望能够在随应用程序推出的 appsettings.json 文件中指定日志文件的位置。我觉得我失去了一些东西。
为了实现此目的,我是否必须使用另一个带有 Microsoft.Extensions.Logging 的库(例如 Serilog)?我已阅读下面的链接,但没有看到任何有关文件日志记录的内容。
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-5.0
我来自使用 log4Net 的背景,但无法理解如何让 Microsofot.Extensions.Logging 工作。
我尝试了 Serilog,但遇到了一个问题:当我调试时,项目似乎总是在 IIS Express 下运行,即使我将配置文件设置为项目名称,并将“启动”设置为“项目”。
我在这里缺少什么?
ASP.NET Core 不包含用于将日志写入文件的日志记录提供程序。要将日志从 ASP.NET Core 应用程序写入文件,请考虑使用第三方日志记录提供程序。
使用 Serilog 对我来说效果很好。
程序.cs:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
namespace WebApplication
{
public class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false)
.Build();
var path = config.GetValue<string>("Logging:FilePath");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.File(path)
.CreateLogger();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序设置.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"FilePath" : "logs/AppLog.txt"
},
"AllowedHosts": "*"
}
Run Code Online (Sandbox Code Playgroud)
控制器(或服务,无论您需要什么):
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace WebApplication
{
[ApiController]
public class MyController : ControllerBase
{
private readonly ILogger<MyController> _logger;
public MyController(ILogger<MyController> logger)
{
_logger = logger;
}
[HttpGet("/test")]
public ActionResult<string> Test()
{
_logger.LogInformation("Hello World.");
return "Success";
}
}
}
Run Code Online (Sandbox Code Playgroud)
我安装的软件包:
<ItemGroup>
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)
至于在 IISExpress 上运行,这取决于您拥有的 launchSettings.json,不确定您的问题是什么。通常,您在配置文件中对 Kestrel使用"commandName": "Project" ,对 IISExpress使用 "commandName": "IISExpress" 。然后,您的 IDE 让您选择想要的运行配置。
归档时间: |
|
查看次数: |
6181 次 |
最近记录: |