依赖项注入ILoggerFactory,中间件中的ILogger,记录器未执行

问题描述

试图构建一个中间件,该中间件将记录每个请求的信息。 ASP.NET Core 3.1 学习一些基础知识

我正试图了解一些奇怪的行为。这是我的中间件构造函数

public ContextRequestLoggingMiddleware( RequestDelegate next,ILoggerFactory loggerFactory ) {
    this._next = next;
    _logger = loggerFactory.CreateLogger( "ContextRequestLoggingMiddleware" );            
}

使用它可以按预期工作。消息记录在每个请求上:

public async Task InvokeAsync (HttpContext context ) {
    _logger.Log@R_776_4045@ion( "test from middleware" );
    await _next( context );    
}

当我使用以下代码时:

_logger = loggerFactory.CreateLogger<ContextRequestLoggingMiddleware>();

执行超过_logger.Log@R_776_4045@ion,但似乎未执行,没有记录任何内容,没有错误,没有问题,只是跳转到下一行代码。使用WatchList查看_logger时,我发现这两种方法之间没有任何区别。

相同的行为,其中什么也没有记录,并且如果使用ILogger<T>也不会遇到错误

public ContextRequestLoggingMiddleware( RequestDelegate next,ILogger<ContextRequestLoggingMiddleware> logger ) {
    this._next = next;
    _logger = logger;
}

我无法注入普通ILogger,因为它会引发运行时错误

尝试激活“ Microsoft.AspNetCore.Builder.ContextRequestLoggingMiddleware”时,无法解析类型为“ Microsoft.Extensions.Logging.ILogger”的服务。

再次检查对象,我看不到我使用的不同方法间的差异。 那为什么呢?我会认为ILogger<T>是最佳选择,但是为什么它在这里不起作用?它确实适用于Controller。谢谢您的解释。

对于上下文,我的CreateHostBuilder

public static IHostBuilder CreateHostBuilder( string[] args ) =>
    Host.CreateDefaultBuilder( args )
        .ConfigureLogging( ( hostContext,loggingBuilder ) => {
            loggingBuilder.ClearProviders();
            loggingBuilder.AddConfiguration( hostContext.Configuration.GetSection( "Logging" ) );
            loggingBuilder.AddCustomFileLogger();
        }
        ).ConfigureWebHostDefaults( webBuilder => {
            webBuilder.UseStartup<Startup>();
        } );

还有我的Startup类的一部分:

public void ConfigureServices( IServiceCollection services ) {
    services.AddControllers();
    services.AddDbContext<NPAContext>( options =>
         options.UsesqlServer( Configuration.GetConnectionString( cnnDB ) ) );
    services.AddAuthentication( options => {
        options.DefaultAuthenticateScheme = ApiKeyAuthenticationoptions.DefaultScheme;
        options.DefaultChallengeScheme = ApiKeyAuthenticationoptions.DefaultScheme;
    } )
        .AddApiKeySupport( options => { } );
    
    services.AddSingleton<List<JobEventDTO>>();            
}

public void Configure( IApplicationBuilder app,IWebHostEnvironment env,ILoggerFactory loggerFactory ) {
    if ( env.IsDevelopment() ) {
        app.UseDeveloperExceptionPage();
    }
    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseContextRequestLoggingMiddleware();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints( endpoints => {
        endpoints.MapControllers();
    } );
}

修改 解析度: 我犯了一个错误,在构建类ContextRequestLoggingMiddleware时,我将其放在NameSpace Microsoft.AspNetCore.Builder下。这样,使记录器在MiddleWare中工作的唯一方法是传递ILoggerFactory并创建记录器,但它只能以一种方式工作

_logger = loggerFactory.CreateLogger( "ContextRequestLoggingMiddleware" )

一旦我将类放在不同的NameSpace下,其他方法也开始起作用

_logger = loggerFactory.CreateLogger<ContextRequestLoggingMiddleware>()

现在也可以通过ILogger<ContextRequestLoggingMiddleware>

因此,下面的建筑课程现在对我有用。 有趣的是,更改名称空间如何使其起作用。

namespace NPARetrieval.Middleware {
public class ContextRequestLoggingMiddleware {
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public ContextRequestLoggingMiddleware( RequestDelegate next,ILogger<ContextRequestLoggingMiddleware> logger ) {
        this._next = next;
        _logger = logger;
    }


    public async Task InvokeAsync (HttpContext context ) {
        _logger.Log@R_776_4045@ion( "test from middleware" );
        await _next( context );    
    }
}

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)