user584018
user584018

Reputation: 11344

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

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?

Upvotes: 1

Views: 7136

Answers (3)

Guy Pender
Guy Pender

Reputation: 41

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"
        }
      }
    ]
  }
}

Upvotes: 3

turhan
turhan

Reputation: 51

I added the username to the path with this

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

which picks up username from the environment variables

Upvotes: 1

brian bentancourt
brian bentancourt

Reputation: 146

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

Upvotes: 4

Related Questions