You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在控制台获取Microsoft.Azure.Devices包的Azure SDK日志?

解决Microsoft.Azure.Devices ServiceClient日志不输出到控制台的问题

问题核心在于:Microsoft.Azure.Devices属于旧版Azure SDK,并未基于Azure.Core构建,因此不支持AzureEventSourceListener(这是新版Azure SDK的日志方案)。它采用传统的System.Diagnostics.TraceSource机制输出日志,需要单独配置。

解决方案步骤:

  1. 添加控制台TraceListener,捕获ServiceClient的日志输出
  2. 配置日志级别,控制输出的详细程度

修改后的完整代码示例:

using System.Diagnostics;
using System.Text;
using Azure.Core.Diagnostics;
using Azure.Storage.Blobs;
using Microsoft.Azure.Devices;

// 配置新版Azure SDK(如Storage Blobs)的日志
using AzureEventSourceListener consoleListener = AzureEventSourceListener.CreateConsoleLogger(System.Diagnostics.Tracing.EventLevel.Verbose);

// 配置Microsoft.Azure.Devices的TraceSource日志
var sourceSwitch = new SourceSwitch("Microsoft-Azure-Devices", "Verbose");
var consoleTraceListener = new ConsoleTraceListener();
TraceSource azureIotTraceSource = new TraceSource("Microsoft-Azure-Devices");
azureIotTraceSource.Switch = sourceSwitch;
azureIotTraceSource.Listeners.Add(consoleTraceListener);

// Blob操作(日志正常输出)
var x = new BlobClient(new Uri("BLOB URL")).Download();

// IoT Hub ServiceClient操作(现在会输出日志)
ServiceClient _serviceClient = ServiceClient.CreateFromConnectionString("CONN STRING");
string msg = "Hi Qwerty";
Message message = new Message(Encoding.ASCII.GetBytes(msg));
await _serviceClient.SendAsync("DEVICE ID", message);

关键说明:

  • SourceSwitch的第二个参数设置日志级别,可选值包括Verbose、Information、Warning、Error等,按需调整
  • TraceSource的名称固定为Microsoft-Azure-Devices,这是该库内置的TraceSource名称
  • 若要自定义日志格式,可以继承TraceListener实现自己的输出逻辑

内容的提问来源于stack exchange,提问作者Pramod Shivaprasad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 10:42:43