Using Azure Function V3, how do I inject existing Ilogger into new class file?

2.8k Views Asked by At

I have created a new Azure Function, V3, CORE 3.1, using VS2019. It uses a basic HTTPTrigger. I have created a new class file and would like to inject the existing Ilogger into it. How can this be achieved? I'm new to this so any help would be appreciated.

1

There are 1 best solutions below

8
On

I have a Function which writes logs to App Insights and I use ILogger.

You can use ILogger like this with Dependency Injection in your other service/helper classes.

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");
    }
}

I enable logging in the Startup file and register DI.

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

Which can be invoked by the main class.

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;
        }
    }
}