Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core Serilog How to read from log file during runtime

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
like image 627
Nazar Antonyk Avatar asked Mar 08 '20 14:03

Nazar Antonyk


2 Answers

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.

like image 87
Mike Goatly Avatar answered Sep 20 '22 12:09

Mike Goatly


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.

like image 40
julealgon Avatar answered Sep 21 '22 12:09

julealgon