0
votes

Im working on a simple Blob trigger that takes CSV-files from a blob storage into SQL.

The functionality of my function is working but i want to add Application Insights in Azure to be able to get notifications about exceptions and logging information. I just cant wrap my head around it. I have been googling around for days and reading loads of articles but cant seem to find anything that works. Im new to Azure and programming in general so its a bit hard to understand some of the examples out there.

I added Application Insights to my function in the portal, and added the Instrumentationkey to the appsettings in the function. When i use Tracewriter in the function, i can publish it and the functions is working (except Application Insights is dead).

When i change to ILogger instead (which is recommended) and publish, i get zero information in my Application Insights and my functions isnt working at all.

I read one article saying that you can just add the Application Insights and istrumentationkey to your function, then add a nuget-package and its gonna work. While another article has some complex example where they build something in the startup.cs class. Just alot of different information and i dont have the experience to know what is right or wrong for my specific application.

My function currently looks like this (.NET Core 2.1):

    public static class BlobTrigger
{
    [FunctionName("BlobToSql")]
    public static async Task Run([BlobTrigger("myblobstorage", Connection = "AzureWebJobsStorage")]
        CloudBlockBlob blob, ILogger log)
    {
        Exception exception = null;
        log.LogInformation($"BlobTrigger processed a request for blob: {blob.Name}");

        var csvToSqlHandler = new CsvToSqlHandler();

        if (!blob.Name.EndsWith(".CSV"))
        {
            log.LogError(($"Blob '{blob.Name}' doesn't have the .csv extension. Skipping processing."));
            return;
        }

        try
        {
            var dataTable = await csvToSqlHandler.CreateDataTableFromCsv(blob);

            csvToSqlHandler.FormatDataTable(dataTable, blob.Name);

            csvToSqlHandler.FormatDataTableColumns(dataTable, blob.Name);

            await csvToSqlHandler.DataTableToSql(dataTable, blob.Name);
        }
        catch (Exception e)
        {
            exception = e;
            log.LogError($"{blob.Name} failed. Exception: {exception.Message}");
        }

        if (exception == null)
        {
            await blob.DeleteAsync();
        }
        log.LogInformation($"Blob '{blob.Name}' successfully executed!");
    }
}

Using this:

using System;
using System.Threading.Tasks;
using BlobToSqlConverter.Handlers;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Blob;

I just want to see some logs in the Application Insights on Azure and ill be happy, it would also be nice if my functions dont die every time i publish using ILogger.

I would really appriciate if anyone took their time helping me with this.

1

1 Answers

1
votes

If you configure the APPINSIGHTS_INSTRUMENTATIONKEY correctly in the application settings of the azure function, then the ILogger will automatically writes data to application insights.

Assume you create the azure function(v2) from visual studio -> azure function template, I write the code like below in my Function.cs:

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

namespace MyFunctionApp3
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static void Run([BlobTrigger("f22/{name}", Connection = "AzureWebJobsStorage")]Stream myBlob, string name, ILogger log)
        {
            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes !!!");
            log.LogTrace("this is a trace info from ilogger !!!");
            log.LogInformation("this is a information from ilogger!!!");
        }
    }
}

And you can also control the log level by adding the following code to the host.json file:

{
  "version": "2.0",
  "logging": {
    "fileLoggingMode": "always",
    "logLevel": {
      "default": "Trace",
      "Host.Results": "Error",
      "Function": "Trace",
      "Host.Aggregator": "Trace"
    }
  }
}

Then publish it to azure.

After publish it successfully to azure, nav to azure portal -> your function app -> Application settings: add the field APPINSIGHTS_INSTRUMENTATIONKEY and it's value. then click save. like below:

enter image description here

Then you can upload a file to the blob storage, then go to your azure function log console, you can see the logs written by ILogger are there:

enter image description here

At the end, nav to azure portal -> your application insights -> search page, and click the refresh button, you can see the logs written by ILogger are shown(it may take a few minutes):

enter image description here

Please let me know if you have any questions.