Integrating Serilog with Azure Functions and Application Insights

...
  • By Ivan Gavryliuk
  • In Kubernetes
  • Posted 14/02/2019

Serilog traditionally doesn't have support for Azure Functions, however there is an awesome Sink Project that I now maintain that allows to add Application Insights integration with Serilog. It's mostly self explanatory, however it's platform agnostic and can be used from any project type like console application or asp.net web api etc.

In order to use it with Azure Functions you can simply add this piece of code in Azure Function static constructor (or a global static initialisation function, if you have many function files):

static MyFunctions()
{
    var config = TelemetryConfiguration.Active;
    if (config != null)
    {
        //logging
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .Enrich.FromLogContext()
            .WriteTo.ApplicationInsightsTraces(config)
            .CreateLogger();
    }
}

Note that I'm using TelemetryConfiguration.Active here, which makes serilog _pick up already configured _Application Insights. Also, in order for this to work, you need to enable AI integration by following the official documentation.

Once done, you will be able to not only see those messages in AI, but log messages will also be correlated between functions calls. What this means is Functions Portal will be able to know which messages are related to which function executions!

Function Apps  p Search  All subscriptions   Function Apps  Functions Read Only  f FtplngestScan  Integrate  Manage  Monitor  proxies Read Only  Slots preview   FtplngestScan  Refresh  Application Insights Instance  DATE LITC v  20190214 152300122  20190214 152200140  20190214  20190214  20190214  20190214  20190214 151700099  20190214  20190214  20190214  Success count in last 30 days  e 2797  Error count in last 30  0 66  RESULT CODE  Invocation Details  Run in Application Insights  DATE UTC  LOG LEVEL  201902  201902  201902  14  14  14  scanning FTP  detected O items  created O inwices


Thanks for reading. If you would like to follow up with future posts please subscribe to my rss feed and/or follow me on twitter.