'How to view Serilog log file while it is used by another process?
I am logging my data by Serilog and I am not able to view the log files of the current day because they are used by another process.
I created logger in my program.cs and it is logging data very well
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.WriteTo.File(new JsonFormatter(), "Logs/Log.txt",
shared:true, rollingInterval: RollingInterval.Day)
.CreateLogger();
I want to be able to view the logs of the current day
Solution 1:[1]
This is answer for getting contents of log file from code, not via FTP, but maybe it can be useful for someone struggling with getting contents from code (like I was).
My original solution for reading the log file was
var path = "...";
var fileBytes = await System.IO.File.ReadAllBytesAsync(path);
return File(fileBytes, "text/plain", fileName);
With this code I was still getting an error that the file is being used by another process. Then I looked into the method ReadAllBytesAsync and there I found this line
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,...)
and I found the parameters FileShare interesting. So I looked, what other possibilities I can put there and I found FileShare.ReadWrite, so I tried it and it worked. Like this
var path = "...";
byte[] result;
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
result = new byte[stream.Length];
await stream.ReadAsync(result, 0, (int)stream.Length);
}
return File(result, "text/plain", fileName);
When I tried the same (the last code snippet) with FileShare.Read, the error was showing again.
So Serilog has the log file opened for (reading?) and writing and when I want to open the file for reading I have to still allow other processes to write to it and therefore I have to use FileShare.ReadWrite.
Finally I searched if my assumptions were correct and I found this nice explanation for the FileShare parameter - https://stackoverflow.com/a/25098500/6277745
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ján PaholÃk |
