首页 > 解决方案 > 使用 Azure Function V3,如何将现有的 Ilogger 注入到新的类文件中?

问题描述

我使用 VS2019 创建了一个新的 Azure Function,V3,CORE 3.1。它使用一个基本的 HTTPTrigger。我创建了一个新的类文件,并希望将现有的 Ilogger 注入其中。如何做到这一点?我是新手,所以任何帮助将不胜感激。

标签: c#visual-studioazure-functionsilogger

解决方案


我有一个将日志写入 App Insights 的函数,我使用 ILogger。

您可以在其他服务/帮助程序类中将 ILogger 与依赖注入一起使用。

public interface IExampleClass
{
    void ExampleMethod();
}

public class ExampleClass : IExampleClass
{
    private readonly ILogger<ExampleClass> _logger;

    public ExampleClass(ILogger<ExampleClass> logger)
    {
        _logger = logger;
    }

    public void ExampleMethod()
    {
       _logger.LogInformation("Example info log");
    }
}

我在启动文件中启用日志记录并注册 DI。

class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddLogging();
        builder.Services.AddTransient<ExampleClass, IExampleClass>();
    }
}

可以由主类调用。

public class ThisIsAnAzureFunction
{
    private readonly IExampleClass _exampleClass;

    public ThisIsAnAzureFunction(IExampleClass exampleClass)
    {
        _exampleClass = exampleClass;
    }

    [FunctionName("SomeAzureFunctionName")]
    public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)
    {
        try
        {
            //Try some stuff
        }
        catch (Exception exception)
        {
            //Log some stuff
            log.LogError(exception);
            throw;
        }
    }
}

推荐阅读