I am trying to use the standard ILogger and make it log to Azure. First I added following to host file:
{
"version": "2.0",
"Logging": {
"ApplicationInsights": {
"LogLevel": {
"Default": "Trace",
"System": "None",
"Microsoft": "None"
}
}
},
"ApplicationInsights": {
"Instrumentationkey": "xx-xx-xx-xx-xx"
}
}
And this is my function:
namespace Jobs
{
public static class ExchangeRates
{
[FunctionName("ExchangeRates")]
public static void Run([TimerTrigger("0 0 0 * * *", RunOnStartup =true)]TimerInfo myTimer, ILogger log)
{
string lol1 = "lol1 text";
string lol2 = "lol2 text";
log.LogWarning("adsad");
log.LogDebug("LogDebug", "asdasd", lol2);
log.LogTrace("LogTrace {lol1}, {lol2}", lol1, lol2);
log.LogInformation("LogInfo {lol1}, {lol2}", lol1, lol2);
log.LogError("LogError");
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
}
}
But no logging are added. I also tried installing nuget package:
Microsoft.Extensions.Logging.ApplicationInsights
Am I missing something - what does it take to make an function app writing to Application Insights?
I think you're running the azure function locally with application insights, right?
If yes, actually it's not recommended since application insights is integrated with azure function in azure portal.
But for testing only, you can just add this line of setting "APPINSIGHTS_INSTRUMENTATIONKEY": "the key" in local.settings.json(remember to set it as "copy if newer"). The sample settings in local.settings.json looks like below:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "xxxxxx",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"APPINSIGHTS_INSTRUMENTATIONKEY": "the key"
}
}
By the way, I also installed the nuget package Microsoft.Extensions.Logging.ApplicationInsights in my test.
Related
I have a service bus trigger function where I want to load the topic name from config
I have seen this post and I have tried the same approach Previous Question
public async Task MyFunctionAsync(
[ServiceBusTrigger("%TopicName%", "data-subscription", Connection = "event-bus-connection")]
string mySbMsg)
{
}
In my localsettings.json file I have
"bindings": [
{
"%TopicName%": "topic"
}
]
"bindings": [
{
"%TopicName%": "rockit-notification-topic"
}
]
This doesnt work
Microsoft.Azure.WebJobs.Host: Error indexing method 'MyFunction'. Microsoft.Azure.WebJobs.Host: '%TopicName%' does not resolve to a value.
Also, even if this did work, how do I add this to the settings of the function within the portal as this is an item in an array?
You shouldn't add the "bindings" section to you localsettings file.
localsettings.json should look something like that:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"event-bus-connection": "test",
"TopicName":"topic",
"SubsriptionName":"data-subscription"
}
}
On Azure Portal you can directly add it to App Service/Function Configuration like properies with name TopicName, SubsriptionName etc.
I took care of all the settings described here Azure WebJobs SDK ServiceBus connection string 'AzureWebJobsAzureSBConnection' is missing or empty
Here is my local.settings.json looks like
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
},
"ConnectionStrings": {
"AzureWebJobsAzureSBConnection": "Endpoint=sb://host.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xx"
}
}
Still I get this error.
Here is the function looks like
public static class Function1
{
[FunctionName("ServiceBusQueueTriggerCSharp")]
public static void Run(
[ServiceBusTrigger("queue", Connection = "Endpoint=sb://host.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxxx")]
ILogger log)
{
log.LogInformation($"C# ServiceBus queue trigger function processed message:");
}
}
A host error has occurred during startup operation '952d758d-8e6c-4159-bc78-ee315de1b93a'.
[2021-08-25T12:41:13.453Z] Microsoft.Azure.WebJobs.ServiceBus: Microsoft Azure WebJobs SDK ServiceBus connection string 'Endpoint=sb://host.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;[Hidden Credential]' is missing or empty.
Value cannot be null. (Parameter 'provider')
Thank you Melissa. Posting your suggestion as an answer to help community members.
You can update local.settings.json and place AzureWebJobsServiceBus inside the Values element.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsServiceBus": "Endpoint=sb://host.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xx",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
I am trying to setup a timerTrigger azure function
My function.json:
{
"disabled": false,
"bindings": [
{
"type": "timerTrigger",
"direction": "in",
"name": "sampleCronTrigger",
"schedule": "*/5 * * * * *",
}
],
"entryPoint": "sampleCron",
"scriptFile": "index.js"
}
In this I need to set an environment variable, but I am not able to do so. I tried looking for some documentation but couldn't find anything which doesn't require some setup on the Azure console?
I can I define environment variables? Or If here is any way I can pass an input to the function, that works too.
App settings in a function app contain global configuration options that affect all functions for that function app. When you run locally, these settings are accessed as local environment variables.
Local settings file
The file local.settings.json stores app settings, connection strings, and settings for Azure Functions Core Tools. Settings in the local.settings.json file are only used by Functions tools when running locally. By default, these settings are not migrated automatically when the project is published to Azure. Use the --publish-local-settings switch when you publish to make sure these settings are added to the function app in Azure.
In Functions, app settings, such as service connection strings, are exposed as environment variables during execution. You can access these settings using process.env, as shown here in the GetEnvironmentVariable function:
module.exports = function (context, myTimer) {
var timeStamp = new Date().toISOString();
context.log('Node.js timer trigger function ran!', timeStamp);
context.log(GetEnvironmentVariable("AzureWebJobsStorage"));
context.log(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
context.done();
};
function GetEnvironmentVariable(name)
{
return name + ": " + process.env[name];
}
There are several ways that you can add, update, and delete function app settings:
From Azure portal.
By using the Azure CLI.
When running locally, app settings are read from the local.settings.json project file.
References:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings
https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node#environment-variables
https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node#environment-variables
Additionally for retrieving values from local.settings.json, another way is to create an IConfigurationRoot object using ExecutionContext executionContext.
ExecutionContext can be added to function definition:
[FunctionName("FunctionName")]
public static async Task Run(
[ServiceBusTrigger(...)]
SomeMessage msg,
ILogger log,
ExecutionContext executionContext)
{
}
After that, you can instantiate an IConfigurationRoot instance, which you instruct to optionally load local.appsettings.json.
var configurationRoot = new ConfigurationBuilder()
.SetBasePath(executionContext.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
With the configurationRoot object, you can retrieve configuration values:
var value = configurationRoot["SomeKey"];
Example local.settings.json:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "...",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"SomeKey": "Value",
},
"Host": {
"LocalHttpPort": "7071"
}
}
I have below code to catch all the messages arrives at IoT Hub
[FunctionName("device-message--funcapp-v2")]
public static void Run([IoTHubTrigger("testhub",
Connection = "IoTHubEventEndPoint",
ConsumerGroup = "ActualConsumerGroup")]EventData message,
ILogger log)
{
log.LogInformation($"C# IoT Hub trigger:
{Encoding.UTF8.GetString(message.Body.Array)}");
}
This works fine as expected, but now I do not want to hard code the ConsumerGroup. So I added below configuraiton entry in local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"EventHub": "",
"CosmosDb": "",
"ConfigurationConsumerGroup": "ActualConsumerGroup"
}
}
and changed code as below
[FunctionName("device-message--funcapp-v2")]
public static void Run([IoTHubTrigger("testhub",
Connection = "IoTHubEventEndPoint",
ConsumerGroup = "ConfigurationConsumerGroup")]EventData message,
ILogger log)
But it fails.
[1/18/2019 9:47:11 AM] Microsoft.Azure.EventHubs: The messaging entity 'iothub-ns-testhub-945897-3a6f492cc4:eventhub:lctesthub~8191|ConfigurationConsumerGroup' could not be found.
Use ConsumerGroup = "%ConfigurationConsumerGroup%" to read settings from local.settings.json. Check the doc. Note that the connection property of triggers and bindings is a special case and automatically resolves values as app settings, without percent signs.
I've downloaded VS2017 Community Edition to try out Azure functions and I can't get it to work. I've searched many post on Stackoverflow and Azure functions Github pages but nowhere there seems to be a complete documentation about anything.
Here's what I have:
Azure function:
namespace FunctionApp1
{
public static class Function1
{
[FunctionName("Function1")]
public static void Run([ServiceBusTrigger("ngctestqueue", AccessRights.Manage, Connection = "Endpoint=sb://ngcservicebus.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SERVICE_BUS_KEY")]string myQueueItem, TraceWriter log)
{
log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
}
}
}
host.json
{
"disabled": false,
"bindings": [
{
"name": "myQueueItem",
"type": "serviceBusTrigger",
"direction": "in",
"queueName": "ngctestqueue",
"connection": "connection",
"accessRights": "manage"
}
]
}
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=ngctest2;AccountKey=STORAGE_ACCOUNT_KEY;EndpointSuffix=core.windows.net",
"AzureWebJobsDashboard": "DefaultEndpointsProtocol=https;AccountName=ngctest2;AccountKey=STORAGE_ACCOUNT_KEY;EndpointSuffix=core.windows.net",
"AzureWebJobsServiceBus": "Endpoint=sb://ngcservicebus.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SERVICE_BUS_KEY",
"connection": "Endpoint=sb://ngcservicebus.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SERVICE_BUS_KEY"
}
}
When I run the function via F5 locally, I get the following error:
Microsoft.Azure.WebJobs.Host: Error indexing method 'Func
tion1.Run'. Microsoft.Azure.WebJobs.ServiceBus: Microsoft Azure WebJobs SDK Serv
iceBus connection string 'AzureWebJobsEndpoint=sb://ngcservicebus.servicebus.win
dows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SERVICE_BUS_KEY' is missing or empty.
My dev environment is as follows:
1) Windows 8.1 Pro
2) VS2017 Community 15.3.5
3) Azure Functions CLI 1.0.4
Any help would really be appreciated.
Thank you.
Connection property should be set to connection string name, not the value itself. The value will then be read from the config.
[ServiceBusTrigger("ngctestqueue", AccessRights.Manage, Connection = "AzureWebJobsServiceBus")]
You don't need to create host.json in local environment (it will be auto-generated by SDK).