我正在使用 .net 6 和 ServiceBusTrigger Azure Function 应用程序。我在函数应用程序内部使用 Microsoft.Extensions.Logging.ILogger 将跟踪消息记录到 Application Insights。效果很好。例如
_logger.LogInformation("Hello World")
但我也希望包含一些自定义属性。我试过了
System.Diagnostics.Activity.Current.AddBaggage()
但当前它始终为空。
所以我像这样尝试了 BeginScope,但这也不起作用。
object customProps = new
{
OrderNumber = "something",
TransactionType = transactionType,
};
using (_logger.BeginScope(new Dictionary<string, object> {
["CustomerId"] = 12345)
{
_logger.LogInformation("abc ");
_logger.LogInformation("def {properties}", customProps);
}
然后我尝试在 LogInformation 方法上使用第二个参数,但这也不起作用。
_logger.LogInformation("xyz {properties}", customProps);
消息已记录,只是没有任何自定义属性。
有人有什么想法可以尝试吗?我目前没有使用任何应用程序洞察 nuget 包。只是默认的 ILogger。我也尝试过点网隔离和非隔离。
-兰迪
我已经使用运行时堆栈 dotnet 创建了服务总线队列触发函数。
我已经创建了服务总线队列并从服务总线资源管理器发送了一条消息。
功能代码:
using System;
using System.Collections.Generic;
using Azure.Messaging.ServiceBus;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace FunctionApp8121
{
public class Function1
{
private readonly ILogger<Function1> _logger;
private readonly IConfiguration _config;
private readonly TelemetryClient _telemetryClient;
[Obsolete]
public Function1(ILogger<Function1> logger, IConfiguration config)
{
_logger = logger;
_config = config;
string instrumentationKey = _config["ApplicationInsights:InstrumentationKey"];
_telemetryClient = new TelemetryClient(new TelemetryConfiguration(instrumentationKey));
}
[Function(nameof(Function1))]
[Obsolete]
public void Run([ServiceBusTrigger("firstqueue", Connection = "servicebusconnection")] ServiceBusReceivedMessage message)
{
_logger.LogInformation("Message ID: {id}", message.MessageId);
_logger.LogInformation("Message Body: {body}", message.Body);
_logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
// Log custom events to Application Insights
_telemetryClient.TrackEvent("MessageProcessed", new Dictionary<string, string>
{
{ "MessageID", message.MessageId },
{ "MessageType", message.ContentType },
});
// Log custom properties
var properties = new Dictionary<string, string>
{
{ "FirstName", "pavan" },
{ "LastName", "kumar" },
};
_telemetryClient.TrackTrace("User Details", SeverityLevel.Information, properties);
// Track custom metric
_telemetryClient.TrackMetric("CustomMetric", 42);
// Automatically flush telemetry data to Application Insights (no need for manual Flush)
}
}
}
local.settings.json:
{
"IsEncrypted": false,
"Values": {
"servicebusconnection": "your-servicebus connection string",
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"ApplicationInsights:InstrumentationKey": "your instrumentation key"
}
}
输出:
我在下面的应用程序洞察检查中获取日志:
我能够在应用程序洞察中获取自定义属性。检查以下:
输出: