截断 .NET 中日志文件的开头
我有一个 VB.NET 应用程序,它以文本格式将状态写入日志文件。随着时间的推移,文件变得越来越大,我想知道是否有一种有效的方法来截断文件的开头。
为了让事情变得更容易,我希望指定一个文件大小(比如 2-3 mb),并且我正在使用 StreamWriter 编写日志:
Using strm As New IO.StreamWriter(filelocation.log, True)
strm.WriteLine("msg to write")
strm.Close()
End Using
我考虑使用 strm.BaseStream.Length
来确定如何要切断的文件的大部分内容,但是通过使用 .SetLength
,它会从末尾开始切断 - 这不是所需的结果。
I have an VB.NET app that writes the status to a log file in text format. Over time, the file is getting large and I wanted to know if there is an efficient way to truncate the beginning of the file.
To make things easier, I am looking to specify a file size (say 2-3 mb) and I am writing the log using a StreamWriter:
Using strm As New IO.StreamWriter(filelocation.log, True)
strm.WriteLine("msg to write")
strm.Close()
End Using
I thought about using the strm.BaseStream.Length
to determine how much of the file to cut off, but by using the .SetLength
it would cut from the end - not the desired result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我强烈建议您查看 log4net 来完成您的日志记录。它非常强大且灵活,并且具有根据您可以指定的大小滚动日志的内置方式。这不是您在这里寻找的答案,但绝对值得研究。以下是我们在调试期间进行日志记录的示例配置:
app.config 文件中的此代码将在应用程序文件夹中创建一个名为 ClientTools.log 的日志文件,以包括日期和时间的特定格式写入该文件,然后滚动日志大小为 3MB。
要使用记录器,我们在网页的 Init() 中执行此操作:
公共 ILog 日志;
然后,当您想要记录某些内容时,请执行以下操作:
您不必担心创建流对象、关闭流、处置流等。而且它非常 干。
I would highly suggest looking at log4net to accomplish your logging. It's extremely powerful and flexible and has a built in way of rolling your logs based on a size you can specify. It's not the answer you're looking for here, but it's definitely worth looking into. Here's a sample config for what we do for logging during debug:
This code in the app.config file will create a log file called ClientTools.log in the application folder, write it in a specific format including the date and time, and roll the log at 3MB.
To use the logger, we do this in Init() of the web page:
public ILog log;
And then when you want to log something, do this:
You don't have to worry about creating a stream object, closing the stream, disposing the stream, etc. And it's very DRY.
为什么不检查文件的字节长度是否大于 3MB,如果是,则覆盖它并重新写入。像这样的事情,(我是 c# 人):
希望这有帮助,
此致,
汤姆.
Why not check if the file's length in bytes is greater than 3MB, if it is, overwrite it and write to it afresh. Something like this, (I'm a c# guy):
Hope this helps,
Best regards,
Tom.
一种方法可以是
One approach could be
您可以检查文件长度并以硬(和脏)方式截断它:
You could check the File-Length and truncate it the hard (and dirty) way:
以下是我用于此目的的几个函数:
还有其他一些需要考虑的事情:
Here are a couple functions that I use for this:
There are a couple other things to consider:
我使用的方法又快又简单。此示例保留日志文件的最新 60 行。
Quick and easy method I use. This example keeps the most recent 60 lines of the log file.