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

标签 c# asp.net-core logging serilog

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

Startup.cs

 public void Configure(IApplicationBuilder app, ILoggerFactory logFactory)
 {
     logFactory.AddFile("Log");
 }

任何以这种方式读取或写入文件的尝试
string ReadLog(string logPath)
{
    return System.IO.File.ReadAllText(logPath);
}

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

编辑 : 我已经安装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();

编辑 2 :
根据 的要求julealgon 我正在分享我的确切阅读逻辑。我正在尝试使用 Controller 阅读,我声明如下:
[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();
    }
}

然后使用下面的示例查询读取 2020 年 3 月 13 日星期五之前记录的日志。
https://localhost:44323/Log/Read?logPath=Logs\log-20200313.txt

最佳答案

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

using (var stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    return Encoding.UTF8.GetString(stream.ReadAllBytes());
}

诀窍似乎是 FileShare.ReadWrite 的规范因为这是在接收器打开要写入的日志文件时用于写入的策略。有一个 similar bug reportedserilog-sinks-file 结束 repo 。

关于c# - ASP.Net Core Serilog 如何在运行时读取日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60588284/

相关文章:

c# - 如何使用反射获取方法或类的文档?

c# - MonoTouch 中的图片库滑动 UI

c# - 如何在 MVC 中使用 html.textboxfor 表示数字

c# - 如何仅更新 Entity Framework (核心)中的特定字段

java - 如何配置 p6spy 将其输出重定向到文件中

c# - 组合的分组算法

iis - 用户配置文件和 HKLM 注册表都不可用。使用临时 key 存储库。应用程序退出时 protected 数据将不可用

javascript - .Net Core 2.2-事件目录: get user name on javascript

logging - 读取 WebSphere MQ Activity 日志文件

java - 有没有办法在不抛出异常的情况下转储堆栈跟踪?