0

I would like to add hostname to the log files which is generated by Serilog file sink.

I tried below, but my file name appears as log-{fileName}-20210910.txt for below code,

  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()));

How to access fileName variable while defining serilog configuration?

ouflak
  • 2,458
  • 10
  • 44
  • 49
user584018
  • 10,186
  • 15
  • 74
  • 160

3 Answers3

4

you are missing the $ symbol

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

other option is:

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

For my AspNet Core 6 WebApp I added the steeltoe Placeholder extensions library

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

added the resolver to the configuration

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

and then changed my appsettings

{

  "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" }
      }
    ]
  }
}
Guy Pender
  • 41
  • 6
0

I added the username to the path with this

{"path": "/tmp/logs/webapi/%USERNAME%_.log"}

which picks up username from the environment variables

Ignore
  • 41
  • 5