How can I use the new DI to inject an ILogger into an Azure Function using IWebJobsStartup?

UPDATE

Reference Use dependency injection in .NET Azure Functions

Registering services

To register services, you can create a configure method and add components to an IFunctionsHostBuilder instance. The Azure Functions host creates an IFunctionsHostBuilder and passes it directly into your configured method.

To register your configure method, you must add an assembly attribute that specifies the type for your configure method using the FunctionsStartup attribute.

So in this case

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]    
namespace MyNamespace {
    public class Startup : FunctionsStartup {
        public override void Configure(IFunctionsHostBuilder builder) {
            //  ** Registers the ILogger instance **
            builder.Services.AddLogging();

            //  Registers the application settings' class.
            //...

            //...omitted for brevity    
        }
    }
}

ORIGINAL

I believe since you have access to the service collection, you should be able to add logging to it

public void Configure(IWebJobsBuilder webJobsBuilder) {       

    //  ** Registers the ILogger instance **
    webJobsBuilder.Services.AddLogging();

    //OR
    //webJobsBuilder.Services.AddLogging(builder => {
    //    //...
    //});

    //  Registers the application settings' class.
    //...

    //...removed for brevity
}

and having anILoggerFactory in the Function's constructor.

//...

//Ctor
public FindAccountFunction(ILoggerFactory loggerFactory, IMapper mapper, IAccountWorkflow accountWorkflow) {
    m_logger = loggerFactory.CreateLogger<FindAccountFunction>();
    m_mapper = mapper;
    m_accountWorkflow = accountWorkflow;
}

//...

You should remove the call of AddLogging method from your startup class. The default logger is already setup by the azure function host.

[assembly: WebJobsStartup(typeof(StartUp))]
public class StartUp : IWebJobsStartup
{
    public void Configure(IWebJobsBuilder builder)
    {
        builder.Services.AddSingleton<AppSettings>();

        builder.Services.AddTransient<IMyService, MyService>();
    }
}

public MyFunction(IMyService service, ILogger<IMyService> logger)
{
    this.service = service;
    this.logger = logger;
}

Instance methods are now supported with azure function since Azure Functions Runtime 2.0.12265

enter image description here


I managed to resolve this problem:

Injecting into my class as below:

MyClass.cs:

public class MyClass
{
    private readonly ILogger<MyClass> _logger;

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

Startup.cs:

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

namespace Namespace {    
public class Startup : FunctionsStartup 
{
    public override void Configure(IFunctionsHostBuilder builder) 
    {
        builder.Services.AddLogging(); 
    }
  }
}