How to debug EventHubTrigger locally? - azure

I'm trying to debug an Azure Function locally. It's an EventHubTrigger.
The problem is that I need to debug the code locally because I still don't have the "real" settings.
My code currently looks like this:
public static class Notificator
{
[FunctionName("Notificator")]
public static async Task Run([EventHubTrigger("achievements")]UserAchivementNofication notification, ILogger log)
{
}
}
But when I try to debug it, I'm getting this error:
Microsoft.Azure.WebJobs.Host: Error indexing method
'Notificator.Run'. Microsoft.Azure.WebJobs.ServiceBus: No event hub
receiver named achievements.
And it's normal, because it doesn't exist.
My local.settings.json is like this:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true"
}
}
How can I debug my code?
Thank you!

You need to create an EventHub on Azure so that you can test the EventHug trigger locally,
Goto local.settings.json to add some settings:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true",
"EventHubConnectionString": "YourEventHubConnectionString"
}
}
Your function should be like this:
public static void Run([EventHubTrigger("EventHubName", Connection = "EventHubConnectionString")]EventData myEventHubMessage, TraceWriter log)

Related

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

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

Azure Durable Functions - OrchestrationTrigger stuck

I am new to azure durable functions. I have created a sample azure durable function using vs 2019. I am running default generated azure durable function template code locally with azure storage enumerator and when I run the durable function, the OrchestrationTrigger stuck and not able to resume.
The hub name is samplehubname. There a pending records present in the samplehubnameInstances azure table but there is no records in the samplehubnameHistory azure table.
There is no exception and no errors in the code.
SampleFunction.cs
public static class SampleFunction
{
[FunctionName("SampleFunction")]
public static async Task<List<string>> RunOrchestrator(
[OrchestrationTrigger] IDurableOrchestrationContext context)
{
var outputs = new List<string>();
// Replace "hello" with the name of your Durable Activity Function.
outputs.Add(await context.CallActivityAsync<string>("SampleFunction_Hello", "Tokyo"));
// returns ["Hello Tokyo!", "Hello Seattle!", "Hello London!"]
return outputs;
}
[FunctionName("SampleFunction_Hello")]
public static string SayHello([ActivityTrigger] string name, ILogger log)
{
log.LogInformation($"Saying hello to {name}.");
return $"Hello {name}!";
}
[FunctionName("SampleFunction_HttpStart")]
public static async Task<HttpResponseMessage> HttpStart(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestMessage req,
[DurableClient] IDurableOrchestrationClient starter,
ILogger log)
{
// Function input comes from the request content.
string instanceId = await starter.StartNewAsync("SampleFunction", null);
log.LogInformation($"Started orchestration with ID = '{instanceId}'.");
return starter.CreateCheckStatusResponse(req, instanceId);
}
}
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"AzureWebJobsSecretStorageType": "files", //files
"MyTaskHub": "samplehubname"
}
}
host.json
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensions": {
"durableTask": {
"hubName": "%MyTaskHub%"
}
}
}
samplehubname-control-03 Message Queue
{"$type":"DurableTask.AzureStorage.MessageData","ActivityId":"72b75a34-e403-4772-aed0-fbb10039795a","TaskMessage":{"$type":"DurableTask.Core.TaskMessage","Event":{"$type":"DurableTask.Core.History.ExecutionStartedEvent","OrchestrationInstance":{"$type":"DurableTask.Core.OrchestrationInstance","InstanceId":"f8d0499a4297480c8bdf4a56954861d3","ExecutionId":"2e46b87e4cf74c2dab572d92e012bded"},"EventType":0,"ParentInstance":null,"Name":"Function1","Version":"","Input":"null","Tags":null,"EventId":-1,"IsPlayed":false,"Timestamp":"2021-09-21T15:41:35.0156514Z"},"SequenceNumber":0,"OrchestrationInstance":{"$type":"DurableTask.Core.OrchestrationInstance","InstanceId":"f8d0499a4297480c8bdf4a56954861d3","ExecutionId":"2e46b87e4cf74c2dab572d92e012bded"}},"CompressedBlobName":null,"SequenceNumber":1,"Sender":{"$type":"DurableTask.Core.OrchestrationInstance","InstanceId":"","ExecutionId":""}}
Any help will appreciated.
If your orchestration code has contain a loop too much, the guidance in our Eternal orchestration documentation.
In your code there is not much loop available. So, you need to use the durable functions eternal orchestrations TerminateAsync (.NET) method of the orchestration client binding to stop it.
Add your durable function into application insights to check the clear view of issue. It may help to fix the issue.
Check the similar issue here.
Try the steps and use fan in/ fan out in durable function durable functions patterns fan out and fan in

Azure Functions V3 ILogger using DI - messages from logger not in traces

In my Azure Function I am trying to log using the DI container; however I am unable to get the logger to display messages in the Log Stream or the Traces in Application Insights. I have created a minimal code sample project which I am testing using the Azure Portal (Code + Test) shown here.
I've tried using Serilog same result.
I've tried removing the log parameter from Function1 - then I get no errors nor messages
I assume I'm missing something simple/obvious but I'm stuck.
namespace LoggingApiTest {
public class Function1 {
private readonly ILogger<Function1> logger;
public Function1(ILogger<Function1> logger)
{
this.logger = logger;
logger.LogInformation("In Function1 ctor using DI created Logger");
}
[FunctionName("Function1")]
public IActionResult Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "Test")] HttpRequest req,
ILogger log) {
logger.LogInformation("Hello from DI Logger");
log.LogInformation("Hello from logger passed as parameter");
return new OkObjectResult("Hello");
}
}
}
startup
namespace LoggingApiTest {
public class Startup : FunctionsStartup {
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddLogging();
}
}
}
host.json
enter code here{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
},
"logLevel": {
"default": "Information"
}
}
}
}
The LogStream shows 2021-07-16T12:59:50.705 [Information] Executing 'Function1' (Reason='This function was programmatically called via the host APIs.', Id=b8238346-7ff7-450d-a7f0-abc8f1a210fa) 2021-07-16T12:59:50.705 [Information] Hello from logger passed as parameter 2021-07-16T12:59:50.705 [Information] Executed 'Function1' (Succeeded, Id=b8238346-7ff7-450d-a7f0-abc8f1a210fa, Duration=1ms)
In your logging section of your host.json file, try adding your solution namespace with the logLevel. This should enable logging at a logLevel of Information and above.
{
"version": "2.0",
"logging": {
"logLevel": {
"LoggingApiTest": "Information"
}
}
}
https://github.com/Azure/azure-functions-host/issues/4425#issuecomment-492678381

Azure Functions - TimerTrigger - Error when ran locally

I have an issue when I start Azure Functions project locally. I am using AzureFunctions v1 (.Net Framework). The error I get is following:
This is my local.settings.json:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true",
"StorageConnectionString": "UseDevelopmentStorage=true"
}
}
I googled the error without much luck.
What could be the couse of this error? Is it about configuration? Also, these are all TimerTrigger functions.
Thanks..
EDIT:
public class TimerPing: _BaseTrigger
{
static TimerPing()
{
Init();
}
[FunctionName("Timer_Ping")]
public static void Run([TimerTrigger("0 * * * * *", RunOnStartup = true)]TimerInfo myTimer, TraceWriter log)
{
//TryRun(() =>
//{
// ErrorHandler.InsertServiceLog(
// $"{SERVICE_NAME} - Ping",
// "ping",
// SensorType.Success);
//});
}
}
Please note that everything is commented out and this error still presists.
Also, in Output window on VS 2017 I get this:
Exception thrown: 'System.NotSupportedException' in mscorlib.dll
And I am running this locally using Azure.Functions.Cli\1.0.12
From the error screenshot you provided, The type initializer xxx in TimerPing.TimerPing(static constructor) throw an exception, so you should check the Init() method in it. Hope it helps.

Why Azure function is not writing to Service Bus Topic

My function is like
[FunctionName("MyFunctionName")]
[return: ServiceBus("mytopic", Connection = "ServiceBusConnectionString")]
public static async Task<string> MyFunctionAsync([QueueTrigger("my-input-queue")] string msgIn, TraceWriter log)
{
My local.settings.json has
{
"IsEncrypted": false,
"Values": {
"ServiceBusConnectionString": "[my connection string]"
}
}
where [my connection string] is copy-pasted from a Primary Connecting String under one of the Shared access policies with a Send claim.
This just silently fails: Messages get stuck in my-input-queue and no errors are written to log streaming. However I'm 100% sure the attribute is the issue because I've deployed 100 different combinations of this to try and make it work :).
Any ideas?
Based on my test,it should work with servicebus attribute. The following is my test code.
[return: ServiceBus("topicName",Connection = "ServiceBusConnectionString", EntityType = EntityType.Topic)]
public static async Task<string>Run([QueueTrigger("queueName")]string myQueueItem, TraceWriter log)
{
...
return myQueueItem; // write to the Topic.
}
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "xxxxxx",
"AzureWebJobsDashboard": "xxxxxxxx",
"ServiceBusConnectionString": "xxxxxx"
}
}
You could get more information about Azure Service Bus output binding from this tutorial. You also could do that with follwoing way
[FunctionName("ServiceBusOutput")]
public static void Run([[QueueTrigger("queueName")]string myQueueItem,
TraceWriter log,
[ServiceBus("topicName",Connection = "ServiceBusConnectionString", EntityType = EntityType.Topic)]out string queueMessage)
{
log.Info("Azure Function Demo - Azure Service Bus Queue Topic");
queueMessage = myQueueItem;
}
You are missing the required settings for your QueueTrigger, so your function isn't triggering on new items in the queue. You should have values for AzureWebJobsStorage and AzureWebJobsDashboard, and your QueueTrigger should have a value for the Connection field.
For more information about how to wire up QueueTriggers and test locally, see this answer.

Resources