c# api请求日志先保存到内存 在定时批量插入数据库

可以使用一个 List 来保存请求日志,然后使用定时器来定期将 List 中的日志批量插入到数据库中。下面是一个简单的示例代码:.

public class RequestLogMiddleware
{
    private readonly RequestDelegate _next;
    private readonly List<RequestLog> _logList;
    private readonly Timer _timer;

    public RequestLogMiddleware(RequestDelegate next)
    {
        _next = next;
        _logList = new List<RequestLog>();
        _timer = new Timer(60000); // 每 60 秒执行一次
        _timer.Elapsed += OnTimerElapsed;
        _timer.Start();
    }

    public async Task Invoke(HttpContext context)
    {
        var requestLog = new RequestLog
        {
            Method = context.Request.Method,
            Path = context.Request.Path,
            QueryString = context.Request.QueryString.ToString(),
            Timestamp = DateTime.Now
        };
        _logList.Add(requestLog);
        await _next(context);
    }

    private void OnTimerElapsed(object sender, ElapsedEventArgs e)
    {
        if (_logList.Count > 0)
        {
            // 批量插入到数据库中
            using (var dbContext = new MyDbContext())
            {
                dbContext.RequestLogs.AddRange(_logList);
                dbContext.SaveChanges();
            }
            // 清空 List
            _logList.Clear();
        }
    }
}

public class RequestLog
{
    public int Id { get; set; }
    public string Method { get; set; }
    public string Path { get; set; }
    public string QueryString { get; set; }
    public DateTime Timestamp { get; set; }
}

public class MyDbContext : DbContext
{
    public DbSet<RequestLog> RequestLogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
    }
}

在上面的代码中,我们创建了一个 RequestLogMiddleware 中间件,它会在每个请求到达时将请求信息保存到一个 List 中。同时,我们使用一个 Timer 定时器来定期将 List 中的请求日志批量插入到数据库中。请注意,这里的定时器是在构造函数中创建并启动的,它会每 60 秒执行一次。您可以根据自己的需求来调整定时器的间隔时间。同时,我们还定义了一个 RequestLog 实体类和一个 MyDbContext 数据库上下文类,用于保存请求日志到数据库中。

下面是详细的调用步骤:

  1. 首先,将 RequestLogMiddleware.cs 文件添加到您的 ASP.NET Core 项目中的 Middleware 文件夹中。

  2. 在 Startup.cs 文件中,找到 Configure 方法,并在其中添加以下代码:

app.UseMiddleware<RequestLogMiddleware>();

这将告诉 ASP.NET Core 使用 RequestLogMiddleware 中间件来处理每个请求。

  1. 如果您想自定义日志输出的格式和位置,可以在 RequestLogMiddleware.cs 文件中修改 LogMessage 方法。例如,如果您想将日志输出到控制台而不是文件中,可以使用以下代码:
Console.WriteLine($"{DateTime.Now}: {context.Request.Path} - {elapsedTime}ms");
  1. 保存文件并运行您的应用程序。现在,每个请求都将被记录,并输出到您指定的位置。