10

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
Nazar Antonyk
  • 470
  • 4
  • 14
  • 2
    You might want to review how you are configuring the logger. The recommended approach is to configure it on `Program.cs` using `AddSerilog` extension from [here](https://github.com/serilog/serilog-aspnetcore/blob/dev/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs). – julealgon Mar 09 '20 at 00:42
  • From [documentation](https://github.com/serilog/serilog-extensions-logging-file#additional-configuration), AddFile() method seems not accept `shared` parameter. – Fei Han Mar 09 '20 at 08:45
  • Can you share your exact reading logic? Is this really your file path `"Logs/log-.txt"`? – julealgon Mar 12 '20 at 21:23
  • @julealgon Sure. Check out my updated question please. – Nazar Antonyk Mar 13 '20 at 14:43

2 Answers2

8

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.

julealgon
  • 7,072
  • 3
  • 32
  • 77
  • 2
    Yep! https://github.com/serilog/serilog-sinks-file - To enable multi-process shared log files, set shared to true: `.WriteTo.File("log.txt", shared: true)` – asawyer Mar 13 '20 at 14:45
  • does not seem to be working for me. using StreamReader elsewhere in .Net 6 application still gives "it is being used by another process" – PBMe_HikeIt Jul 06 '22 at 20:59
  • 1
    @PBMe_HikeIt can you post how you are creating the `StreamReader` instance? Are you explicitly passing the share option on the constructor? If not, can you give that a try? – julealgon Jul 07 '22 at 17:42
  • 1
    @julealgon, I was not passing that and doing that fixed the problem. thanks! – PBMe_HikeIt Jul 18 '22 at 13:20
7

When reading the file, I think use something like this will work:

using (var stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(stream))
{
    return reader.ReadToEnd();
}

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.

Mike Goatly
  • 7,380
  • 2
  • 32
  • 33
  • c# 6 does not have 'ReadAllBytes' – OverMars Oct 28 '22 at 22:19
  • 1
    @OverMars - yes, you're right, that was my bad when I wrote the answer, ReadAllBytes is an extension method I have in a common library. I've updated the answer with something that should be logically equivalent. – Mike Goatly Oct 30 '22 at 18:55