1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[C#] GenericHost環境でSerilogを年や月フォルダに振り分けさせる

Last updated at Posted at 2021-07-07

あらまし

Serilogの出力をフォイルに保存する際に、年/月/日.txtのように保存したくて情報探しまくった結果、やっとこさ見つかったのでそのメモ

方法

いつものSerilog.Sinks.ConsoleSerilog.Sinks.Fileに加え、Serilog.Sinks.Mapをパッケージ参照として加える

あとは、以下のissueに書かれた方法で年や月フォルダに振り分けできる。

GenericHostでの実装例

WriteToに次いで指定するMapメソッドの引数にて、

  • 引数keySelectorで日付を作成
  • 引数configurekeySelectorで作成した日付を基にフォルダパスを構成
await Host.CreateDefaultBuilder(args)
    .ConfigureServices((ctx, services) => {
        // snip...
    })
    .ConfigureLogging((logging) => {
        logging.ClearProviders();

        var logger = 
            new LoggerConfiguration()           
            .WriteTo.Map(
                keySelector: logEvent => new DateTime(logEvent.Timestamp.Year, logEvent.Timestamp.Month, logEvent.Timestamp.Day),
                configure: (month, writer) => {
                    writer.File(path: $"./logs/{month:yyyy}/{month:yyyyMM}/log-{month:yyyyMMdd}.txt", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information);
                },
                sinkMapCountLimit: 1
            )
            .WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information)
            .CreateLogger()
        ;

        logging.AddSerilog(logger);
    })
    .RunConsoleAsync()
;
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?