.NET Core 2.2中如何捕获SignalR日志并转发至Azure Insights
解决.NET Core 2.2 SignalR日志转发到Azure Insights的问题
我之前也碰到过类似的困扰,默认配置确实不会自动把SignalR的日志同步到Application Insights,咱们可以通过调整.NET Core的日志配置来搞定这件事,具体步骤如下:
1. 安装必要的NuGet包
首先确保你的后端项目已经安装了Microsoft.ApplicationInsights.AspNetCore包,版本要和.NET Core 2.2兼容(建议选2.14.x系列的稳定版本,避免兼容性问题)。
2. 配置日志框架,关联SignalR与Application Insights
在Program.cs的CreateWebHostBuilder方法里,我们需要明确配置日志过滤器,打开SignalR相关的日志级别,同时绑定Application Insights:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureLogging((hostingContext, logging) => { // 绑定Application Insights的 instrumentation key var instrumentationKey = hostingContext.Configuration["ApplicationInsights:InstrumentationKey"]; logging.AddApplicationInsights(instrumentationKey); // 开启SignalR和连接相关的日志,级别可按需调整(Debug/Information/Warning) logging.AddFilter("Microsoft.AspNetCore.SignalR", LogLevel.Information); logging.AddFilter("Microsoft.AspNetCore.Http.Connections", LogLevel.Information); // 保留默认的日志输出渠道(比如控制台、调试窗口) logging.AddConsole(); logging.AddDebug(); }) .UseApplicationInsights();
同时在appsettings.json里配置好Application Insights的密钥:
{ "ApplicationInsights": { "InstrumentationKey": "你的Azure Insights密钥" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } } }
3. 在Azure Insights中查询SignalR日志
配置完成后重启后端服务,之后就能在Azure Portal的Application Insights里查询SignalR日志了。打开Insights的日志页面,用Kusto语句过滤:
traces | where message contains "SignalR" or message contains "Http.Connections" | order by timestamp desc
你会看到SignalR的连接建立、消息收发、断开等日志都被捕获进来,和其他遥测数据统一管理。
额外提示
- 如果需要在自定义Hub里记录业务日志,可以直接注入
ILogger<YourHub>,这些日志也会自动转发到Application Insights:public class ChatHub : Hub { private readonly ILogger<ChatHub> _logger; public ChatHub(ILogger<ChatHub> logger) { _logger = logger; } public async Task SendMessage(string user, string message) { _logger.LogInformation($"User {user} sent message: {message}"); await Clients.All.SendAsync("ReceiveMessage", user, message); } } - 之前你尝试的文件系统日志没找到有效内容,大概率是因为默认文件日志提供者只捕获Microsoft前缀的Warning及以上级别日志,而我们通过
AddFilter明确指定了SignalR的日志级别后,就能让Application Insights正常捕获这些日志了。
内容的提问来源于stack exchange,提问作者A Horse From Belgrade
相关产品推荐
相关产品推荐

