logging: ASP .NET Core 5 usage: cannot read log file content - The process cannot access the file '...' because it is being used by another process
Hello.
I use your library in ASP .NET Core 5 Web app. In Startup.cs inside ConfigureServices(IServiceCollection services) I have:
services.AddLogging(loggingBuilder => {
loggingBuilder.AddFile("Logs/app.log", options => {
options.Append = true;
options.MinLevel = LogLevel.Warning;
options.FileSizeLimitBytes = 5 * 1024 * 1024;
options.MaxRollingFiles = 1000;
});
});
In Program.cs I resolve Ilogger via host.Services.GetService<ILogger<TelegramBot>>() and pass it to the constructor of a TelegramBot class. Inside the constructor logger is saved in local variable that is later used to log some events with logger.LogWarning() (specifically - bot start\stop events).
On some page in my application I’m trying to read log file content with the following code (start\stop events are definitely doesn’t happend and logger.LogWarning() is definitely not called at that moment):
try
{
using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
....
}
catch (IOException ex)
{
//Here I get 'The process cannot access the file '...' because it is being used by another process'
}
but I get IOException
The process cannot access the file ‘…’ because it is being used by another process
So what’s wrong with my library usage? How can I properly read log file content? Can it be that logger unblocks log file only on Dispose() event? Should it live as short as possible (resolve->write log->dispose)?
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 1
- Comments: 24 (9 by maintainers)
@bairog The issue is that what is opening the file needs to have
FileShare.ReadWrite(as suggested by @zoran-petrovic-87). This will allow the file to be written to while you are reading it. The docs description is a tad misleading on this but essentially if the file is already open for writing, and you’re only willing to share with others reading it when you try to open it, you come off second best. Note thatFileShare.Readseems to be the default in .NET 5 if you’re not explicit.Why I end up with the file not even readable by the likes of Notepad still is a mystery to me.
There’s a unit test in the above pull request that confirms that with
FileShare.ReadWriteyou can read the file while it is open.When using
var log = await File.ReadAllTextAsync("app.log");I get “The process cannot access the file ‘…’ because it is being used by another process”But this does work for me:
The problem here is that some logs are still not written to the file, so sometimes I end up with log that is not complete… I need to read log file when my console app is done with execution, so I did this:
Ugly but it works in my specific case. I think that library should provide a better way to handle this.
@VitaliyMF thanks for this library, I hope that you will continue to maintain it for a long time 😃