ASP.Net Core Serilog 如何在运行时读取日志文件

Naz*_*nyk 6 c# logging serilog asp.net-core

我正在开发 ASP.NET Core 3.1 应用程序。我想将事件记录到文件中并能够在应用程序运行时读取它们。为此,我尝试使用Serilog.Extensions.Logging.File NuGet 包,然后指定日志文件路径如下:

启动文件

 public void Configure(IApplicationBuilder app, ILoggerFactory logFactory)
 {
     logFactory.AddFile("Log");
 }
Run Code Online (Sandbox Code Playgroud)

任何以这种方式读取或写入文件的尝试

string ReadLog(string logPath)
{
    return System.IO.File.ReadAllText(logPath);
}
Run Code Online (Sandbox Code Playgroud)

System.IO.IOException: 'The process cannot access the file {log-path} because it is being used by another process.'异常结束。


编辑:我已经安装了Serilog.AspNetCore并进行了如下所示的更改,同时还从配置功能中删除了 logFactory。但异常继续发生。


程序.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();
Run Code Online (Sandbox Code Playgroud)

编辑 2:根据julealgon 的要求,我正在分享我的确切读取逻辑。我正在尝试使用控制器阅读,我声明如下:

[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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用下面的示例查询读取 2020 年 3 月 13 日星期五之前记录的日志。

https://localhost:44323/Log/Read?logPath=Logs\log-20200313.txt
Run Code Online (Sandbox Code Playgroud)

jul*_*gon 9

配置File接收器时,有一个提供shared布尔参数的重载。如果您将其设置为truefalse默认情况下),您应该能够在应用程序的其他位置读取文件的内容。

  • 是的!https://github.com/serilog/serilog-sinks-file - 要启用多进程共享日志文件,请将共享设置为 true: `.WriteTo.File("log.txt", shared: true)` (2认同)

Mik*_*tly 8

阅读文件时,我认为使用这样的东西会起作用:

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

技巧似乎是规范,FileShare.ReadWrite因为这是接收器打开要写入的日志文件时用于写入的策略。存储库中报告了类似的错误serilog-sinks-file