简体   繁体   English

ILogger 通过构造函数注入 Azure Function 2.x 的 Http 触发器函数

[英]ILogger injected via constructor for Http trigger functions with Azure Function 2.x

ILogger can be injected to function parameter, like Token method below. ILogger可以注入到函数参数中,如下面的Token方法。

However, the error below occurred when it is injected to constructor parameter log .但是,将其注入到构造函数参数log时发生了以下错误。

[07/03/2019 17:15:17] Executed 'Token' (Failed, Id=4e22b21f-97f0-4ab4-8f51-8651b 09aedc8) [07/03/2019 17:15:17] Microsoft.Extensions.DependencyInjection.Abstractions: Una ble to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'Functions'. [07/03/2019 17:15:17] 执行“令牌”(失败,Id=4e22b21f-97f0-4ab4-8f51-8651b 09aedc8)[07/03/2019 17:15:17] Microsoft.ExtensionsInject.D抽象:尝试激活“功能”时无法解析“Microsoft.Extensions.Logging.ILogger”类型的服务。

ILogger can be injected to Token function parameter below.可以将ILogger注入到下面的Token函数参数中。 But the error above occurred when it is injected to constructor parameter log .但是在注入构造函数参数log时发生了上述错误。

public class Functions
{
    private HttpClient _httpClient;
    private IAppSettings _appSettings;
    private ILogger _log;

    public Functions(HttpClient httpClient, IAppSettings appSettings  //working for these two
      , ILogger log  //not working, errors
    )
    {

        _log = log;
    }

    [FunctionName("Token")]
    public async Task<IActionResult> Token(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "Token")]
        HttpRequest httpRequest,
        ILogger log)
    {

    }
}

Dependence injection below下面的依赖注入

[assembly: WebJobsStartup(typeof(Startup))]
namespace MyApp
{
    public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.Services.AddHttpClient();
            builder.Services.AddTransient<IAppSettings, AppSettings>();     
             //builder.Services.AddLogging();  //not working
           //builder.Services.AddSingleton<ILogger>() //not working
        }
}

Visual studio 2017视觉工作室 2017

I had this problem as well.我也有这个问题。 I was able to fix it by calling AddLogging() :我能够通过调用AddLogging()来修复它:

[assembly: WebJobsStartup(typeof(Startup))]
namespace MyApp
{
    public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.Services.AddHttpClient();
            builder.Services.AddTransient<IAppSettings, AppSettings>();     
            builder.Services.AddLogging();
        }
}

And then, in the Azure Function, I had to do pass a ILoggerFactory instead of an ILogger and get the ILogger instance from the loggerFactory :然后,在 Azure 函数中,我必须通过ILoggerFactory而不是ILogger并从loggerFactory获取ILogger实例:

public class Functions
{
    private HttpClient _httpClient;
    private IAppSettings _appSettings;
    private ILogger _log;

    public Functions(HttpClient httpClient, IAppSettings appSettings, ILoggerFactory loggerFactory)
    {
        _log = loggerFactory.CreateLogger<Functions>();
    }

    [FunctionName("Token")]
    public async Task<IActionResult> Token(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "Token")]
        HttpRequest httpRequest)
    {
           // No need to keep getting the ILogger from the Run method anymore :)
    }
}

Calling LogCategories.CreateFunctionUserCategory fixed my problem.调用LogCategories.CreateFunctionUserCategory解决了我的问题。 Complete example:完整示例:

Azure Functions Core Tools (2.7.1158 Commit hash: f2d2a2816e038165826c7409c6d10c0527e8955b)
Function Runtime Version: 2.0.12438.0

Startup.cs启动文件

No need to add builder.Services.AddLogging();无需添加builder.Services.AddLogging(); it's imported automatically in the container.它会自动导入到容器中。

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(MyFunctionsNamespace.Startup))]

namespace MyFunctionsNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddTransient<IMyService, MyService>();
        }
    }
}

MyFunkyFunction.cs MyFunkyFunction.cs

using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;

namespace MyFunctionsNamespace
{
    public class MyFunkyFunction
    {
        private readonly IMyService _myService;

        public MyFunkyFunction(IMyService myService)
        {
            _myService = myService;
        }

        [FunctionName("FunkyFunc")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            HttpRequest req
            , ILogger log
        )
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            _myService.Do();

            return new OkObjectResult("Hello");
        }
    }
}

IMyService.cs IMyService.cs

Anything in LogCategories.CreateFunctionUserCategory will do the job. LogCategories.CreateFunctionUserCategory任何内容LogCategories.CreateFunctionUserCategory可以完成这项工作。 It seems to be some WebJob legacy requirement.这似乎是一些 WebJob 遗留要求。

using Microsoft.Azure.WebJobs.Logging;
using Microsoft.Extensions.Logging;

namespace MyFunctionsNamespace
{
    public interface IMyService
    {
        void Do();
    }


    public class MyService : IMyService
    {
        private readonly ILogger _log;

        public MyService(ILoggerFactory loggerFactory)
        {
            // Important: Call CreateFunctionUserCategory, otherwise log entries might be filtered out
            // I guess it comes from Microsoft.Azure.WebJobs.Logging
            _log = loggerFactory.CreateLogger(LogCategories.CreateFunctionUserCategory("Common"));
        }

        public void Do()
        {
            _log.Log(LogLevel.Information, "Hello from MyService");
        }
    }
}

I had this same problem.我有同样的问题。 I finally found that adding this "logging" element to my host.json file solved it for me.我终于发现将这个“日志”元素添加到我的 host.json 文件中为我解决了这个问题。

{
    "version": "2.0",
    "logging": {
        "logLevel": {
            "default": "Trace"
        }
    }
}

Now the standard .NET core constructor-injected logger method works fine.现在标准的 .NET 核心构造函数注入记录器方法工作正常。

暂无
暂无

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

相关问题 Azure function 2.x ILogger 与.net core ILogger 不兼容? - Azure function 2.x ILogger is not competible with .net core ILogger? Azure应用功能(功能2.x):通过HTTP功能在CosmosDB中创建新文档 - Azure App Function (Functions 2.x): Create new document in CosmosDB via HTTP function 使用新的 DI 功能时未注入 ILogger - Azure 功能 - ILogger is not injected when using new DI functionality - Azure Functions 使用 Azure Functions 应用程序 2.x 设置 Azure Functions 应用程序的基目录 - Setting Azure Functions app's base directory wtih Azure Function app 2.x ILogger 未注入 Durable Functions v2.0 - ILogger not Injected in Durable Functions v2.0 通过 DI 注入到 ServiceBusTrigger Azure function 的 IHttpClientFactory 是否为每个触发器重用或重新创建? - Is an IHttpClientFactory that is injected via DI into a ServiceBusTrigger Azure function reused or recreated for each trigger? 为什么在我的 Azure Function v2 中注入的 ILogger 缺少 APPINSIGHTS_INSTRUMENTATIONKEY? - Why is the ILogger injected in my Azure Function v2 missing the APPINSIGHTS_INSTRUMENTATIONKEY? 如何通过 Postman POST 到 Azure 函数(HTTP 触发器)? - How to POST to an Azure Function (HTTP Trigger) via Postman? 通过 azure function HTTP 触发器取回 MySqlDataAdapter 数据 - Getting back MySqlDataAdapter data via azure function HTTP trigger 使用 Azure 函数的 ILogger 依赖注入 - ILogger Dependency Injection with Azure Functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM