I'm working on a ASP.NET Core 3.1 application. I want to log events to file and be able to read them during application runtime. To do that I'm trying to use Serilog.Extensions.Logging.File NuGet package and then specifying log file path as following:
Startup.cs
public void Configure(IApplicationBuilder app, ILoggerFactory logFactory)
{
logFactory.AddFile("Log");
}
Any attempt to read or write to file like this way
string ReadLog(string logPath)
{
return System.IO.File.ReadAllText(logPath);
}
ends in System.IO.IOException: 'The process cannot access the file {log-path} because it is being used by another process.'
exception.
EDIT: I have installed Serilog.AspNetCore and made changes shown below while also removing logFactory from Configure function. But exception continues to occur.
Program.cs
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File(
"Logs/log-.txt",
shared: true,
flushToDiskInterval: TimeSpan.FromSeconds(5),
rollingInterval: RollingInterval.Day)
.CreateLogger();
try
{
Log.Information("Starting web host");
CreateHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseSerilog();
EDIT 2: As requested by julealgon I'm sharing my exact read logic. I'm trying to read using a controller, which I declared following way:
[Controller]
[Route("[controller]")]
public class LogController : Controller
{
[Route("Read")]
public IActionResult ReadLog(string logPath)
{
if (System.IO.File.Exists(logPath))
{
string logContent = System.IO.File.ReadAllText(logPath);//exception appears here.
return Content(logContent);
}
else return NotFound();
}
}
Then using example query below to read log recorded by Friday, March 13, 2020.
https://localhost:44323/Log/Read?logPath=Logs\log-20200313.txt
When reading the file, I think use something like this will work:
using (var stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
return Encoding.UTF8.GetString(stream.ReadAllBytes());
}
The trick appears to be the specification of FileShare.ReadWrite
as this is the policy used to write to when the sink opens the log file to write to. There's a similar bug reported over in the serilog-sinks-file
repo.
When configuring the File
sink, there is an overload that provides a shared
Boolean argument. If you set that to true
(it's false
by default) you should then be able to read the contents of the file somewhere else in your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With