0

使用 ASP.Net Core 5.0 推出作为其自己的 Windows 服务运行的 Web API 服务。我试图弄清楚如何使用 Microsoft.Extensions.Logging 将日志写入文件。

我希望能够在应用程序推出的 appsettings.json 文件中指定日志文件的位置。我觉得我错过了什么。

我是否必须使用另一个带有 Microsoft.Extensions.Logging 的库(如 Serilog)才能完成此操作?我已经阅读了下面的链接,没有看到任何关于文件日志的信息。

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-5.0

我来自我们使用 log4Net 的背景,但无法理解如何让 Microsofot.Extensions.Logging 工作。

我尝试了 Serilog,但遇到了一个问题,即在调试时,项目似乎总是在 IIS Express 下运行,即使我将配置文件设置为项目名称,并将“启动”设置为“项目”。

我在这里想念什么?

4

2 回答 2

2

从微软文档

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>(); });
    }
}

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "FilePath" : "logs/AppLog.txt"
  },
  "AllowedHosts": "*"
}

控制器(或服务,无论您需要什么):

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";
        }
    }
}

我安装的软件包:

<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>

至于在 IISExpress 上运行,这取决于您拥有的 launchSettings.json,不确定您的问题是什么。通常,您在配置文件中对 Kestrel使用"commandName": "Project" ,对 IISExpress 使用"commandName": "IISExpress"。然后,您的 IDE 允许您选择想要的运行配置。

于 2021-06-02T09:51:43.630 回答
0

我的解决方案基于 Jakob 的解决方案,并进行了一些小改动

在 appSettings.json 我添加了文件路径:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    },
    "FilePath": "logs/AppLog.txt"
  },
  "AllowedHosts": "*"
}

在 Program.cs 我添加了以下代码:

using Serilog;

var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false)
    .Build();

var builder = WebApplication.CreateBuilder(args);

// Apply logging 
builder.Logging.ClearProviders();
var path = config.GetValue<string>("Logging:FilePath");
var logger = new LoggerConfiguration()
    .WriteTo.File(path)
    .CreateLogger();
builder.Logging.AddSerilog(logger);

我还安装了 Nuget 包:Serilog、Serilog.AspNetCore 和 Serilog.Sinks.File

在我的控制器的构造函数中,我提供了记录器,这样我就可以在整个控制器中使用记录器:

private readonly ILogger<ExampleController> _logger;

public ExampleController(ILogger<ExampleController> logger)
{
    _logger = logger;
}

现在,每当我记录异常时,我都会调用_logger.LogError(ex.Message); 并且此错误将写入记录器文件中,该文件在 appSettings.json 中定义

于 2022-01-21T11:49:57.273 回答