Is it possible to configure Serilog to truncate (i.e. make empty) the log file for each new process?

浪子不回头ぞ 提交于 2021-01-27 07:20:38

问题


Moving from nlog to serilog, I would like my .NET framework desktop application to reuse a statically-named log file each time I run it, but to clear out the contents of the file with each new process. Is it possible to configure serilog this way?

This is a similar question, but it's not quite the same. In the linked question, the user uses a new log file each time with a unique filename. In my case, I want to use the same log file name each time.


回答1:


This is not something Serilog can do for you as of this writing.

Serilog.Sinks.File is hard-coded to open the file with FileMode.Append thus if the file already exists, it will always append contents at the end of the file.

FileLifecycleHooks allows you to intercept when the file is being opened, and that would give you an opportunity to remove the contents of the file (by calling SetLength(0) on the stream), but unfortunately the stream implementation that Serilog.Sinks.File uses (WriteCountingStream) does not support SetLength.

Your best bet is to just truncate or delete the log file yourself at the start of the app, and let Serilog create a new one.

e.g.

// Ensure that the log file is empty 
using (var fs = File.OpenWrite("mylog.log")) { fs.SetLength(0); }

// ... Configure Serilog pipeline


来源:https://stackoverflow.com/questions/64657367/is-it-possible-to-configure-serilog-to-truncate-i-e-make-empty-the-log-file-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!