在 2025 年,Parcel 支持“结构化日志”(JSON 输出),如何将其导入 Loki 并在 Grafana 中查询?请给出 promtail 配置。

解读

面试官想验证三件事:

  1. 你是否真的用过 Parcel 2025 版本的新特性(--log-format=json);
  2. 你是否能把“前端构建日志”当成“可观测性数据”来处理,而不是简单 tail -f;
  3. 你是否熟悉国内落地 Loki 的套路:多租户、中文标签合规、容器/裸机双部署、以及公安部日志留档 180 天的要求。

因此,答案必须体现“前端工具链 + 可观测性后端 + 国内合规”三段式思路,不能只说“把日志扔给 Loki”。

知识点

  1. Parcel 2025 结构化日志字段:timestamp、level、scope、message、buildId、entryPoint、env、duration、errorCode、stack。
  2. Promtail pipeline_stages:json → timestamp → label → pack,避免高基数字段(如 buildId)成为 Loki 索引。
  3. 国内机房常用“裸机 + systemd”与“容器 sidecar”两种部署,promtail 配置需同时给出。
  4. Grafana 查询语法:{job="parcel"} | json | level="error" | line_filter "Cannot resolve" ,配合 UniFi-Alert 做飞书告警。
  5. 合规:日志必须落盘到本地 /logs/parcel/ 目录,promtail 用 decompress-gz 支持 Parcel 自动轮转;labels 中禁止出现用户敏感路径,用 hash 替代。

答案

  1. 开启 Parcel 结构化日志
    parcel build src/index.html --log-format=json --log-file=/logs/parcel/parcel.log

  2. systemd 场景下的 promtail 配置(/etc/promtail/parcel.yaml)

server:
  http_listen_port: 9080
  grpc_listen_port: 0

positions:
  filename: /tmp/positions.yaml

clients:
  - url: http://loki-cluster.internal:3100/loki/api/v1/push
    tenant_id: frontend-team   # 国内多租户隔离

scrape_configs:
  - job_name: parcel
    static_configs:
      - targets: [localhost]
        labels:
          job: parcel
          team: frontend
          env: prod
          __path__: /logs/parcel/parcel.log
    pipeline_stages:
      - json:
          expressions:
            ts: timestamp
            level: level
            scope: scope
            msg: message
            buildId: buildId
            entry: entryPoint
            dur: duration
            err: errorCode
      - timestamp:
          source: ts
          format: RFC3339Nano
      - labels:
          level:
          scope:
          env:        # 从静态标签继承,避免高基数
      - pack:
          pack: true
  1. 容器 sidecar 场景(k8s yaml 片段)
annotations:
  promtail.io/scrape: "true"
  promtail.io/job: "parcel"
  promtail.io/path: "/logs/parcel/*.log"
  promtail.io/pipeline: |
    - json: {...同上...}
  1. Grafana 查询示例
{job="parcel",env="prod"} 
  | json
  | level="error" 
  | line_filter "Cannot resolve"
  | unwrap dur
  1. 合规加固
  • labels 中不出现绝对路径,用 __path__ 原始值,展示层用 Grafana transform 做 hash;
  • 日志文件 100 MB 切割,gzip 保存,promtail 自带 decompress-gz: true;
  • 飞书告警路由:level=error 且 err=ModuleNotFound 时 @前端值班组。

拓展思考

  1. 如果构建集群是弹性容器,如何让 buildId 在 Loki 中做“链路追踪”?
    答:把 buildId 注入到 HTTP 响应头 X-Parcel-Build-Id,前端埋点上报到 Sentry,Sentry 再回写 Loki,实现“构建-运行”全链路打通。

  2. 国内金融客户要求“日志不出机房”,又要用 Grafana Cloud,怎么办?
    答:在本地部署 Loki Simple-Scalable 模式,只把聚合指标(error 率、构建耗时 P99)通过 Grafana-Agent-remote-write 推送到 Grafana Cloud,日志本体留在本地 MinIO-S3,满足“数据不出境”审计。

  3. 当 Parcel 日志量达到 10 TB/月,如何降本?
    答:

    • 使用 Loki 2025 的“结构化流分片”功能,把 scope=optimize 的 TRACE 级日志单独路由到低成本 HDD 存储类;
    • 对重复 stack 做 promtail match: {err: "ModuleNotFound"} 直接采样 1/100;
    • 开启 boltdb-shipper 压缩+week-table,查询慢 200 ms 但存储降 60%。