Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use ILogger<T> from an Azure Functions V2 function?

I have some services that were initially designed to be called from my ASP.NET Core 2.1 web application. They have dependencies injected to their constructors using Microsoft.Extensions.DependencyInjection package stuff. Some of them have a dependency of ILogger logger.

public GroupService(ILogger<GroupService> logger)
{
    ...
}

I am building a service provider within the function so that they can still work as expected however I'm wondering what I should do about the logger dependencies. An Azure Function (V2) gets an ILogger injected into it by default but that can't be used in the DI container to create the additional loggers that the services require.

Is there a LoggerFactory registered somewhere "under the covers" that I can get access to to be used in my DI container? I think that would allow me to add additional loggers that log to the functions output window or am I completely misunderstanding how logging in a function would work?

Do I just need to set up a new LoggerFactory and make that log to the ApplicationInsights instance used by the functions project?

like image 236
Adam Stapleton Avatar asked Dec 20 '18 15:12

Adam Stapleton


People also ask

Where are azure function logs stored?

In the path of Storage Account > File Shares (under Data Storage) > Your Function App > LogFiles > Application > Functions > Function > Your Function Name > You can see the console result (Application Logs - Execution results/failed result/error data) of the function.

What is host JSON in Azure function?

The host. json metadata file contains configuration options that affect all functions in a function app instance. This article lists the settings that are available starting with version 2. x of the Azure Functions runtime.


1 Answers

Using the most recent Azure Function runtime, you can now have the runtime inject your dependencies through constructors.

You can now remove the static keywords from your Azure Function and have the runtime.

Here is how you can set this up:

[assembly: WebJobsStartup(typeof(StartUp))]

public class StartUp : IWebJobsStartup
{
    public void Configure(IWebJobsBuilder webJobsBuilder)
    {
        // Enables logging and sets the minimum level of logs.
        webJobsBuilder.Services.AddLogging(loggingBuilder =>
        {
            loggingBuilder.SetMinimumLevel(LogLevel.Debug);
        });

        // Registers your services.
        webJobsBuilder.Services.AddTransient<IGroupService, GroupService>();
    }        
}
like image 185
Kzrystof Avatar answered Oct 12 '22 08:10

Kzrystof