Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

519
Vistas
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?");
        }
    }
}
     
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda