2

I have a simple function app that uses MediatR pattern and the base function looks like this:

public class ShareEnvelopesFunction
{
    private readonly IMediator _mediator;

    public ShareEnvelopesFunction(IMediator mediator)
    {
        _mediator = mediator;
    }

    [FunctionName(nameof(ShareEnvelopesFunction))]
    public async Task Run([TimerTrigger("%ScheduleShareEnvelopesSetting%")]TimerInfo timer, ILogger log)
    {
        log.LogInformation("Starting Share Envelopes function {0}", timer);
        var result = await _mediator.Send(new ShareEnvelopesCommandRequest { log = log });
    }
}

As you can see ShareEnvelopesCommandRequest is a class that has only one property which is the ILogger

public class ShareEnvelopesCommandRequest : IRequest<ShareEnvelopesCommandResponse>
{
    public ILogger log { get; set; }
}

Now in my command handler, if I use request.log.LogInformation, it logs messages to my console. A sample command handler code looks like this:

public class ShareEnvelopesCommandHandler : IRequestHandler<ShareEnvelopesCommandRequest, ShareEnvelopesCommandResponse>
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IDocuSignApiService _docuSignService;

    public ShareEnvelopesCommandHandler(IUnitOfWork unitOfWork
        , IDocuSignApiService docuSignService
        )
    {
        _unitOfWork = unitOfWork;
        _docuSignService = docuSignService;
    }

    public async Task<ShareEnvelopesCommandResponse> Handle(ShareEnvelopesCommandRequest request, CancellationToken cancellationToken)
    {
        request.log.LogInformation("Starting to share envelopes");
        await _docuSignService.ShareEnvelopes(fromGroupUser.UserId, deltaUsers);

        return new ShareEnvelopesCommandResponse() {isSuccess=true };
    } 

Now the real issue here is that, if you see the above code, I am injecting a docusign service and inside this service, I need to log certain information into the console. My sample docusign service looks like this:

public class DocuSignApiService : IDocuSignApiService
{
    public IGroupsApi _groupsApi { get; set; }
    public IAccountsApi _accountsApi { get; set; }

    public DocuSignApiService(IGroupsApi groupsApi, IAccountsApi accountsApi)
    {
        _groupsApi = groupsApi;
        _accountsApi = accountsApi;
    }

    public async Task ShareEnvelopes(string fromUserId, List<string> toUsersList)
    {
        //_logger.LogInformation("This is a test");

    }
}

Now I need to be able to log any information from this service to the console. Now I can pass the ShareEnvelopesCommandRequest request to this service but I don't think that would be very efficient. So here is what I have tried:

I injected ILogger into the service:

public class DocuSignApiService : IDocuSignApiService
{
    public IGroupsApi _groupsApi { get; set; }
    public IAccountsApi _accountsApi { get; set; }
    private readonly ILogger _logger;


    public DocuSignApiService(IGroupsApi groupsApi, IAccountsApi accountsApi, ILogger<ShareEnvelopesCommandRequest> logger )
    {
        _groupsApi = groupsApi;
        _accountsApi = accountsApi;
        _logger = logger;
    }

    public async Task ShareEnvelopes(string fromUserId, List<string> toUsersList)
    {
        _logger.LogInformation("This is a test");

    }
}

The configuration on DI in my startup class looked like this:

services.AddScoped<IDocuSignApiService>(_ => new DocuSignApiService(docuSignConfig, 
                                                                                _.GetService<IGroupsApi>(),
                                                                                _.GetService<IAccountsApi>(),
                                                                                _.GetService<ILogger<ShareEnvelopesCommandRequest>>()
                                                                                )
                                                    );

However, doing that didn't log information into the azure function app console. Are there an ideas on how I can go about logging messages from a service into the console? Thanks in advance.

2
  • I guess you also need to setup logging itself: learn.microsoft.com/en-us/azure/azure-functions/…
    – Fildor
    Nov 10, 2022 at 7:08
  • Did you add a Console log provider in your Startup.cs ? There should be a call to AddConsole in the log configuration .AddScoped<IDocuSignApiService>(...) should be replaced by just .AddScoped<IDocuSignApiService,DocuSignApiService>() because it tries to do what DI is meant to do - find the correct dependencies and inject them. Dec 6, 2022 at 16:26

2 Answers 2

0

Maybe you have to setup log level in host.json like this:

{
    "version": "2.0",
    "logging": {
        "applicationInsights": {
            "samplingSettings": {
                "isEnabled": true,
                "excludedTypes": "Request"
            }
        },
        "logLevel": {
            "YourNamespace.DocuSignApiService": "Information",
            "YourNamespace.ShareEnvelopesFunction": "Information",
        }
    }
}
1
  • i tried this and it didn't work
    – Fast Chip
    Nov 11, 2022 at 6:55
0

I'm guessing you get the ILogger instance in your Run method directly from azure, whenever you run the function.

_.GetService<ILogger<ShareEnvelopesCommandRequest>>()

That above probably gets another instance unrelated to the one azure provides you and maybe that's why no logs happen. If you're going to use DI, you gotta do it from the start of the Run method of your function class (ShareEnvelopesFunction).

public class ShareEnvelopesFunction
{
    private readonly IMediator _mediator;
    private readonly ServiceCollection _serviceCollection;

    public ShareEnvelopesFunction(IMediator mediator, ServiceCollection serviceCollection)
    {
        _serviceCollection = serviceCollection;//inject this from your startup
        _mediator = mediator;
    }

    [FunctionName(nameof(ShareEnvelopesFunction))]
    public async Task Run([TimerTrigger("%ScheduleShareEnvelopesSetting%")] TimerInfo timer, ILogger log)
    {
        _serviceCollection.AddSingleton(log);//this should ensure that all log instances injected into your services are references to the one azure provided, or something like that
        _serviceCollection.AddScoped<IDocuSignApiService,DocuSignApiService>();//now that your servicecollection knows what ILogger to inject, you can also inject your service normally, not sure if this needs to be done here tho, leaving it in your startup should be fine

        log.LogInformation("Starting Share Envelopes function {0}", timer);
        var result = await _mediator.Send(new ShareEnvelopesCommandRequest { log = log });
    }
}

I've done this in a recent AWS Lambda project, their ILambdaContext also serve as logger. I was having the same issue as you, no logs in DI dependent services.

If that doesn't do the trick, try rebuilding your ServiceProvider before Mediator does it's thing.

    using (IServiceProvider serviceProvider = _serviceCollection.BuildServiceProvider())
    {
        log.LogInformation("Starting Share Envelopes function {0}", timer);
        _mediator = serviceProvider.GetService<IMediator>();
        var result = await _mediator.Send(new ShareEnvelopesCommandRequest { log = log });
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.