是否可以将 Serilog 配置为截断(即清空)每个新进程的日志文件? [英] Is it possible to configure Serilog to truncate (i.e. make empty) the log file for each new process?

查看:99
本文介绍了是否可以将 Serilog 配置为截断(即清空)每个新进程的日志文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 nlog 转移到 serilog,我希望我的 .NET 框架桌面应用程序在每次运行时重用静态命名的日志文件,但要清除每个新进程的文件内容.可以这样配置serilog吗?

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.

推荐答案

在撰写本文时,这不是 Serilog 可以为您做的事情.

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

Serilog.Sinks.File 被硬编码以使用 FileMode.Append 打开文件,因此如果文件已经存在,它将始终在文件末尾附加内容.

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 允许您在打开文件时进行拦截,并且这将使您有机会删除文件的内容(通过在流上调用 SetLength(0)),但不幸的是 Serilog.Sinks.File 使用的流实现(WriteCountingStream) 不支持 SetLength.

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.

最好的办法是在应用程序启动时自己截断或删除日志文件,然后让 Serilog 创建一个新的.

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.

例如

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

// ... Configure Serilog pipeline

这篇关于是否可以将 Serilog 配置为截断(即清空)每个新进程的日志文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆