首页 > 解决方案 > 部署到 Server 2019 上的 IIS 时,asp.net 5 中的 ILogger 无法正常工作

问题描述

我有一个使用 asp.net 5 的简单 Web API。我添加了一个跟踪侦听器,以便在添加调试时 ILogger 输出到一个文件。这在调试和发布模式下的测试(在 VS2019 中)都可以正常工作。但是当我将它部署到 IIS 时,它什么也没输出。它确实设法创建了日志文件,但从未在其中放入任何内容。

我的 appsettings.json 在 dev 和 Prod 中是一样的......我还需要另一个文件吗?

    {
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

这也是我的 abSoundAPI.runtimeconfig.json

{
  "runtimeOptions": {
    "tfm": "net5.0",
    "framework": {
      "name": "Microsoft.AspNetCore.App",
      "version": "5.0.0"
    },
    "configProperties": {
      "System.GC.Server": true,
      "System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }

}

这是我的程序课:

public static void Main(string[] args)
    {
        TextWriterTraceListener fileOutListener = new("abSoundAPI.log", "fileOutListnener");
        Trace.Listeners.Add(fileOutListener);
        Trace.AutoFlush = true;

        try
        {
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception e)
        {
            Trace.WriteLine($"Fatal Exception {e.Message}");
            throw new Exception("Failed to start!");
        }
        finally
        {
            //Trace.Flush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging((context, logging) =>
            {
                logging.ClearProviders(); // see comments in code F12 on the CreateHostBuilder above
                logging.AddConfiguration(context.Configuration.GetSection("Logging"));
                logging.AddDebug();
                logging.AddConsole();
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

标签: asp.net-coreloggingiis-10asp.net5ilogger

解决方案


您是否检查过是否有任何特定于环境的文件,例如 appsettings.development.json?因为在 iis 中设置了 asp.net 应用程序,所以应该使用 appsettings.development.json 而不是 appsettings.json。

您应该修改 appsettings.development.json 如下:

{
 "Logging": {
   "LogLevel": {
     "Default": "Trace",
     "Microsoft": "Warning",
     "Microsoft.Hosting.Lifetime": "Information"
   }
 }
}

推荐阅读