Search code examples
c#asp.net-core-3.1serilogserilog-sinks-file

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?


Solution

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