菜单
开源

json

注意

Promtail 已被弃用,并通过长期支持 (LTS) 持续到 2026 年 2 月 28 日。Promtail 将于 2026 年 3 月 2 日达到生命周期结束 (EOL)。您可以在此处找到迁移资源。

json 阶段是一个解析阶段,它将日志行读取为 JSON,并接受 JMESPath 表达式来提取数据。

模式

yaml
json:
  # Set of key/value pairs of JMESPath expressions. The key will be
  # the key in the extracted data while the expression will be the value,
  # evaluated as a JMESPath from the source data.
  #
  # Literal JMESPath expressions can be done by wrapping a key in
  # double quotes, which then must be wrapped in single quotes in
  # YAML so they get passed to the JMESPath parser.
  expressions:
    [ <string>: <string> ... ]

  # Name from extracted data to parse. If empty, uses the log message.
  [source: <string>]

  # When true, then any lines that cannot be successfully parsed as valid JSON objects
  # will be dropped instead of being sent to Loki.
  [drop_malformed: <bool> | default = false]

此阶段使用 Go JSON unmarshaller,这意味着数字或布尔值等非字符串类型将被解组为这些类型。提取的数据可以包含非字符串值,并且此阶段不执行任何类型转换;下游阶段需要根据需要对这些值执行正确的类型转换。有关如何执行此操作,请参阅template 阶段

如果提取的值是复杂类型,例如数组或 JSON 对象,则在插入提取数据之前会将其转换回 JSON 字符串。

示例

使用日志行

对于给定的流水线

yaml
- json:
    expressions:
      output: log
      stream: stream
      timestamp: time

给定以下日志行

{"log":"log message\n","stream":"stderr","time":"2019-04-30T02:12:41.8443515Z"}

将在提取数据集中创建以下键值对

  • output: log message\n
  • stream: stderr
  • timestamp: 2019-04-30T02:12:41.8443515

使用提取的数据

对于给定的流水线

yaml
- json:
    expressions:
      output:    log
      stream:    stream
      timestamp: time
      extra:
- json:
    expressions:
      user:
    source: extra

以及给定的日志行

{"log":"log message\n","stream":"stderr","time":"2019-04-30T02:12:41.8443515Z","extra":"{\"user\":\"marco\"}"}

第一阶段将在提取数据集中创建以下键值对

  • output: log message\n
  • stream: stderr
  • timestamp: 2019-04-30T02:12:41.8443515
  • extra: {"user": "marco"}

第二阶段将从提取数据中解析 extra 的值作为 JSON,并将以下键值对附加到提取数据集中

  • user: marco

使用 JMESPath 字面量

此流水线使用 JMESPath 字面量表达式来解析名称中带有特殊字符(例如 @.)的 JSON 字段。

对于给定的流水线

yaml
- json:
    expressions:
      output: log
      stream: '"grpc.stream"'
      timestamp: time

给定以下日志行

{"log":"log message\n","grpc.stream":"stderr","time":"2019-04-30T02:12:41.8443515Z"}

将在提取数据集中创建以下键值对

  • output: log message\n
  • stream: stderr
  • timestamp: 2019-04-30T02:12:41.8443515

注意

如果不将 grpc.stream 用双引号括起来再用单引号包围,引用将无法正常工作。