如何将自定义文件名添加到 serilog 文件接收器生成的日志文件

How to add custom file name to serilog file sink generated logs file

我想将主机名添加到 Serilog 文件接收器生成的日志文件中。

我在下面尝试过,但是对于下面的代码,我的文件名显示为 log-{fileName}-20210910.txt

  vservices.AddLogging(logging => logging.AddSerilog(
            new LoggerConfiguration()
                .WriteTo.RollingFile(Path.Combine(Environment.CurrentDirectory, $"log-{fileName}.txt"),
                    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {fileName}, {Message:lj}{NewLine}{Exception}")
                .CreateLogger()));

如何在定义 serilog 配置时访问 fileName 变量?

您缺少 $ 符号

var fileName = Environment.GetEnvironmentVariable("HOSTNAME") ?? "add-on";
    services.AddLogging(logging => logging.AddSerilog(new LoggerConfiguration()
        .WriteTo.RollingFile(Path.Combine(Environment.CurrentDirectory, $"log-{fileName}.txt"))
        .CreateLogger()));

其他选项是:

var fileName = Environment.GetEnvironmentVariable("HOSTNAME") ?? "add-on";
    services.AddLogging(logging => logging.AddSerilog(new LoggerConfiguration()
        .WriteTo.RollingFile(Path.Combine(Environment.CurrentDirectory, "log-" + fileName + ".txt"))
        .CreateLogger()));

对于我的 AspNet Core 6 WebApp,我添加了 steeltoe Placeholder 扩展库

https://docs.steeltoe.io/api/v2/configuration/placeholder-provider.html

将解析器添加到配置中

public Startup(IConfiguration configuration)
{
    _configuration = configuration.AddPlaceholderResolver();
}

然后更改了我的应用程序设置

{

  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
          "path": "/tmp/logs/webapi/${HOSTNAME}_.log", //Linux version
          //"path": "/tmp/logs/webapi/${COMPUTERNAME}_.log", //Windows version
          "rollingInterval": "Day",
          "rollOnFileSizeLimit": true,
          "fileSizeLimitBytes": 1073741824,
          "retainedFileCountLimit": 31
        }
      },
      {
        "Name": "Seq",
        "Args": { "serverUrl": "http://dc-seq-service:5341" }
      }
    ]
  }
}