Serilog Net Core 3.1未创建任何日志文件

问题描述 投票:0回答:1

我在.NET Core 3.1项目中,并且我正在使用Serilog进行日志管理。该项目部署在IIS下的Windows服务器上。此外,我还有一个文件服务器可用于存储日志文件。 IIS用户对此文件服务器具有读取和写入权限,因为已经有其他Web应用程序登录此服务器。服务器在服务器之间可见且可访问。

我以以下方式实现了Serilog:

public class Program 
{
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args) 
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.UseIISIntegration();
                })
                .ConfigureAppConfiguration((context, builder) =>
                {
                    // Here I recover the configuration correctly
                    var configuration = GetConfiguration();
                })
                .UseSerilog((hostingContext, loggerConfiguration) => 
                {
                     // hostingContext.Configuration.GetLogOuput() is a custom extension methods.
                     var pathLogFile = Path.Combine(hostingContext.Configuration.GetLogOutput(), hostingContext.HostingEnvironment.ApplicationName, "concurrentFlat.json");

                    if (hostingContext.HostingEnvironment.IsDevelopment())
                    {
                        loggerConfiguration
                          .MinimumLevel.Debug()
                          .Enrich.FromLogContext()
                          .Enrich.WithMachineName()
                          .Enrich.WithEnvironmentUserName()
                          .Enrich.WithProcessId()
                          .Enrich.WithProcessName()
                          .Enrich.WithThreadId()
                          .Enrich.WithProperty("ApplicationName", hostingContext.HostingEnvironment.ApplicationName)
                          .Enrich.WithProperty("Environment", hostingContext.HostingEnvironment.EnvironmentName)
                          .WriteTo.Console()
                          .WriteTo.File(
                              path: pathLogFile,
                              formatter: new CompactJsonFormatter(),
                              rollOnFileSizeLimit: true,
                              fileSizeLimitBytes: 10000000
                          );
                    }
                    else
                    {
                        loggerConfiguration
                             .MinimumLevel.Information()
                             .Enrich.FromLogContext()
                             .Enrich.WithMachineName()
                             .Enrich.WithEnvironmentUserName()
                             .Enrich.WithProcessId()
                             .Enrich.WithProcessName()
                             .Enrich.WithThreadId()
                             .Enrich.WithProperty("ApplicationName", hostingContext.HostingEnvironment.ApplicationName)
                             .Enrich.WithProperty("Environment", hostingContext.HostingEnvironment.EnvironmentName)
                             .WriteTo.File(
                                 path: pathLogFile,
                                 formatter: new CompactJsonFormatter(),
                                 rollOnFileSizeLimit: true,
                                 fileSizeLimitBytes: 10000000
                             );
                    }
                });
}

使用开发配置,一切正常,当我尝试在生产环境(始终将环境变量ASPNETCORE_ENVIRONMENT设置为Production)中始终在本地计算机上模拟应用程序的行为时,行为是预期的。此方法:“ hostingContext.Configuration.GetLogOutput()”从环境变量读取文件服务器的路径。我已经验证它是正确的,但是没有创建文件。

这是一个使用.NET Core ILoggger界面的代码段:

using Microsoft.Extensions.Logging;

public class FooController : Controller
{
    private readonly ILogger<FooController> _logger;

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

    public async Task<IActionResult> Get() 
    {
        _logger.LogError("Test Error log");
         return Ok();
    }
}

您是否知道为什么未在文件服务器上创建日志文件?

提前感谢

file asp.net-core iis logging serilog
1个回答
0
投票

我已经测试了您的代码,并且看起来工作良好。因此,我认为您可以检查下面的列表以查看是否与我的有所不同,

  1. 版本
  <ItemGroup>
    <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
    <PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
    <PackageReference Include="Serilog.Enrichers.Process" Version="2.0.1" />
    <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
    <PackageReference Include="Serilog.Extensions.Logging.File" Version="2.0.0" />
  </ItemGroup>
  1. 使用普通日志路径替换为pathLogFile变量进行测试
public static class CustomConfigurationExtension
{
    public static string GetLogOutput(this IConfiguration config) => "log";
}  
  1. 用于测试的不同环境(DevelopmentProduction等)的设置琐碎的appsettings.json路径

Startup.cs

.ConfigureHostConfiguration(config =>
{
    config.SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
        .AddEnvironmentVariables();
})
  1. 使用此appsetting.json进行测试

appsettings.json

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    }
  },
  "AllowedHosts": "*"
}

上面的大多数示例我都遵循github中的serilog EarlyInitializationSample。这是我测试过的全部内容。希望会有所帮助。

Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
            webBuilder.UseIISIntegration();
        })
        .ConfigureHostConfiguration(config =>
        {
            config.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
                .AddEnvironmentVariables();
        })
        .UseSerilog((hostingContext, loggerConfiguration) =>
        {
            var pathLogFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                hostingContext.Configuration.GetLogOutput(), 
                hostingContext.HostingEnvironment.ApplicationName,
                "concurrentFlat.json"
            );

            if (hostingContext.HostingEnvironment.IsDevelopment())
            {
                loggerConfiguration
                  .MinimumLevel.Debug()
                  .Enrich.FromLogContext()
                  .Enrich.WithMachineName()
                  .Enrich.WithEnvironmentUserName()
                  .Enrich.WithProcessId()
                  .Enrich.WithProcessName()
                  .Enrich.WithThreadId()
                  .Enrich.WithProperty("ApplicationName", hostingContext.HostingEnvironment.ApplicationName)
                  .Enrich.WithProperty("Environment", hostingContext.HostingEnvironment.EnvironmentName)
                  .WriteTo.Console()
                  .WriteTo.File(
                      path: pathLogFile,
                      rollingInterval: RollingInterval.Day,
                      formatter: new CompactJsonFormatter(),
                      rollOnFileSizeLimit: true,
                      fileSizeLimitBytes: 10000000
                  );
            }
            else
            {
                loggerConfiguration
                     .MinimumLevel.Information()
                     .Enrich.FromLogContext()
                     .Enrich.WithMachineName()
                     .Enrich.WithEnvironmentUserName()
                     .Enrich.WithProcessId()
                     .Enrich.WithProcessName()
                     .Enrich.WithThreadId()
                     .Enrich.WithProperty("ApplicationName", hostingContext.HostingEnvironment.ApplicationName)
                     .Enrich.WithProperty("Environment", hostingContext.HostingEnvironment.EnvironmentName)
                     .WriteTo.File(
                         path: pathLogFile,
                         formatter: new CompactJsonFormatter(),
                         rollOnFileSizeLimit: true,
                         fileSizeLimitBytes: 10000000
                     );
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.