Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Functions - ILogger Logging across classes

In an Azure function the run method creates an ILogger which in my main class I can use to log errors and information, however, I am using helper classes to run my Graph API and Cosmos DB queries.

What is the best way to log errors and information in the separate classes, should I be passing the log in all my classes or methods? or is there a better way to make the ILogger available to all classes at runtime?

public class AzureFunction
{
    public Task Run([TimerTrigger("0 0 1 * * *")] TimerInfo myTimer, ILogger log)
    {
        log.LogInformation("This message logs correctly");
        GraphHelper graphHelper = new GraphHelper();
        graphHelper.GetGraphData();
    }
}
 
public class GraphHelper
{
    public void GetGraphData()
    {
        try 
        {
            asyncTask() 
        }
        catch (Exception ex) 
        {
            log.LogInformation($"{ex.Message} - How can I log this without passing ILogger to every class or method?");
        }
    }
}
     
like image 416
CKelly-Cook Avatar asked Oct 20 '25 19:10

CKelly-Cook


1 Answers

The right way (IMHO) is through dependency injection.

using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace FunctionApp1
{
   public class HelperClass : IHelperClass
    {
        private static ILogger<IHelperClass> _logger;
        public HelperClass(ILogger<IHelperClass> logger)
        {

            _logger = logger;
        }
        public void Dowork()
        {
            _logger.LogInformation("Dowork: Execution Started");
            /* rest of the functionality below
                .....
                .....
            */
            _logger.LogInformation("Dowork: Execution Completed");
        }
    }
}

host.json

{
    "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingExcludedTypes": "Request",
      "samplingSettings": {
        "isEnabled": true
      }
    },
    "logLevel": {
      "FunctionApp1.HelperClass": "Information"
    }
  }
}

Helper class

using System;
using System.Collections.Generic;
using System.Text;

namespace FunctionApp1
{
    public interface IHelperClass
    {
        void Dowork();
    }
}

MainFunction

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace FunctionApp1
{
    public class MainFunction // Ensure class is not static (which comes by default)
    {
        private IHelperClass _helper;
     
        public MainFunction(IHelperClass helper)
        {
            _helper = helper;
        }

        [FunctionName("MainFunction")]
        public void Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
            // call helper 
            _helper.Dowork();
        }
    }
}

Startup.cs

using Microsoft.Azure.Functions.Extensions.DependencyInjection; // install nuget - "Microsoft.Azure.Functions.Extensions"
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

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

namespace FunctionApp1
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {           
            builder.Services.AddSingleton<IHelperClass,HelperClass>();            

        }
    }
}

A Full sample can be found on https://gist.github.com/nareshnagpal06/82c6b4df2a987087425c32adb58312c2

like image 91
Thiago Custodio Avatar answered Oct 22 '25 13:10

Thiago Custodio