loki

Loki 日志查询代理技能,用于查询与分析日志以支持故障排查和运行监控。

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "loki":https://skillpi.com/zh/skills/deepskill-600c8728db464493ddf42e41258ca16687f9dc08e43f89809060869f19c9a7bf。安装前核对上游来源和版本:https://skillhub.cn/skills/user_3c6cb52e/loki-log-query-agent。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

skillhub.cn

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

Loki 日志查询代理技能,用于查询与分析日志以支持故障排查和运行监控。

0 下载

介绍来源: third_party · user_3c6cb52e · 3.8 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: loki
description: >
  Loki is a horizontally scalable log aggregation system built by Grafana Labs. Unlike traditional log
  platforms that index the full text of every log line, Loki indexes only metadata labels, making it
  significantly cheaper to operate. It integrates natively with Grafana for querying and visualization,
  and uses LogQL — a query language inspired by PromQL — to filter, parse, and aggregate log streams.
license: Apache-2.0
compatibility: 'linux, macos, windows'
metadata:
  author: terminal-skills
  version: 1.0.0
  category: data-ai
  tags:
    - logging
    - observability
    - log-aggregation
    - grafana
    - logql

Loki

Loki is a log aggregation system designed to be cost-effective and easy to operate. It takes a fundamentally different approach from Elasticsearch or Splunk: instead of indexing log content, it indexes only the labels attached to log streams. The actual log lines are compressed and stored in chunks. This means writes are fast, storage is cheap, and you still get powerful querying through LogQL.

This skill covers deploying Loki and Promtail with Docker, writing LogQL queries, and integrating Loki with Grafana for log exploration and alerting.

Docker Deployment

A typical Loki setup has two components: the Loki server that stores and queries logs, and Promtail, an agent that ships logs from your hosts into Loki.

# docker-compose.yml — Loki and Promtail deployment
# Loki on port 3100, Promtail tails container logs via Docker socket

version: "3.8"

services:
  loki:
    image: grafana/loki:latest
    ports:
      - "3100:3100"
    volumes:
      - ./loki-config.yml:/etc/loki/local-config.yaml
      - loki-data:/loki
    command: -config.file=/etc/loki/local-config.yaml

  promtail:
    image: grafana/promtail:latest
    volumes:
      - ./promtail-config.yml:/etc/promtail/config.yml
      - /var/log:/var/log:ro
      - /var/run/docker.sock:/var/run/docker.sock:ro
    command: -config.file=/etc/promtail/config.yml
    depends_on:
      - loki

volumes:
  loki-data:

Loki Configuration

# loki-config.yml — minimal Loki server configuration
# Single-instance mode with filesystem storage and 30-day retention

auth_enabled: false

server:
  http_listen_port: 3100

common:
  ring:
    instance_addr: 127.0.0.1
    kvstore:
      store: inmemory
  replication_factor: 1
  path_prefix: /loki

schema_config:
  configs:
    - from: "2024-01-01"
      store: tsdb
      object_store: filesystem
      schema: v13
      index:
        prefix: index_
        period: 24h

storage_config:
  filesystem:
    directory: /loki/chunks

limits_config:
  retention_period: 720h
  max_query_series: 5000

compactor:
  working_directory: /loki/compactor
  retention_enabled: true

Promtail Agent

Promtail discovers log targets, attaches labels, and pushes log entries to Loki. It can tail files, scrape journal entries, and read Docker container logs.

# promtail-config.yml — Promtail agent configuration
# Scrapes Docker container logs and labels them with container name and compose service

server:
  http_listen_port: 9080

positions:
  filename: /tmp/positions.yaml

clients:
  - url: http://loki:3100/loki/api/v1/push

scrape_configs:
  - job_name: docker
    docker_sd_configs:
      - host: unix:///var/run/docker.sock
        refresh_interval: 5s
    relabel_configs:
      - source_labels: ['__meta_docker_container_name']
        target_label: container
        regex: '/(.+)'
      - source_labels: ['__meta_docker_container_label_com_docker_compose_service']
        target_label: service

  - job_name: system
    static_configs:
      - targets: [localhost]
        labels:
          job: syslog
          host: production-1
          __path__: /var/log/syslog

Structured Metadata with Pipeline Stages

Promtail can parse log lines and extract labels or structured metadata using pipeline stages:

# promtail-pipeline.yml — pipeline stages for JSON log parsing
# Extracts level, method, and status from JSON application logs

scrape_configs:
  - job_name: app
    static_configs:
      - targets: [localhost]
        labels:
          job: myapp
          __path__: /var/log/myapp/*.log
    pipeline_stages:
      - json:
          expressions:
            level: level
            method: method
            status: status
            duration: duration_ms
      - labels:
          level:
      - timestamp:
          source: timestamp
          format: RFC3339

LogQL Queries

LogQL is Loki's query language. It starts with a log stream selector (labels in curly braces) and optionally chains filter expressions and aggregations.

Stream Selection and Filtering

# LogQL — all logs from the API service
{service="api"}
# LogQL — API errors containing "timeout"
{service="api"} |= "timeout" | logfmt | level="error"
# LogQL — filter with regex, exclude health checks
{service="api"} |~ "POST|PUT" !~ "/healthz"

Parsing and Extracting Fields

# LogQL — parse JSON logs and filter by HTTP status
{service="api"} | json | status >= 500
# LogQL — parse logfmt and extract specific fields
{job="myapp"} | logfmt | duration > 1000 | line_format "slow request: {{.method}} {{.path}} took {{.duration}}ms"

Metric Queries

LogQL can compute metrics from logs, turning log data into time-series:

# LogQL — error rate per service over 5-minute windows
sum by (service) (rate({job="myapp"} |= "error" [5m]))
# LogQL — 99th percentile request duration from parsed logs
quantile_over_time(0.99, {service="api"} | json | unwrap duration_ms [5m]) by (method)
# LogQL — top 5 noisiest log sources by volume
topk(5, sum by (service) (rate({job=~".+"} [1h])))

Grafana Integration

Loki is a first-class data source in Grafana. Adding it lets you view logs alongside metrics on the same dashboard, which is essential for correlating issues.

Provisioning Loki as a Data Source

# provisioning/datasources/loki.yml — Loki data source for Grafana
apiVersion: 1

datasources:
  - name: Loki
    type: loki
    access: proxy
    url: http://loki:3100
    jsonData:
      maxLines: 1000
      derivedFields:
        - name: TraceID
          matcherRegex: '"trace_id":"(\w+)"'
          url: 'http://tempo:3200/api/traces/${__value.raw}'
          datasourceUid: tempo

The derivedFields configuration extracts trace IDs from log lines and creates clickable links to a tracing backend, connecting logs to traces with zero effort.

Log Panel in a Dashboard

{
  "__comment": "dashboard-panel.json — Grafana log panel showing API errors",
  "type": "logs",
  "title": "API Errors",
  "gridPos": { "h": 10, "w": 24, "x": 0, "y": 0 },
  "datasource": { "type": "loki", "uid": "loki" },
  "targets": [
    {
      "expr": "{service=\"api\"} | json | level=\"error\"",
      "refId": "A"
    }
  ],
  "options": {
    "showTime": true,
    "showLabels": true,
    "wrapLogMessage": true,
    "sortOrder": "Descending",
    "enableLogDetails": true
  }
}

Log-Based Alerts

You can create Grafana alert rules that fire when log patterns exceed a threshold:

# provisioning/alerting/log-alerts.yml — alert on high error log volume
apiVersion: 1

groups:
  - orgId: 1
    name: log-alerts
    folder: Logs
    interval: 60s
    rules:
      - uid: high-error-logs
        title: High Error Log Volume
        condition: A
        data:
          - refId: A
            datasourceUid: loki
            model:
              expr: 'sum(rate({service="api"} |= "error" [5m]))'
              conditions:
                - evaluator:
                    type: gt
                    params: [10]
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Error log rate exceeds 10/s for the API service"

Loki works best when you keep label cardinality low. Use labels for broad categories like service, environment, and host — not for high-cardinality values like user IDs or request IDs. Those belong in the log line itself, where LogQL can parse them on demand.

当前收录版本

3.8

核对来源版本 ↗

安全与评测信息

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值95/100

亮点

  • 提供完整的 Loki 日志聚合系统部署与查询解决方案
  • 涵盖 Docker 部署、Promtail 配置、LogQL 查询语法和 Grafana 集成
  • 适用于运维、开发和可观测性场景,实用价值高
触发精准95/100

亮点

  • 触发词精准完整,详细描述了 Loki 的核心特性和适用场景
  • 覆盖多种变体,边界清晰,易于用户理解和使用
结构规范95/100

亮点

  • Phase/步骤清晰,包含部署、配置、查询和集成等完整流程
  • 有端到端示例,frontmatter 完整,单文件未超限
执行可靠95/100

亮点

  • 工具来源明确,参数正确,覆盖了主要异常处理
  • 不可逆操作有确认机制,整体执行可靠性高
证据可验 (前四项均值)95/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • loki
  • tempo

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。