Startup中如何注册ILogger

How to register ILogger in Startup

我在 json 设置中有一个日志记录部分:

{
    "logging": {
        "applicationInsights": {
            "samplingSettings": {
                "isEnabled": true,
                "excludedTypes": "Request"
            }
        }
    }
}

我需要在 Startup 中注册它以便能够在处理程序中使用。

到目前为止,我已经尝试了多种选择,但 none 其中有效:

选项 1

    builder.Services.AddApplicationInsightsTelemetry(); // returns error: IServicesCollection does not contain a definition for AddApplicationInsightsTelemetry 

选项 1 更新

我将 Microsoft.ApplicationInsights.AspNetCore 添加到项目中,因此 AddApplicationInsightsTelemetry 现在可用,但 ILogger 仍然提供 null

选项 2

    builder.Services.AddLogging(logging =>
    {
        logging.AddConfiguration(hostingContext.GetSection("logging"));
    }); // ILogger is null in handler

但找不到关于我的具体案例的任何信息

如何在 Startup 中注册 ILogger 以继续使用我的应用 json 中的设置?

这是我正在使用的处理程序:

public class ExampleHandler : IRequestHandler<ExampleQuery, bool>
{
    private readonly ILogger _log;

    public ExampleHandler(ILogger log)
    {
        _log = log;
    }

    public async Task<bool> Handle(ExampleQuery request, CancellationToken cancellationToken)
    {
        // _log is null here;

        return true;
    }
}
  1. 安装Microsoft.ApplicationInsights.AspNetCore nuget 包

  2. 解析类型记录器:

public class ExampleHandler : IRequestHandler<ExampleQuery, bool>
{
    private readonly ILogger<ExampleHandler> _log;

    public ExampleHandler(ILogger<ExampleHandler> log)
    {
        _log = log;
    }
    ...
}