Serilog处理/关闭日志文件流

问题描述 投票:2回答:1

最近,我专注于Serilog,以指出基于每个LogEvent的当前日期的模板化路径。在弄清楚如何实现这一点之后,我终于通过使用LogEvent将Date字段转换为Serilog.Sinks.Map来动态地解决了路径,如下所示:

return new LoggerConfiguration().WriteTo
    .Map(
        // Log key
        (LogEvent le) => le.Timestamp.Date,
        // Log Action
        (DateTime date, LoggerSinkConfiguration lc) =>
        {
            string path = GetFilesPath(date, logName);
            lc.File(path);
        }
    );
public string GetFilePath(DateTime date, string logName) =>
            Path.Combine("./Logs", $"{date:yyyy-MM-dd}", $"{logName}.log");

这样,我实现了我的目标:根据日期在子文件夹中写入日志。

问题是,由于Serilog不知道指向路径已更改,因此它没有按预期方式关闭或处理文件流。因此,我的应用程序无限制地每天打开文件。

[如果有人遇到了这种方法,可以手动关闭流,或者Serilog API以某种方式公开地自动关闭那些流,那就太好了。

顺便说一句,我正在使用

  • Serilog 2.9.0
  • Serilog.Sinks.File 4.1.0
  • Serilog.Sinks.Map 1.0.1
c# logging stream serilog
1个回答
0
投票

Serilog.Sinks.Map接受参数sinkMapCountLimit来控制它:

return new LoggerConfiguration().WriteTo
    .Map(
        // Log key
        (LogEvent le) => le.Timestamp.Date,
        // Log Action
        (DateTime date, LoggerSinkConfiguration lc) =>
        {
            string path = GetFilesPath(date, logName);
            lc.File(path);
        },
        sinkMapCountLimit: 5
    );
© www.soinside.com 2019 - 2024. All rights reserved.