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

如何通过Serilog+Otlp Collector配置Loki自定义动态标签?

解决方案:将.NET日志动态属性转为Loki标签

方法一:通过Serilog OpenTelemetry Sink配置属性映射

Serilog的OpenTelemetry Sink支持自定义日志属性处理,可将指定参数(如ModuleId)注入到LogRecord的属性集合中,为后续转为Loki标签做准备。

修改你的Serilog OpenTelemetry配置:

configuration.WriteTo.OpenTelemetry(options =>
{
    options.Endpoint = "http://localhost:4317";
    options.ResourceAttributes.Add("service.name", "MyAppName");
    // 配置将目标日志属性转为LogRecord Attributes
    options.ConfigureLogEvent = (logEvent, export) =>
    {
        foreach (var property in logEvent.Properties)
        {
            // 筛选需要转为标签的属性,此处以ModuleId为例
            if (property.Key.Equals("ModuleId", StringComparison.OrdinalIgnoreCase))
            {
                export.Attributes[property.Key] = property.Value.ToString().Trim('"');
            }
        }
    };
});

方法二:通过OpenTelemetry Collector将属性转为Loki标签

Loki的OTLP exporter会把资源属性和标记为标签的LogRecord属性作为日志标签。需添加transform处理器,将指定的LogRecord属性映射为Loki标签。

1. 更新otel-collector.yaml,添加transform处理器

processors:
  batch:
    timeout: 3s
    send_batch_size: 1000
  # 新增transform处理器,处理日志属性转标签逻辑
  transform:
    logs:
      queries:
        # 将LogRecord中的ModuleId属性转为Loki标签
        - context: log_record
          expressions:
            labels["ModuleId"] = attributes["ModuleId"]
        # 如需批量转换多个属性,可追加表达式
        # - context: log_record
        #   expressions:
        #     labels["UserId"] = attributes["UserId"]

2. 将transform处理器加入日志管道

修改service.pipelines.logs节点:

service:
  extensions: [health_check]
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch]
      exporters: [otlp/tempo]
    metrics:
      receivers: [otlp]
      processors: [batch]
      exporters: [prometheus]
    logs:
      receivers: [otlp]
      processors: [batch, transform]  # 引入transform处理器
      exporters: [otlphttp/loki]

验证步骤

  1. 重启.NET应用与OpenTelemetry Collector
  2. 触发含ModuleId的日志,例如执行:logger.LogInformation("Some message for {ModuleId}", "PaymentModule")
  3. 在Grafana查询Loki日志,可看到带ModuleId="PaymentModule"标签的日志条目

注意事项

  • 若需批量匹配属性(如所有以Module开头的属性),可使用正则表达式:labels[k] = attributes[k] where k matches "^Module.*"
  • 确保Loki配置中limits_config.allow_structured_metadata已设为true(当前配置已满足),否则无法接收结构化属性作为标签

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:07:33