流畅位到 Loki - “日志”字段未被解析/过滤

问题描述

我有

  1. 一个简单的 Python 应用(“iss-web”)将 JSON 日志输出写入标准输出
  2. Python 应用(“iss-web”)位于 Docker 容器中
  3. Python 应用程序(“iss-web”)容器日志记录驱动程序设置为“fluentd”
  4. 运行“fluent/fluent-bit:1.7”的单独容器,用于收集 Python 应用 JSON 日志输出
  5. Loki 2.2.1 通过容器部署以接收来自 fluent-bit 的 Python 应用日志输出
  6. Grafana 连接到 Loki 以可视化日志数据

问题是“日志”字段没有被 fluent-bit 过滤/解析,因此在 Loki/Grafana 中,“日志”字段的内容没有被解析并用作“检测到的字段”。

"iss-web" docker-compose.yml

version: '3'
services:
    iss-web:
        build: ./iss-web
        image: iss-web
        container_name: iss-web
        env_file:
            - ./iss-web/app.env
        ports:
            - 46664:46664
        logging:
            driver: fluentd
            options:
                tag: iss.web
    redis:
        image: redis
        container_name: redis
        ports:
            - 6379:6379
        logging:
            driver: "json-file"
            options:
                max-file: ${LOG_EXPIRE}
                max-size: ${LOG_SEGMENT}

“流畅位”docker-compose.yml

version: '3'
services:
  fluent-bit:
    image: fluent/fluent-bit:1.7
    container_name: fluent-bit
    environment:
      - LOKI_URL=http://135.86.186.75:3100/loki/api/v1/push
    user: root
    volumes:
      - ./fluent-bit.conf:/fluent-bit/etc/fluent-bit.conf
      - ./parsers.conf:/fluent-bit/etc/parsers.conf
    ports:
      - "24224:24224"
      - "24224:24224/udp"

fluent-bit.conf

[SERVICE]
    Flush 1
    Daemon Off
    log_level debug
    Parsers_File /fluent-bit/etc/parsers.conf

[INPUT]
    Name forward
    Listen 0.0.0.0
    port 24224

[FILTER]
    Name parser
    Match iss.web
    Key_Name log
    Parser docker
    Reserve_Data On
    Preserve_Key On

[OUTPUT]
    Name loki
    Match *
    host 135.86.186.75
    port 3100
    labels job=fluentbit

[OUTPUT]
    Name stdout
    Match *

parsers.conf

我尝试过使用/不使用 Time_Key、Time_Format、Time_Keep

[PARSER]
    Name         docker
    Format       json
    #Time_Key     time
    #Time_Format  %Y-%m-%dT%H:%M:%s.%L
    #Time_Keep    On
    # Command      |  Decoder | Field | Optional Action
    # =============|==================|=================
    #Decode_Field_As   escaped_utf8    log    do_next
    Decode_Field_As   json       log

流畅的日志提取

[0] iss.web: [1620640820.000000000,{"log"=>"{'timestamp': '2021:05:10 11:00:20.439513','epoch': 1620640820:8,19,568.4' 'level': 'DEBUG','message': '/ping','data': {'message': 'PONG','timestamp': '1620640820.4394963','version': '0.1'}}"," container_id"=>"bffd720e9ac1e8c3992c1120eed37e00c536cd44ec99e9c13cf690d840363f80","container_name"=>"/iss-web","source"=>"stdout"}]

Grafana/Loki 屏幕

我希望“检测到的字段”包含 pid=1、message=/ping 等

enter image description here

解决方法

我的“记录器”中需要一个“json.dumps”:

def log(message,level="INFO",**extra):
    out = {"timestamp": get_now(),"epoch": get_epoch(),"pid": get_pid(),"level": level,"message": message}
    if extra: out |= extra
    print(json.dumps(out),flush=True)
    return True