Logging with ILogger in Azure Functions
  • 27 Sep 2022
  • 1 Minute to read
  • Contributors
  • Comment
  • Dark
    Light
  • PDF

Logging with ILogger in Azure Functions

  • Comment
  • Dark
    Light
  • PDF

#ServerlessTips - Azure Functions
Author: Steef-Jan Wiggers Azure MVP

An alternative to using TraceWriter in Azure Functions is leveraging the ILogger. With the ILogger you will have support for structured logging, which allows richer analytic support. Moreover, with Azure Functions V2.0 the TraceWriter will be obsolete.
With Azure Functions, you can use Application Insights and thus target your logs to it. By using ILogger, you can issue statements such as:

  • LogInformation
  • LogTrace
  • LogError
  • LogWarning
  • LogCritical

The log statement you can use within your function dependent on the requirements of your project or overall solution.

With the ILogger you can apply structured logging and thus better analyze your logs in the end.

A useful blog on good practices for structured logging is the blog post from Paco de la Cruz - Correlated Structured Logging on Azure Functions.

Azure-functions.png

You can inject the ILogger in the signature of your function operation – for instance:

public static void Run(EventGridEvent eventGridEvent, ICollector<string> outputSbMsg, ILogger log)

The ILogger becomes available within your code, and you can access the Log methods (LogInformation, and so on).

In case you want to use the ILogger in various other classes in your function you can do Dependency Injection using Azure Function Autofac.

You can follow the steps outlined in the blog Everything you need to know to write, debug, deploy and monitor Azure Functions – under the Dependency Injection paragraph to accomplish this.

Lastly, logging is essential for your function to observe the behaviour and useful when you need to troubleshoot them using for instance Application Insights.


Was this article helpful?