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

Azure Application Insights中severityLevel如何显示为字符串

问题背景

在Azure Application Insights平台查询日志时,内置severityLevel字段默认返回严重级别对应的数字编码,而非Information、Error这类文本形式的级别标识,需要实现字符串形式的级别展示。
问题示例截图
当前使用的Serilog配置如下:

"Serilog": {
  "Using": [
    "Serilog.Sinks.ApplicationInsights"
  ],
  "MinimumLevel": {
    "Default": "Debug",
    "Override": {
      "Microsoft": "Information"
    }
  },
  "WriteTo": [
    {
      "Name": "ApplicationInsights",
      "Args": {
        "restrictedToMinimumLevel": "Information",
        "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights",
        "instrumentationKey": "key"
      }
    }
  ],
  "Enrich": [
    "FromLogContext"
  ],
  "Properties": {
    "Application": "Sample"
  }
}
实现方案

Azure Application Insights内置的severityLevel是平台固定Schema的数值型枚举字段,不支持直接修改内置字段的存储格式为字符串,可通过以下两种方案实现文本级别的展示需求:

方案1:查询时做数值-文本映射(零改造成本)

severityLevel数值和文本级别的映射关系是固定的:

  • 0 = Verbose
  • 1 = Information
  • 2 = Warning
  • 3 = Error
  • 4 = Critical

在Log Analytics中写KQL查询时,通过case函数动态生成文本格式的级别字段即可,示例查询:

traces
| extend SeverityLevelText = case(
    severityLevel == 0, "Verbose",
    severityLevel == 1, "Information",
    severityLevel == 2, "Warning",
    severityLevel == 3, "Error",
    severityLevel == 4, "Critical",
    "Unknown"
)
| project timestamp, message, SeverityLevelText, customDimensions

可将该查询保存为工作区共享查询,后续直接复用无需重复编写映射逻辑。

方案2:日志写入时追加自定义文本级别字段(一劳永逸)

通过Serilog的Enrich机制,在日志写入环节直接把文本格式的日志级别存入自定义维度,后续查询可直接读取该字段,无需每次做映射。

  1. 实现自定义Enricher,将Serilog日志事件的级别以字符串形式追加到日志属性:
using Serilog.Core;
using Serilog.Events;

public class LogLevelTextEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        logEvent.AddPropertyIfAbsent(
            propertyFactory.CreateProperty("LogLevelText", logEvent.Level.ToString())
        );
    }
}
  1. 在Serilog初始化时注册该Enricher,和原有JSON配置完全兼容:
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration) // 读取现有appsettings中的Serilog配置
    .Enrich.With<LogLevelTextEnricher>() // 注册自定义Enricher
    .CreateLogger();

配置生效后,新写入的日志会在customDimensions节点下自动携带LogLevelText字段,值为Information/Error/Warning这类纯文本,直接查询引用即可。

注意:不要尝试通过自定义TelemetryConverter覆盖内置severityLevel字段的类型,会违反Application Insights的Schema约束,导致日志写入失败、数据识别异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 19:54:15