0

I am having an issue formatting the date in the filename using the appsettings.json file for a C# worker service.

My current config looks like this:

Serilog": {
    "WriteTo": [
        {
            "Name": "File",
            "Args": {
                "path": "C:\\Program Files (x86)\\Alarm\\AlarmServiceLogs\\AlarmService.txt",
                "rollingInterval": "Day"
            }
        }
    ]
}

It's very basic. I tried adding {Date: yyyy-DD-MM} and other variations as well as using pathFormat rather than path, but that all just seems to add the verbatum text to the log file name.

Is this doable from the .json file? Otherwise I will do it directly in code as I have with other logs. Just trying to be consistent with my log file naming.

1

2 Answers 2

0

First you have to make sure you configured you application to load the config correctly:
Example from Serilog:

static void Main(string[] args)
{
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
        .Build();

    var logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        .CreateLogger();

    logger.Information("Hello, world!");
}

If you did this you have to correctly structure your json like this: https://github.com/serilog/serilog-sinks-rollingfile?tab=readme-ov-file#controlling-event-formatting

{
  "Serilog": {
    "WriteTo": [
      { "Name": "RollingFile", "Args": { "pathFormat": "log-{Date}.txt" } }
    ]
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Your example here is using the rolling file sink, which has been deprecated for a long time. Instead, the file sink should be used, which supports rolling functionality.
Do you have a code sample for that?
The page I linked to has documentation.
0

@Nathan you can find a [code sample here](https://github.com/serilog/serilog-settings-configuration/blob/dev/sample/Sample)

Appsettings should work with the following:

{
  "Serilog": {
    "WriteTo": [
      { "Name": "File", "Args": { "path": "log-{Date}.txt", "rollingInterval": "Day" } }
    ]
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.