Serilog文件接收器未记录到文件

时间:2019-05-03 04:06:05

标签: c# .net asp.net-core serilog

我正试图在基于documentation的ASP.Net core 2.2应用程序上运行Serilog文件接收器。我在应用程序中看不到日志。 我想念什么?

Program.cs:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;
using System;

namespace Scrubber
{
  public class Program
  {
    private static string _environmentName;

    public static void Main(string[] args)
    {
      try
      {
        var iWebHost = CreateWebHostBuilder(args).Build();
        var configuration = new ConfigurationBuilder()
          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
          .AddJsonFile($"appsettings.{_environmentName}.json", optional: true, reloadOnChange: true)
        .Build();

        var logger = new LoggerConfiguration()
          .ReadFrom.Configuration(configuration.GetSection("Serilog"))
          .CreateLogger();
        Log.Logger = logger;
        Log.Information("Application starting");
        iWebHost.Run();
      }
      catch(Exception exception)
      {
        Log.Error(exception.ToString());
      }
      finally
      {
        Log.CloseAndFlush();
      }
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
          WebHost.CreateDefaultBuilder(args)
          .ConfigureLogging((hostingContext, config) =>
          {
            //config.ClearProviders();
            _environmentName = hostingContext.HostingEnvironment.EnvironmentName;
          })
          .UseStartup<Startup>();
    }
}

Appsettings.development.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Serilog": {
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "log.txt",
          "rollingInterval": "Day"
        }
      }
    ]
  } 
}

1 个答案:

答案 0 :(得分:2)

一个可能的原因是该应用程序根本没有加载配置。

请注意,您可以通过以下方式设置配置:

   var configuration = new ConfigurationBuilder()
     .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
     .AddJsonFile($"appsettings.{_environmentName}.json", optional: true, reloadOnChange: true)
    .Build();
  1. 您没有为ConfigurationBuilder设置基本路径
  2. 您通过设置optional注册了optional: false json文件

结果,如果json文件不在正确的位置,则它会自动失败。

我建议您可以如下更改代码:

// get the real path 
//     or by reflection 
//     or by injection, 
var path = Directory.GetCurrentDirectory();       // assume the current directory

var configuration = new ConfigurationBuilder()
    .SetBasePath(path)                                                       // set the right path
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)  //  make it required
    .AddJsonFile($"appsettings.{_environmentName}.json", optional: true, reloadOnChange: true)
    .Build();

希望有帮助。