简体   繁体   English

如何设置 DbContext 以将错误记录到 ILogger?

[英]How do I set up a DbContext to log errors to ILogger?

I have an ASP.NET Core application, and in my Startup.cs file, in the ConfigureServices(IServiceCollection services) function, I'm trying to write something like this:我有一个 ASP.NET 核心应用程序,在我的Startup.cs文件中,在ConfigureServices(IServiceCollection services) function 中,我正在尝试编写如下内容:

//...

namespace MyNamespace
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            //...

            services.AddDbContext<ModelDbContext>(options =>
            {
                options.UseSqlServer(_configuration.GetConnectionString("Model"),
                    sqlServerOptionsAction => sqlServerOptionsAction.EnableRetryOnFailure());
                options.LogTo(
                    filter: (eventId, _) => eventId.Id == CoreEventId.ExecutionStrategyRetrying,
                    logger: (eventData) =>
                    {
                        var retryEventData = (ExecutionStrategyEventData)eventData;
                        var exceptions = retryEventData.ExceptionsEncountered;
                        var exception = exceptions[exceptions.Count - 1];
                        logger.LogWarning(exception,
                            "Database error occurred. Retry #{ExceptionsCount} with delay {RetryEventDataDelay} due to error: {ExceptionMessage}",
                            exceptions.Count, retryEventData.Delay, exception.Message);
                    });
            }, ServiceLifetime.Transient);

            //...
        }

        //...
    }
}

However, I don't know how to make this line above work:但是,我不知道如何使上面的这一行起作用:

logger.LogWarning(exception,
    "Database error occurred. Retry #{ExceptionsCount} with delay {RetryEventDataDelay} due to error: {ExceptionMessage}",
    exceptions.Count, retryEventData.Delay, exception.Message);

The problem is that I don't have a reference to an instance of ILogger , so I don't know how to call the LogWarning function in that context.问题是我没有对ILogger实例的引用,所以我不知道如何在该上下文中调用LogWarning function。

So my question is:所以我的问题是:

  • What should I do to configure the DbContext with a reference to an ILogger instance?我应该怎么做才能使用对ILogger实例的引用来配置DbContext
    • Can I somehow use IServiceCollection services to construct an instance of ILogger ?我可以以某种方式使用IServiceCollection services来构造ILogger的实例吗? It feels a bit wrong to do that inside the ConfigureServices(IServiceCollection services) function.ConfigureServices(IServiceCollection services) function 中这样做感觉有点不对劲。 Or is there another better way?或者还有其他更好的方法吗?

You can use the other overload of AddDbContext, which provides the application's IServiceProvider which you can get logger from it, but somehow this overload is documented as less preferred.您可以使用 AddDbContext 的另一个重载,它提供应用程序的 IServiceProvider,您可以从中获取记录器,但不知何故,这种重载被记录为不太受欢迎。

The other way is just inject ILogger into your DbContext via the constructor, and configure your logging in DbContext.OnConfiguring to log into the injected logger.另一种方法是通过构造函数将 ILogger 注入到您的 DbContext 中,并在 DbContext.OnConfiguring 中配置您的日志记录以登录到注入的记录器。

"The problem is that I don't have a reference to an instance of ILogger " Let me start by this. “问题是我没有对ILogger实例的引用”让我从这个开始。 You can use ILogger<TCategoryName> Interface , used to enable activation of a named ILogger from dependency injection.您可以使用ILogger<TCategoryName> 接口,用于启用从依赖注入中激活命名的 ILogger。

This means that you can use dependency injection in any class, even StartUp.cs or DbContext to initiate an instance of ILogger .这意味着您可以在任何 class 甚至StartUp.csDbContext中使用依赖注入来启动ILogger的实例。

public class Startup
{
    private readonly ILogger<Startup> _logger;

    public IConfiguration Configuration { get; }

    public Startup(ILogger<Startup> logger, IConfiguration configuration)
    {
        _logger = logger;
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        _logger.LogInformation("ConfigureServices called");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM