我创建了一个示例 .NET 6 控制台应用程序,并添加了以下 Microsoft learn 网站中提到的以下代码行,以启用 azure sdk 客户端库日志。
using AzureEventSourceListener consoleListener =
AzureEventSourceListener.CreateConsoleLogger(System.Diagnostics.Tracing.EventLevel.Verbose);
在示例应用程序中,我使用 BlobClient 下载 Blob,该 BlobClient 在“Azure.Storage.Blobs”nuget 包中定义。 我还使用 ServiceClient 发送云到设备消息,该消息在“Microsoft.Azure.Devices”nuget 包中定义。
对于 blob 客户端操作,我可以在控制台中获取 sdk 日志,但对于使用“ServiceClient”的云到设备消息操作,我无法获取 sdk 日志。
服务客户端操作的类似日志未记录
您能帮我在控制台中获取“Microsoft.Azure.Devices”库的 sdk 日志吗
这是我的代码
using AzureEventSourceListener consoleListener = AzureEventSourceListener.CreateConsoleLogger(System.Diagnostics.Tracing.EventLevel.Verbose);
var x = new BlobClient(new Uri("BLOB URL")).Download();
ServiceClient _serviceClient = ServiceClient.CreateFromConnectionString("CONN STRING");
string msg = "Hi Qwerty";
Message message = new Message(Encoding.ASCII.GetBytes(msg));
await _serviceClient.SendAsync("DEVICE ID", message);
Microsoft.Extensions.Logging.Console
Microsoft.Extensions.Logging
AzureEventSourceListener consoleListener = AzureEventSourceListener.CreateConsoleLogger(System.Diagnostics.Tracing.EventLevel.Verbose);
// Set up logger
var serviceProvider = new ServiceCollection()
.AddLogging(builder =>
{
builder.AddConsole();
})
.BuildServiceProvider();
var logger = serviceProvider.GetService<ILogger<Program>>();
try
{
// Download a blob
BlobClient blobClient = new BlobClient(new Uri("https://samstoragehello.blob.core.windows.net/hellocont/_ViewImports.cshtml?sp"));
BlobDownloadInfo downloadedContent = await blobClient.DownloadAsync();
// Read the downloaded content
using (var streamReader = new StreamReader(downloadedContent.Content))
{
string downloadedContentString = await streamReader.ReadToEndAsync();
// Send a message to an IoT device
ServiceClient _serviceClient = ServiceClient.CreateFromConnectionString("HostName=samiothubtodel1.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=");
string msg = "Hi Qwerty";
Microsoft.Azure.Devices.Message message = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(msg));
await _serviceClient.SendAsync("mywebpi", message);
// Log information including blob content and IoT message content
logger.LogInformation("Blob downloaded successfully. Content: {BlobContent}", downloadedContentString);
logger.LogInformation("IoT message sent. Content: {IoTMessageContent}", msg);
}
}
catch (Exception ex)
{
// Log error
logger.LogError(ex, "An error occurred: {ErrorMessage}", ex.Message);
}
输出:
Microsoft.Azure.Devices.Client
MSDOC DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Mqtt);
deviceClient.SetConnectionStatusChangesHandler((status, reason) =>
{
logger.LogInformation($"Connection Status Changed - Status: {status}, Reason: {reason}");
});
await deviceClient.OpenAsync();