Skip to content

Instantly share code, notes, and snippets.

@nareshnagpal06
Created September 17, 2020 15:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nareshnagpal06/82c6b4df2a987087425c32adb58312c2 to your computer and use it in GitHub Desktop.
Save nareshnagpal06/82c6b4df2a987087425c32adb58312c2 to your computer and use it in GitHub Desktop.
Azure Functions ILogger Dependency Injection in other classes
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");
}
}
}
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingExcludedTypes": "Request",
"samplingSettings": {
"isEnabled": true
}
},
"logLevel": {
"FunctionApp1.HelperClass": "Information"
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace FunctionApp1
{
public interface IHelperClass
{
void Dowork();
}
}
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();
}
}
}
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>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment