Clear a log file at runtime:Used by another process error

对着背影说爱祢 提交于 2019-12-11 05:14:31

问题


I am using serilog framework in my application. In my application when the log file size reaches 2MB, im creating a backup of log file by renaming the existing file from file.log to file.log.bak and creating a new file.log. At runtime i was facing issue reading the log file, "the process logfile is used by another process" error was shown. so i used below code to read the content of serilog file.

Stream stream = File.Open (_filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader streamReader = new StreamReader (stream);
string str = streamReader.ReadToEnd ();

But now im not able to clear the log file. I get the same error. How do i clear the content of log file at runtime?


回答1:


If you have a logger instante as below

var _logger = new LoggerConfiguration()
                .WriteTo.File("Logs/log.log", shared: true)
                .CreateLogger();

You will need to dispose it before dealing with current log file

_logger.Dispose();

Then do needed modifications

string str = string.Empty;
using (Stream stream = System.IO.File.Open("Logs/log.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using (StreamReader streamReader = new StreamReader(stream))
    {
        str = streamReader.ReadToEnd();
        //.....
    }
}

and create new logger instance again so you can continue logging

_logger = new LoggerConfiguration()
    .WriteTo.File("Logs/log.log", shared: true)
    .CreateLogger();


来源:https://stackoverflow.com/questions/55487202/clear-a-log-file-at-runtimeused-by-another-process-error

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