How To Store Logs in Azure Functions Which Can Be Accessed Later

How To Store Logs in Azure Functions Which Can Be Accessed Later

In this Azure tutorial, we will discuss How To Store Logs in Azure Functions Which Can be accessed later. Along with this, we will also discuss a few other topics like Configure Azure Application Insights, View Log Data in Monitor tab, Default Azure Functions log location, Azure Function ILogger, Azure Functions Logging, Azure Function Log To Blob Storage and we will also discuss Where To See Logs in Azure Functions, View Azure Function Log From Visual Studio 2019, View Azure Function Log From Azure Storage Explorer, etc.

How To Store Logs in Azure Functions Which Can Be Accessed Later? There are few options for this purpose that are:

  • Azure Application Insight is an excellent inbuilt tool and one of the best option provided by Microsoft that stores the logs on the Performance, Exception logs, etc
  • You can use the ILogger interface for the logging purpose in the case of Azure Functions to write Logs.
  • All the Logging and timing information related to your Azure Function also stores in the Storage account that you created while creating your Function App initially.

How To Store Logs in Azure Functions Which Can Be Accessed Later

Well, Let’s discuss a very important topic, How To Store Logs in Azure Functions Which Can Be Accessed Later. As we all know, Logs are very important to track how the Azure Function behaves. In case, If the Azure Function fails or didn’t work properly then we can analyze the logs to get some Idea what exactly happened to the Azure Function.

The log details helps us to fix the issue related to the Azure function with less time.

Azure Functions provides a great inbuilt tool to store the log files related to the Azure Function that is known as Azure Application Insights.

This is an excellent tool from Microsoft that monitors your Azure Function closely and stores all the Log, Performance, and the error data, Exceptions, etc that really helps you to troubleshoot your Azure Function in case of any issues or exceptions.

How To Enable Application Insights For Azure Functions

You can integrate the Application Insights with your Azure function at free but there is some data limit per day that you can utilize free of cost.

Configure Azure Application Insights

If you are first time configuring the Azure Application Insights, You can enable it by following the below steps

Navigate to the Azure Function App, on the Function App page, click on the Application Insights link from the left navigation and then click on the Turn on Application Insights button.

Configure Azure Application Insights

Select the Enable option under the Application Insights option.

Enable Azure Application Insights 1

Expand the Change your resource option, Choose the Create new resource option unless and until you already set up an Application Insights resource for this particular app and then click on the Apply button.

How to Enable Azure Application Insights

Once you click on the Apply button, It will prompt you the below Pop up, click on the Yes button. Now it will show you the changes are applied.

How to setup Azure Application Insights

Now if you will click on the Application Insights link from the left navigation again.

Now you need to select the below options based on your need for how you want to get the data. Select the below options and then click on the Apply button to save the changes.

How to Configure Azure Application Insights

View Log Data in Azure Function Monitor Tab

Once you enabled the Azure Application Insights, you can view the log data from the Monitor tab.

Navigate to the Azure Function App and then click on the Functions option from the left navigation. Then on the Functions page, click on the Monitor link from the left navigation.

One important thing to remember here is that the function must be run at least once after you enable the Application Insights option.

How To Store Logs in Azure Functions Which Can Be Accessed Later

You can click on each date on the Date (UTC) column to see the log data in detail for that particular date.

Now click on the Run query in Application Insights link, it will provide you the details on the source of the query that retrieves the Azure Monitor Log Data. Since I was configuring this option for the first time so it showed me the below options, I clicked on the Get Started button.

Azure Functions logs in Application Insights in Azure Portal

Now it will configure the Azure Monitor Log Analytics tool successfully that helps to provide insights from the Azure Monitor Logs.

Now you can able to see the following Query window. it provides you the last 30 days log data.

Azure Functions Logging to Application Insights

Default Azure Functions log location

While creating the Azure Functions app for the first time, we are configuring the Azure Storage account along with that. If we will navigate to the file service in the Storage account, you can find the host and function logs in the “/LogFiles/Application/Functions” directory.

Azure Function TraceWriter

Initially, Azure function provided the logging mechanism with the help of the TraceWriter class. This is was the first logging mechanism that was available in the case of Azure Functions.

The format was like below

public static void Run(Message msg, TraceWriter log)
{
  log.Info("Logging with TraceWriter");
}

But there were many problems were there with the TraceWriter like it is only helpful for the applications being executed by the Azure Functions runtime so all the Classes need to be tightly coupled with the TraceWriter class and this is not at all a good idea.

Now, to overcome these issues ILogger interface came into picture for the same purpose.

Azure Function ILogger

Well, this is a very important concept as part of the Logging functionality in the case of the Azure Function. So a question that comes to our mind is How can we log the information or error from the Visual Studio to the Application Insights.

So, here is the ILogger interface that comes into the picture in this case, With the help of the ILogger interface, we can create a properly structured logging inside our Azure function and can store the information inside the Application Insights.

This the alternative to the TraceWriter which was there earlier before the ILogger for the same purpose. But there are few disadvantages to the TraceWriter. To Overcome the problems with TraceWriter, ILogger comes into Picture and this is one of the best options as of now for logging purpose in Azure Functions.

ILogger can be used for logging different purposes like below

  • LogInformation
  • LogTrace
  • LogWarning
  • LogError
  • LogDebug
  • LogCritical

Now the next thing is that how can we implement the Logging functionality in your function in Visual Studio 2019 and then how you store that logs information in the Azure Application Insights.

The first thing is, you can create an Azure Application Insights in the Azure Portal first. To do that follow the below steps

Step-1: Login to Azure Portal (https://portal.azure.com/)

Step-2: Search for the Application Insights and click on the Search result.

Azure Function ILogger

Step-3: Now click on the + Add button on the Application Insights window to create a new Application Insights.

azure functions ilogger application insights

Step-4: For the Basics tab on the Application Insights window, Provides the appropriate values for the below options

  • Subscription: Choose your Subscriptions.
  • Resource Group: Provide the existing Resource group if you have any or else you can click on the Create new link to create a new Resource Group.
  • Name: Provide a valid name for the Application Insights.
  • Region: Select the location for the Application Insights.
  • Resource Model: Choose Classic as the Resource Model

Now click on the Review + create button.

azure function application insights dependency injection

Now click on the Create button on the below window to create the Application Insights.

azure functions logging

Now the Application Insights will create successfully, now click on the Go to Resource button to go to the newly created Application Insights. On the Overview tab, copy the instrumentation key as high lighted below as we are going to use this in our code in visual studio.

azure functions logging configuration

Now we have the Application Insights created in the Azure Portal and ready to use.

Azure Functions Logging

The next thing is, Open your Azure Function project and open the local.settings.json file and add the code to provide the InstrumentationKey that you have copied above for your Application Insights.

{
  "ApplicationInsights": {
    "InstrumentationKey": "c854346f-8d4f-41c6-b692-767df3e8c6e3",
    "IsEncrypted": false,
    "Values": {
      "AzureWebJobsStorage": "UseDevelopmentStorage=true",
      "FUNCTIONS_WORKER_RUNTIME": "dotnet"
    }
  }
}

You have to to provide the value for the InstrumentationKey as highlighted like below.

azure function app insights ilogger

Now if you can see the Azure function looks like below with the ILogger as the Parameter.

  [FunctionName("Function1")]
    
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {

Now you can add the code for the logging inside the Azure Function like below.

 log.LogInformation("hello checking the log");

Now the complete function looks like below

[FunctionName("Function1")]
    
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
           
            string name = req.Query["name"];
            log.LogInformation("hello checking the log");
            
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }

See it now

Azure Functions app Logging

Now you can Publish the function to Azure and Don’t forget to run and test the Azure function once in the Azure Portal by clicking on the Code + Test link from the left navigation on the Function page and then click on the Test/Run button from the top to run and test the function once.

Now navigate to the Application Insights that we have created above and then click on the Search from the left navigation and then click on the Refresh button from the top to get the updated contents.

azure functions v2 logging

Then, search for the same text that you put inside the Azure function code for logging. Now you can able to see the log for the same.

application insights logging

If you click on that, It will show you the details like below

Logging with ILogger in Azure Functions

Azure Function Log To Blob Storage

All the logging information and timing information related to your Azure function is by default stored in the Storage account that you have created while creating the Azure Function initially if you remember. It stores the log details in Table storage By default.

Where To See Logs in Azure Functions

Above, we discussed the detailed steps where to see the logs in the Azure Application Insights in the Azure Portal. Once it stores the logs in the Azure table storage, now we will discuss Where to see the Azure Function logs in Visual Studio 2019 and Where exactly we need to check the Logs in the Azure Storage Explorer.

View Azure Function Log From Visual Studio 2019

You can able to see or view the log details that are stored in the table storage from the Visual studio itself. But before that, you make sure you have already installed the Azure SDK for your Visual Studio. Now let’s see how to view the Logs from the Visual Studio 2019. Follow the below steps to view the logs in your Visual Studio 2019.

Open your Azure Functions Project that you have created already in Visual Studio 2019.

The next step is to open the Cloud Explorer by Navigating to the option View —> Cloud Explorer

Azure Function Log To Blob Storage

On the Cloud Explorer window, expand the Storage Accounts and then expand the function app for which one you want to see the logs. Now expand the Tables, you can able to see AzureWebJobsHostLogs with the date.

How to send Azure Function logs to blob storage?

Now if you will open that you can able to see the logs as below

Azure Function Write To Blob Storage

Now you click on the each logs to see the logs in details as below.

how to send azure function log to blob storage

View Azure Function Log From Azure Storage Explorer

You can able to view the Azure Function logs from the Azure Storage Explorer as well. Follow the below steps to view the Azure Function logs using the Azure Storage Explorer.

 Login to Azure Portal (https://portal.azure.com/) to copy the value for your App setting key Azure WebJobsStorage.

Once you logged in to the Azure Portal, navigate to the Azure Function app for which one you want to see the logs. On the Function App page, click on the Configuration from the left navigation.

View Azure Function Log From Azure Storage Explorer

Now Under Application settings, locate the AzureWebJobsStorage and click on that link to get the value for the AccountName and AccountKey as highlighted below.

how to send azure function log using blob storage

Now copy the value and extract the Account Name and Account Key from there and keep it somewhere as you need to use those values in the Azure Storage Explorer.

View Azure Function Log using Azure Storage Explorer

Now Open the Azure Storage Explorer that you have installed in your Machine before. If you have not installed till now, you can install the Azure Storage Explorer now.

Now use the Account name and the Accountkey that you have copied before in your Azure Storage Explorer to retrieve the log details for your Azure Functions. Follow the below steps in the Azure Storage Explorer.

Open the Azure Storage explorer from your machine and click on the Open Connect Dialog button from the left side.

How to View Azure Function Log using Azure Storage Explorer

Select the option “Use a storage account name and key” from the below Pop up and then click on the Next button.

How to View Azure Function Log from Azure Storage Explorer

Now provide the below details on the Connect with Name and Key window

  • Display Name: Provide a name for the connection
  • Account name: Provide the Account name that you copied before as mentioned on the above steps.
  • Account Key: Provide the Account key that you copied before as mentioned on the above steps.
  • Storage Domain: Select the storage domain option as Azure and then click on the Next button.
How to View Azure Function Log in Azure Storage

Now. on the Connection Summary page, validate all the details provided before and then click on the Connect button to establish the Azure connection.

Azure Function Logs To Blob Storage

Now it created a connection with the name that we provided now expand the connection name and then expand the Tables, You can able to see the AzureWebJObsHostLogs with the date as highlighted below.

Azure Function Logs To Blob Storage configuration

Now if you will click on that, you can able to see the list of logs like below

Monitoring Azure Functions with Azure Monitor Logs

This is how we can How to access Azure Function Log From Visual Studio 2019 and View Azure Function Log From Azure Storage Explorer.

You may also like following the below Articles

Wrapping Up

Well, In this article, we have discussed, How To Store Logs in Azure Functions Which Can Be Accessed Later, Configure Azure Application Insights, How To Enable Application Insights For Azure Functions, View Log Data in Azure Function Monitor Tab, and then we discussed, Default Azure Functions log location, Azure Function ILogger, Azure Functions Logging, Azure Function Log To Blob Storage.

Then finally we discussed, Where To See Logs in Azure Functions, View Azure Function Log From Visual Studio 2019, View Azure Function Log From Azure Storage Explorer.

Leave a Comment