Serilog - how to customize date in rolling file name?
Asked Answered
N

2

17

In Serilog, you can easily enable rolling log files:

Log.Logger = new LoggerConfiguration()
    .WriteTo.File("log-.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

This will create a new log file every day in the following format:

  • log-20200214.txt
  • log-20200215.txt
  • log-20200216.txt

My question: is it possible to customize where the date is placed in the file name, and to customize how the date is formatted?

e.g. I want the file names to look like this:

  • 2020-02-14-log.txt
  • 2020-02-15-log.txt
  • 2020-02-16-log.txt

I was hoping replacing "log-.txt" with "{Date:yyyy-MM-dd}-log.txt" would work, but it doesn't.

Nygaard answered 14/2, 2020 at 14:13 Comment(3)
use $"{Date:yyyy-MM-dd}-log.txt", then it should work if you have a datefield, if not use instead of Date DateTime.NowFionnula
@Fionnula this solution doesn't work for meYang
i am too expecting the same. but, unfortunately no inbuilt methodology to format it.Hostetler
Q
13

This is not currently supported by the Serilog.Sinks.File sink. If you really want this feature, you can try to send a pull-request, or fork the repository and use your own custom implementation.

Links you might be interested in:

Quaff answered 14/2, 2020 at 14:55 Comment(3)
still not supported, except for the automatically added timestamp when time-based rolling is used?Yang
Yes, that’s correctQuaff
They already have a placeholder '{Timestamp:yyyy-MM-dd HH:mm:ss}' for the outputTemplate, why not applying this logic to the filename. Still not supported today unfortunately.Rockafellow
S
0

Since this is currently not supported, I've made it with Map:

var log = new LoggerConfiguration()
            .WriteTo.Map(
            le => new DateTime(le.Timestamp.Year, le.Timestamp.Month, le.Timestamp.Day),
            (date, wt) => wt.File($"{date:yyyy-MM-dd}-log.txt"))
            .CreateLogger();

Checked the creation of a log file when the day changes via log.Write(new EventLog())

Stump answered 4/7 at 14:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.