Приемник файла Serilog не входит в файл - PullRequest
0 голосов
/ 03 мая 2019

Я пытаюсь заставить приемник файлов Serilog работать над моим приложением ASP.Net core 2.2 на основе документации . Я не могу видеть журналы в моем приложении. Чего мне не хватает?

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 Ответ

2 голосов
/ 03 мая 2019

Возможная причина в том, что приложение вообще не загружало конфигурацию.

Обратите внимание, что вы настроили конфигурацию следующим образом:

   var configuration = new ConfigurationBuilder()
     .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
     .AddJsonFile($"appsettings.{_environmentName}.json", optional: true, reloadOnChange: true)
    .Build();
  1. Вы не установили базовый путь для ConfigurationBuilder
  2. Вы зарегистрировали файл optional json, установив optional: false

В результате, если файл 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();

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...