Почему Serilog не регистрирует, что находится в моем контроллере API Blazor wasm .net 6?

У меня есть проект Blazor wasm .net 6, размещенный на хосте.

Я настроил serilog для записи в файл и mssqlserver. Я отлично работаю с журналом из serilog.aspnetcore, но когда я пытаюсь использовать Log.Debug(...) в моем контроллере API, ничего не регистрируется в файле или на сервере sql.

Program.cs в Blazor.Server

      public class Program
{
    public static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
           .SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json")
           .Build();

        Serilog.Events.LogEventLevel logEventLevelFile = (Serilog.Events.LogEventLevel)Enum.Parse(typeof(Serilog.Events.LogEventLevel), configuration.GetSection("Serilog:MinimumLevelFile").Value);
        Serilog.Events.LogEventLevel logEventLevelDB = (Serilog.Events.LogEventLevel)Enum.Parse(typeof(Serilog.Events.LogEventLevel), configuration.GetSection("Serilog:MinimumLevelDB").Value);

        Log.Logger = new LoggerConfiguration()
                .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Month, restrictedToMinimumLevel: logEventLevelFile)
                .WriteTo.MSSqlServer(connectionString: configuration.GetSection("Serilog:ConnectionStrings:LogDatabase").Value,
                                        restrictedToMinimumLevel: logEventLevelDB,
                                       sinkOptions: new MSSqlServerSinkOptions
                                       {
                                           TableName = configuration.GetSection("Serilog:TableName").Value,
                                           SchemaName = configuration.GetSection("Serilog:SchemaName").Value
                                       },
                                       appConfiguration: configuration
                                       , columnOptionsSection: configuration.GetSection("Serilog:ColumnOptions"))
               .CreateBootstrapLogger();

        Serilog.Debugging.SelfLog.Enable(msg =>
        {
            Debug.Print(msg);
            Debugger.Break();
        });

        try
        {
            Log.Information("Application starting up.");

            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "The application failed to start up correctly.");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        var builder = Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            }).UseSerilog();

        return builder;
    }
}

appsettings.json

      "Serilog": {
    "Using": [ "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevelFile": "Debug",
    "MinimumLevelDB": "Debug",
    "ConnectionStrings": {
      "LogDatabase": "...valid connection string ..."
    },
    "SchemaName": "dbo",
    "TableName": "Logs"
  },

UserController.cs

      
public UserController(){}

    // GET: api/user
    [AllowAnonymous]
    [HttpGet]
    public IActionResult Get(string empId)
    {
        Log.Debug($"{HttpContext.Request.Path} => Loading current user from Query String: {empId}");
        ....

У меня есть очень похожий проект в .net 6 (Angular вместо Blazor wasm), и все работает нормально. Пользовательский контроллер такой же.

Я пытался переместить конфигурацию, например, переместить ее в .UseSerilog() CreateHostBuilder, но не повезло.

Почему Serilog не регистрирует то, что находится в моем контроллере API?

1 ответ

Похоже, что уровень ведения журнала по умолчанию «Информация» был применен, даже если я устанавливал уровень для каждого приемника.

      Log.Logger = new LoggerConfiguration()
                .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Month, restrictedToMinimumLevel: logEventLevelFile)
                .WriteTo.MSSqlServer(connectionString: configuration.GetSection("Serilog:ConnectionStrings:LogDatabase").Value,
                                        restrictedToMinimumLevel: logEventLevelDB,
                                       sinkOptions: new MSSqlServerSinkOptions
                                       {
                                           TableName = configuration.GetSection("Serilog:TableName").Value,
                                           SchemaName = configuration.GetSection("Serilog:SchemaName").Value
                                       },
                                       appConfiguration: configuration
                                       , columnOptionsSection: configuration.GetSection("Serilog:ColumnOptions"))
               .CreateBootstrapLogger();

Установка минимального уровня на Verbose устранила проблему.

      Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Verbose()
                .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Month, restrictedToMinimumLevel: logEventLevelFile)
                .WriteTo.MSSqlServer(connectionString: configuration.GetSection("Serilog:ConnectionStrings:LogDatabase").Value,
                                        restrictedToMinimumLevel: logEventLevelDB,
                                       sinkOptions: new MSSqlServerSinkOptions
                                       {
                                           TableName = configuration.GetSection("Serilog:TableName").Value,
                                           SchemaName = configuration.GetSection("Serilog:SchemaName").Value
                                       },
                                       appConfiguration: configuration
                                       , columnOptionsSection: configuration.GetSection("Serilog:ColumnOptions"))
               .CreateBootstrapLogger();
Другие вопросы по тегам