Azure app insights TelemetryConfiguration not working in Startup.cs file of azure function - azure

my startup file looks like this
[assembly: FunctionsStartup(typeof(Startup))]
{
public override void Configure(IFunctionsHostBuilder builder)
{
var context = builder.GetContext();
var _config = context.Configuration;
var telemetryConfig = new TelemetryConfiguration();
telemetryConfig.ConnectionString = _config.GetConnectionString("ApplicationInsights");
builder.Services.AddSingleton<TelemetryClient>(x => new TelemetryClient(telemetryConfig));
}
}
and the settings file looks like this
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"APPINSIGHTS_INSTRUMENTATIONKEY": "xxxxxx-fbc9-441b-9869-70bcb4afc93a",
"TimerInterval": "0 */5 * * * *"
},
"ConnectionStrings": {
"ApplicationInsights": "InstrumentationKey=xxxxxx-fbc9-441b-9869-
70bcb4afc93a;IngestionEndpoint=https://xxx-
in.applicationinsights.azure.com/;LiveEndpoint=https://xxxxxx.livediagnostics.monitor.azure.c
om/" }
}
problem here is that telemetryConfig is set properly i can see the InstrumentationKey and ConnString
but new TelemetryClient(telemetryConfig) has InstrumentationKey empty and most of the properties set to null.
even if i set InstrumentationKey directly (which is obsolete) the dependency injected value in the code has empty InstrumentationKey
in code i am using it like this
private readonly TelemetryClient _telemetry;
public FHIRExtract(ILogger<FHIRExtract> logger, TelemetryClient telemetry, IConfiguration configuration)
{
_logger = logger;
_config = configuration;
_telemetry = telemetry;
}
[FunctionName("FHIRExtract")]
public async Task Run([TimerTrigger("%TimerInterval%"
_telemetry has InstrumentationKey empty
but when i set this value in the code
//_telemetry.InstrumentationKey = "xxxxxx-fbc9-441b-9869-70bcb4afc93a";
it works and i am able to send telemetry data
I am trying to use non obsolete functions to configure Telemetry client and want to use it by DI.
what am i doing wrong ?

You shouldn't setup Application Insights this way.
Install the Microsoft.Azure.WebJobs.Logging.ApplicationInsights NuGet package in the azure functions project
In the Configure override add the logging:
builder.Services.AddLogging();
Configure the instrumentatio key by setting APPINSIGHTS_INSTRUMENTATIONKEY in the settings.json file
Inject a TelemetryConfiguration in your function and create an instance of TelemetryClient:
public FHIRExtract(ILogger<FHIRExtract> logger, TelemetryConfiguration
telemetryConfig, IConfiguration configuration)
{
_logger = logger;
_config = configuration;
_telemetry = new TelemetryClient(telemetryConfig);
}
For some reason the custom telemetry logging in azure functions breaks when only setting APPLICATIONINSIGHTS_CONNECTION_STRING in the configuration but I am sure that will be fixed in the near future. In my experience the application insights integration always lags behind a bit.
References:
Offical docs
Sample repository demoing various Application Insights techniques

Related

When deploy Azure function to Azure how did it know that it should read the AzureFunctionSettings from App settings instead of from local.setting.json

I created my first Azure Function which integrate with SharePoint Online list, using those main points:-
1-I created an Azure App with self-sign certificate to authorize my Azure function.
2-I created a new Azure Function project using Visual Studio 2019. here are the main components
-Function.cs:-
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using PnP.Core.Services;
using PnP.Core.Model.SharePoint;
using System.Collections.Generic;
namespace FunctionApp1
{
public class Function1
{
private readonly IPnPContextFactory pnpContextFactory;
public Function1(IPnPContextFactory pnpContextFactory)
{
this.pnpContextFactory = pnpContextFactory;
}
[FunctionName("Function1")]
public void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
using (var context = pnpContextFactory.Create("Default"))
{
var myList = context.Web.Lists.GetByTitle("SubFolders");
Dictionary<string, object> values = new Dictionary<string, object>
{
{ "Title", System.DateTime.Now }
};
// Use the AddBatch method to add the request to the current batch
myList.Items.AddBatch(values);
context.Execute();
}
}
}
}
-Startup.cs:-
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PnP.Core.Auth;
using System.Security.Cryptography.X509Certificates;
[assembly: FunctionsStartup(typeof(FunctionApp1.Startup))]
namespace FunctionApp1
{
class Startup :FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var config = builder.GetContext().Configuration;
var azureFunctionSettings = new AzureFunctionSettings();
config.Bind(azureFunctionSettings);
builder.Services.AddPnPCore(options =>
{
options.DisableTelemetry = true;
var authProvider = new X509CertificateAuthenticationProvider(azureFunctionSettings.ClientId,
azureFunctionSettings.TenantId,
StoreName.My,
StoreLocation.CurrentUser,
azureFunctionSettings.CertificateThumbprint);
options.DefaultAuthenticationProvider = authProvider;
options.Sites.Add("Default", new PnP.Core.Services.Builder.Configuration.PnPCoreSiteOptions
{
SiteUrl = azureFunctionSettings.SiteUrl,
AuthenticationProvider = authProvider
});
});
}
}
}
-local.setting.json:-
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"SiteUrl": "https://***.sharepoint.com/",
"TenantId": "0b***",
"ClientId": "92***",
"CertificateThumbPrint": "EB***",
"WEBSITE_LOAD_CERTIFICATES": "EB***"
}
}
then i deploy it to Azure and it is working well, where each 5 minutes it adds a new list item.
But what i am unable to understand, is that when i test the function locally, the function reads its setting from the local.settings.json file, but after deploying it to Azure it start reading its settings from the online Azure App settings.. so how it did this behind the senses ?
This is by design.
App settings in a function app contain configuration options that affect all functions for that function app. When you run locally, these settings are accessed as local environment variables.
and
You can use application settings to override host.json setting values without having to change the host.json file itself. This is helpful for scenarios where you need to configure or modify specific host.json settings for a specific environment. This also lets you change host.json settings without having to republish your project.
Taken from App settings reference for Azure Functions.

ASP.NET Core Web App .NET 6, reading configuration from within a Razor pages' cs file

I'm trying to find a simple way to access a value from the configuration of a .NET 6, ASP.NET Core Web App, in a Razor page's .cs file, using Visual Studio 2022. There's a lot of examples of how to do this online the old way. I'm trying to get up to speed with ASP.NET Core, and .NET 6, and I don't want to use the old techniques.
Right now I can connect to a SQLite database with a very simple configuration. Here's the code in my Index.cshtml.cs file,
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using System.Data.SQLite;
namespace Something.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
var cnnStrBuilder = new SQLiteConnectonStringBuilder();
cnnStrBuild.DataSource = "DBFile.SQLite";
using (SQLiteConnection cnn = new(cnnStrBuilder.ConnectionString))
{
cnn.Open();
...
}
}
}
}
This works. I can read and display data without the need for a DBContext, or EntityFramework, or anything else. All I want to change is to get the connection string from the appsettings.json file. My appsettings.json looks like this,
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"MyConStr" : "DBFile.SQLite"
},
"AllowedHosts": "*"
}
in my Program.cs file is the builder object, which I could use to get the configuration.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
but how do I get access to the builder object in the Razor page's .cs file so I can get to the configuration? .NET 6 is supposed to make things like this easier, I thought.
BTW, I purposefully left 'connection string' out of the title of this post because I feel like this should be a generic thing. It shouldn't be so hard to retrieve a string value from the configuration settings from anywhere in the application. What am I missing?
You can inject an instance of IConfiguration in your PageModel which you can use to access appsettings.json values.
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
private readonly IConfiguration _configuration;
public IndexModel(ILogger<IndexModel> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
public void OnGet()
{
var cnnStrBuilder = new SQLiteConnectonStringBuilder();
cnnStrBuild.DataSource = _configuration.GetConnectionString("MyConStr");
using (SQLiteConnection cnn = new(cnnStrBuilder.ConnectionString))
{
cnn.Open();
...
}
}
}
You can also check this article for more info:
https://www.learnrazorpages.com/configuration/

Project level Culture setting for Azure Functions App

Is it possible to change culture on a project level on Azure Functions App?
https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings
The app is using Consumption plan or Premium plan, not via ASP.NET Core.
My Startup.cs file is like below:
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
}
}
Can ASP.NET Core that is based on different Startup.cs not like above use Consumption plan or Premium plan??
Asp.net Core that must use App Service plan like below:
https://andrewlock.net/adding-localisation-to-an-asp-net-core-application/
When migrating legacy application running on servers to Azure you always need to take care of Timezone and Culture settings that originally are fetched from the machine. For Azure Functions you can set the timezone in the app settings:
WEBSITE_TIME_ZONE=Europe/London
Possible values found here https://en.wikipedia.org/wiki/List_of_tz_database_time_zones. This actually differs for app services that seem to use TZ for Linux and WEBSITE_TIME_ZONE for Windows.
For culture it is more complicated. Using aspnet core you define it in Configure in the Startup class
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
ILoggerFactory loggerFactory)
{
var cultureInfo = new CultureInfo("en-US");
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(cultureInfo),
SupportedCultures = new List<CultureInfo>
{
cultureInfo,
},
SupportedUICultures = new List<CultureInfo>
{
cultureInfo,
}
});
}
That is not possible in Azure Function Apps. What you can do is to create a Setup class and then set the culture for the appdomain and the current thread. This will probably work as long Azure isnt altering the Appdomain.
[assembly: FunctionsStartup(typeof(Startup))]
namespace FunctionApp
{
public class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder app)
{
var cultureInfo = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
}
}
}
Azure Function didn't provide a built-in method to change culture.
Put this at the starting of your function app:
using System.Threading;
using System.Globalization;
//......
string culture = "en-US";
CultureInfo CI = new CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = CI;
Above code will change the culture to en-US. You can set it to other value.
This is the document:
https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.currentculture?view=netcore-3.1
Does this solved your problem?

Where in Azure Portal are the logger.Log statements?

I have a .NET Core WebAPI app. The app is deployed on Azure as an App Service.
In the code, I have enabled Application Insights like so
public static IWebHost BuildWebHost(string[] args) =>
WebHost
.CreateDefaultBuilder(args)
.UseApplicationInsights()
.UseStartup<Startup>()
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")).SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Error);
logging.AddApplicationInsights(" xxxxx-xxxx-xxxx-xxxx--xxxxxxxxxxx").SetMinimumLevel(LogLevel.Trace);
})
.Build();
In the constructor of a controller and inside an method of a controller I have these logging statements.
_logger.LogInformation("ApiController, information");
_logger.LogWarning("ApiController, warning");
_logger.LogCritical("ApiController, critical");
_logger.LogWarning("ApiController, error");
_logger.LogDebug("ApiController, debug");
In the Azure Portal I have Application Insights for my App Service enabled. Here a picture from the portal.
App Insights in Azure Portal
But where do I see the logging statements in the Azure portal?
When I go to Application Insights -> Logs and I query by
search *
I can see the requests made to the API but not the logging statements.
Application Insights Log
Where are the log statements?
First, it is not good practice to configure the log level in code. You can easily configure the log level in the appsettings.json file. So in Program.cs -> public static IWebHost BuildWebHost method, change the code to below:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseApplicationInsights()
.UseStartup<Startup>()
.Build();
Then in appsettings.json(also right click the file -> properties -> set "copy to output directory" to "Copy if newer"):
{
"Logging": {
"IncludeScopes": false,
"ApplicationInsights": {
"LogLevel": {
"Default": "Trace"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"ApplicationInsights": {
"InstrumentationKey": "the key"
}
}
In Controller, like ValuesController:
public class ValuesController : Controller
{
private readonly ILogger _logger;
public ValuesController(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<ValuesController>();
}
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
_logger.LogInformation("ApiController, information");
_logger.LogWarning("ApiController, warning");
_logger.LogCritical("ApiController, critical");
_logger.LogWarning("ApiController, error");
_logger.LogDebug("ApiController, debug");
return new string[] { "value1", "value2" };
}
}
Run the project, and wait for a few minutes(application insights would always take 3 to 5 minutes or more to display the data). Then nave to azure portal -> application insights logs, remember that all the logs written by ILogger are stored in "traces" table. Just write the query like "traces" and specify a proper time range, you should see all the logs like below:

Serilog: azure webjob logging doesn't seem to work when hosted in azure?

I have azure webjob sdk (v3.0.3) app which has been configured to use serilog for logging.
The log seems to work when I run the app locally in my system. Below is the configuration:
static void Main(string[] args)
{
try
{
var builder = new HostBuilder()
.ConfigureAppConfiguration(SetupConfiguration)
.ConfigureLogging(SetupLogging)
.ConfigureServices(SetupServices)
.ConfigureWebJobs(webJobConfiguration =>
{
webJobConfiguration.AddTimers();
webJobConfiguration.AddAzureStorageCoreServices(); //this is to store logs in azure storage
})
.UseSerilog()
.Build();
builder.Run();
}
}
The code for SetupConfiguration is below:
private static void SetupConfiguration(HostBuilderContext hostingContext, IConfigurationBuilder builder)
{
var env = hostingContext.HostingEnvironment;
_configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
}
The code for setting up services:
private static void SetupServices(HostBuilderContext hostingContext, IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<IConfiguration>(_configuration);
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(_configuration)
.CreateLogger();
_logger = serviceCollection.BuildServiceProvider().GetRequiredService<ILoggerFactory>().CreateLogger("test");
}
The logging is setup as following:
private static void SetupLogging(HostBuilderContext hostingContext, ILoggingBuilder loggingBuilder)
{
loggingBuilder.SetMinimumLevel(LogLevel.Information);
loggingBuilder.AddConsole();
loggingBuilder.AddDebug();
loggingBuilder.AddSerilog(dispose: true);
}
In my TimerTrigger method I'm using the logger:
[Singleton]
public async static Task Trigger([TimerTrigger("%Job%")]TimerInfo myTimer)
{
_logger.LogInformation($"From Trigger {DateTime.UtcNow.ToString()}");
}
In appSettings.json, serilog is configured as follows:
"Serilog": {
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"pathFormat": ".\\Log\\log-{Date}.txt",
"retainedFileCountLimit": 7,
"fileSizeLimitBytes": 5000000,
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} {EventId} [{Level}] [{Properties}] {Message}{NewLine}{Exception}"
}
}
]
}
the folder "Log" and the log files get created when i run the app locally. But when I publish the webjob, the "Log" folder or the log file is not created in the "app_data" folder of webjob. Can anyone help me figureout how to configure serilog to make it work with webjobs?
Following are the nuget packages used:
If you want to use serilog in WebJob , you need to install this package Serilog.Extensions.WebJobs. Then after configuring the serilog, you would be able to use it.
You must inject the ILogger rather than using the global Log.Logger otherwise the log messages will not be written to the Microsoft Azure WebJobs dashboard.
About the detailed description about how to configure and use serilog, you could refer to this doc.
Hope this could help you, if you still have other questions, please let me know.

Resources