↓ 跳过正文
  1. 博客/
  2. Grafana/

用 Loki 存储日志数据

··3634 字·18 分钟·
小钰大主宰
作者
小钰大主宰
建站工程师
目录
Grafana - 这篇文章属于一个选集。
§ 4: 本文

本文将使用 Proxmox 集群上两个运行 Debian GNU/Linux 的 LXC,把 Loki 服务器装好并配置成接收、存储日志数据。

  1. loki1.localdomain.com 在 8080 端口运行 Loki 服务器。
  2. nginx1.localdomain.com 在 443 端口运行 NGINX 作反向代理,对外地址是 loki.publicdomain.com。

本系列假定已安装并正确配置了内部 DNS 服务器。localdomain.com 是集群内部使用的 DNS 区域,publicdomain.com 是用于从互联网访问服务的公网 DNS 区域。

Loki 服务器会收集由 Promtail agent 发来的日志数据——这些 agent 运行在你想采集日志的宿主机或 guest 里。因此 Promtail 需要单独配置。

Promtail agent 在它们监视的日志文件里收集到新条目时,会连接该地址和端口;随后 Loki 把数据存进本地磁盘上的时序数据库,位置在 /var/lib/loki/。

它是怎么工作的
#

Loki 从各种来源(本例中是 Promtail)摄入日志,以标签的形式附加元数据,并存进时序数据库(TSDB)。查询日志时使用 LogQL——一种类似 Prometheus 所用 PromQL 的查询语言。Loki 针对高写入吞吐和高效存储做了优化。

执行查询时:

  1. Loki 用元数据标签识别相关的日志流。
  2. 检索并过滤出匹配查询的日志行。
  3. 结果在 Grafana 或其他受支持的界面里呈现。

它能用来做什么
#

Loki 可以用于:

  • 集中式日志管理。把多个系统的日志汇总到一个统一视图。
  • 成本友好的日志方案。把多个系统的日志收进统一存储,避免这些系统自己去处理资源密集的任务。
  • 可观测性。把日志与指标、链路关联起来排查应用问题,也就是调试与监控。
  • 历史分析。长期保留日志以满足合规、审计或性能分析需求。

主要组件
#

Loki 是一个由许多组件构成的模块化系统。这些组件既可以一起运行(单二进制模式,运行所有 target),也可以按逻辑分组运行(简单可扩展部署模式,各运行 read、write 或 backend target),还可以各自独立运行(微服务模式)。正是这一点让它具备扩展能力。

组件allreadwritebackend说明
Distributorxx处理来自客户端的推送请求
Ingesterxx持久化数据并送往长期存储
Query front-endxx为查询调度器排队并优化请求
Query schedulerxx供 frontend 使用,把拆分后的查询排给 querier
Querierxx执行 LogQL 查询
Index gatewayxx处理并提供元数据查询
Compactorxx压实 ingester 产生的索引文件
Rulerxx管理与评估规则及告警表达式
Bloom plannerxx周期性规划 bloom 创建任务
Bloom builderxx处理规划器创建的任务以构建数据结构
Bloom gatewayxx处理并提供基于 bloom 过滤器的数据块过滤请求
Loki 组件

安装
#

首先安装一些前置依赖:

apt-get install curl gnupg2 ca-certificates lsb-release debian-archive-keyring

接着导入 Grafana 官方签名密钥,好让 APT 能校验我们稍后安装的软件包:

curl --silent https://apt.grafana.com/gpg.key | 
  gpg --dearmor --yes --output /etc/apt/keyrings/grafana.gpg

为 Grafana 的稳定版软件包配置 APT 仓库:

cat << EOF > /etc/apt/sources.list.d/apt-grafana.sources
X-Repolib-Name: APT Grafana
Types: deb
URIs: https://apt.grafana.com
Suites: stable
Components: main
Architectures: amd64
Signed-By: /etc/apt/keyrings/grafana.gpg
Enabled: yes
EOF

配置仓库 pinning,让系统优先使用 apt.grafana.com 的包而不是默认源:

echo -e "Package: *\nPin: origin apt.grafana.com\nPin: release o=stable\nPin-Priority: 900\n" \
  | tee /etc/apt/preferences.d/99loki

现在更新软件包索引并安装 Loki 与 Redis:

export LOKI_VERSION="3.5.1"
apt-get update
apt-get install loki=${LOKI_VERSION} redis

Redis 配置
#

Loki 使用 Redis 做缓存。Redis 只需最小配置,编辑 /etc/redis/redis.conf 里的以下选项:

requirepass <password>
maxmemory 100mb
maxmemory-policy allkeys-lru

密码可以用下面的命令生成:

openssl rand -base64 25 | tr --delete /=+ | cut --characters -32

然后重启 Redis:

systemctl restart redis

Loki 配置
#

Loki 服务器使用单一的 YAML 配置文件 /etc/loki/config.yml,其中包含 Loki 服务器及其各个组件的配置。这个文件由 systemd 服务文件1作为参数传给可执行文件。文件非常长,所以我们先介绍可用的主配置段:

键说明
target要运行的组件列表
auth_enabled启用认证与授权
ballast_bytes帮助优化垃圾回收
server配置主要的 HTTP 与 gRPC 服务器设置
common各组件共享的配置
distributor控制日志条目如何分发给 ingester
querier配置查询执行与结果处理
query_scheduler管理多个 querier 之间的查询调度
frontend配置查询 frontend,负责处理与缓存查询
query_range控制范围查询的拆分、缓存与并行化
ruler管理告警与记录规则
ruler_storage管理与 Thanos 对象存储2客户端的连接
ingester_client配置 distributor 与 ingester 的通信方式
ingester配置 ingester 组件,它把日志写入存储
block_builder定义日志数据如何被构造并压缩成块
block_scheduler管理块构建任务的调度
pattern_ingester配置基于模式的日志摄入
index_gateway在不必频繁访问对象存储的情况下管理索引查询
bloom_build构建 bloom 过滤器3以加速查询
bloom_gateway用 bloom 过滤器提供查询服务
storage_config为块与索引定义存储后端
chunk_store_config配置块的缓存与刷写行为
schema_config配置用于索引与存储日志的 schema
compactor配置索引压实以优化性能与成本
compactor_grpc_client配置 compactor 的 gRPC 客户端设置
limits_config设置摄入与查询的全局及按租户限制
frontend_worker配置处理 frontend 查询的 worker
table_manager管理索引表的生命周期
memberlist配置基于 memberlist 的 KV 存储以协调集群
dataobj_explorer允许交互式查看对象存储中的内容
runtime_config允许运行时动态变更配置
operational_config设置 Loki 实例的运行参数
tracing配置分布式链路追踪
analytics启用用量分析的采集
profiling配置性能剖析以分析性能
shutdown_delay延迟关闭,以便在途请求完成
metrics_namespace为所有发出的指标设置前缀

我们会用到其中大部分配置段,但不是全部。

配置 Loki
#

我们会用上面列出的配置键来配置单实例 Loki 服务器,名为 loki1.localdomain.com;顺序上大致参考 Grafana Labs 随 loki 包附带的默认 /etc/loki/config.yml 文件,以及 Grafana Loki 配置参数文档里的顺序。

我们会把一些默认值显式写出来,方便在系列推进、喂给 Loki 越来越多日志的过程中查找和调整。

目前 Loki 在配置变更后需要重启。所以当你过完所有配置选项、/etc/loki/config.yml 准备就绪时,执行:

systemctl restart loki

基础选项
#

我们会在单个实例里运行所有组件。此外,认证交给 NGINX 反向代理,并用防火墙限制对服务器的访问。

# Run all components in single binary mode
target: all

# Disable authentication
auth_enabled: false

# Optionally, disable reporting statistics to stats.grafana.org
analytics:
  reporting_enabled: false

服务器选项
#

Grafana 和我们的 Promtail agent 都会用 HTTP 与 Loki 通信。而 Loki 各组件之间用 gRPC 通信。

# Configuration options of the Loki server.
# See: https://grafana.com/docs/loki/latest/configure/#server
# Log level is set to `info` by default.
server:

  # Optionally, change the default ports
  http_listen_port: 8080
  grpc_listen_port: 8081

  # Default listen addresses
  http_listen_address: "0.0.0.0"
  grpc_listen_address: "0.0.0.0"

  # TLS configuration over HTTP
  # All gRPC connections will use the localhost, so no TLS needed
  tls_min_version: VersionTLS12
  http_tls_config:
    cert_file: "/etc/ssl/certs/localdomain.com.crt"
    key_file: "/etc/ssl/private/localdomain.com.key"

  # Log level
  log_level: info

  # Default size limit of gRPC messages this server can receive and send (4 MB)
  grpc_server_max_recv_msg_size: 4194304
  grpc_server_max_send_msg_size: 4194304

  # Increase the limit on the number of concurrent streams for gRPC
  # calls per client connection from 100 to 1K
  grpc_server_max_concurrent_streams: 1000

通用选项
#

这些是会被多个模块继承的基础配置项,可以在各模块自己的配置段里覆盖。

我们会用文件系统作为存储,这也是默认选项。软件包默认使用子目录 /tmp/loki,但我们会按 Debian 的规范调整它。

# Common configuration to be shared between multiple modules
# See: https://grafana.com/docs/loki/latest/configure/#common
common:
  path_prefix: /var/lib/loki
  storage:
    # Use the local filesystem as storage
    filesystem:
      # Directory to store chunks in
      chunks_directory: /var/lib/loki/chunks
      # Directory to store rules in
      rules_directory: /var/lib/loki/rules
  
  # Instruct components to use the localhost to communicate among themselves
  instance_addr: 127.0.0.1

  # Adapt the default replication factor to a single-instance deploy
  replication_factor: 1

  # Use the in-memory key/value store
  ring:
    kvstore:
      store: inmemory

instance_addr 是各组件向集群公布自己时使用的 IP 地址,它影响所有组件间通信(ring、gRPC、健康检查等)。

replication_factor 决定日志流在 ingester 之间存多少份副本。单实例部署必须把它设为 1,因为默认值 3 会让 Loki 试图向不存在的实例做复制。

Loki 里的 ring 是一种协调机制,组件用它跟踪自己对数据分片的所有权。它用哈希环确保日志流被一致地映射到特定 ingester,这对保持数据一致性和多实例部署中的复制至关重要。

在我们的单实例配置里,ring 的主要作用是满足 Loki 的内部架构要求,因此无需 etcd 这类分布式键值存储。

查询 frontend
#

这段配置决定查询 frontend 组件在查询拆分与缓存方面的行为。我们会用 Redis 替代默认的内嵌缓存,并尽可能使用压缩与缓存。

# Configuration options for query splitting and caching in the query-frontend
query_range:
  
  # Cache backend for the query frontend component
  results_cache:
  
    # Configures the cache backend for a specific component.
    # See: https://grafana.com/docs/loki/latest/configure/#cache_config
    cache:
  
      # Default validity of entries (unless overridden)
      default_validity: 1h

      # Redis server configuration
      redis:
        # Redis endpoint
        endpoint: 127.0.0.1:6379
        # Let Loki manage TTL via default validity
        expiration: 0s
        # Let Loki auto-scale (10 per CPU core)
        pool_size: 0
        # Password to use when connecting to Redis
        password: <password>
        # Keep idle connections open indefinitely
        idle_timeout: 0s
        # Keep connections alive forever
        max_connection_age: 0s

    # Use compression in cache
    compression: snappy

  # Cache query results (default is false)
  cache_results: true

  # Default behaviour to cache index stats, volume, series and label  query results
  cache_index_stats_results: true
  cache_volume_results: true
  cache_series_results: true
  cache_label_results: true

全局限制
#

limits_config 块配置 Loki 的全局与按租户限制。它支持的选项非常多,为了便于理解和维护,下面按类别分开呈现。此外,我们会用 Loki 来满足长期存储的合规要求。

样本大小包括日志行的大小和结构化元数据标签的大小

# Configure global limits
# See: https://grafana.com/docs/loki/latest/configure/#limits_config
limits_config:

  # A. Ingestion and rate limit

  # Enforce limits globally
  ingestion_rate_strategy: "global"

  # Default per-user ingestion rate limit in sample size per second (4MB)
  ingestion_rate_mb: 4

  # Default per-user allowed ingestion burst size (6MB). Burst size is the per-distributor
  # local rate limiter. Should be aligned with the expected max payload size per push request.
  ingestion_burst_size_mb: 6

  # Default maximum byte rate per second per stream (3MB)
  per_stream_rate_limit: "3MB"

  # Default maximum burst bytes per stream (15MB)
  per_stream_rate_limit_burst: "15MB"

  # B. Retention and aging

  # Default behaviour to reject samples meeting the criteria below
  reject_old_samples: true

  # Default maximum accepted sample age
  reject_old_samples_max_age: "1w"
  
  # Duration which table will be created/deleted before/after it is needed.
  # Samples from before this time will not be accepted.
  creation_grace_period: "10m"

  # Retention period to apply to stored data. Must be either 0 (disabled) or a multiple of 24h.
  # Requires `compactor.retention_enabled = true`. 43800 hours equals 5 years.
  retention_period: "43800h"

  # Default deletion mode
  deletion_mode: "filter-and-delete"

  # C. Query and performance

  # Enable metric aggregation to speed up histogram queries
  metric_aggregation_enabled: true

  # Default maximum number of unique series that is returned by a metric query
  max_query_series: 500

  # Default maximum number of queries that will be scheduled in parallel by the frontend
  max_query_parallelism: 32

  # Default limit to length of chunk store queries
  max_query_length: 30d1h

  # Default (lack of) limit to the length of the [range] inside a range query
  max_query_range: 0s

  # D. Metadata and features

  # Do not attempt auto-discovery of log levels during ingestion.
  # We will do this manually, via regex within Promtail.
  discover_log_levels: false

  # Default maximum number of active streams per user, across the cluster
  max_global_streams_per_user: 5000

  # Default behaviour to allow user to send structured metadata in push payload
  allow_structured_metadata: true

  # Default behaviour to enable log-volume endpoints for log volume dashboards.
  # Allows aggregating log counts (or sizes) over specified time ranges, grouped by labels,
  # e.g., "logs per minute" trend.
  volume_enabled: true

Compactor
#

compactor 组件为提升性能而压实索引分片,同时负责保留策略——也就是删除被认为过旧的日志。Loki 的默认行为是永久保留日志,我们要按需改变它。

# Configuration options of the compactor.
# See: https://grafana.com/docs/loki/latest/configure/#compactor
compactor:
  # Activate custom (per-stream, per-tenant) retention
  retention_enabled: true

  # Default aximum number of tables to compact in parallel
  max_compaction_parallelism: 1

  # Default number of upload/remove operations to execute in parallel when finalizing
  # a compaction, per compact operation, which can be executed in parallel
  upload_parallelism: 10

  # Define a store to be used for managing delete requests (default is none, which is invalid)
  # Requires setting `storage_config.filesystem.directory`.
  delete_request_store: filesystem

  # Default max number of delete requests to run per compaction cycle
  delete_batch_size: 70

  # Default interval at which compaction operations are run (how often)
  compaction_interval: 10m

  # Default delay after which chunks will be fully deleted during retention
  retention_delete_delay: 2h

  # Default working directory to store downloaded bloom blocks
  working_directory: "/var/lib/loki/compactor"

Ingester
#

在我们的单实例 Loki(ZFS 文件系统存储、启用压缩)上,我们会尝试一套优化过的 ingester 配置,以在块文件数量、内存占用与可靠性之间取得平衡。收到的日志流会同时按时间和大小从内存刷写到磁盘。

# Configuration options of the ingester.
# See: https://grafana.com/docs/loki/latest/configure/#ingester
ingester:

  # Flush chunks after 24h to prevent too many small files
  max_chunk_age: 24h

  # Align with `max_chunk_age` to flush inactive streams
  chunk_idle_period: 24h

  # Increase target compressed size (2MB) for chunks to balance file count and query performance.
  chunk_target_size: 2097152

  # Default target uncompressed size (256KB) of a chunk block lets ZFS compression handle this
  # effficiently. When this threshold is exceeded, the head block will be cut and compressed
  # inside the chunk.
  chunk_block_size: 262144

  # Retain chunks in memory after they have been flushed for late-arriving logs
  chunk_retain_period: 15m

  # Default maximum retries for failed flushes, critical for filesystem reliability
  max_retries: 10

  # How the lifecycle of the ingester will operate
  lifecycler:
    ring:

      # Default period at which to heartbeat to the ring
      heartbeat_period: 15s

      # Default heartbeat timeout after which compactors are considered unhealthy within the ring
      heartbeat_timeout: 1m

    # Default duration to sleep before exiting on shutdown (no data loss with WAL)
    final_sleep: 0s

Schema
#

这段配置块索引的 schema 及其存放位置。我们会按天维护索引表与块表,并把索引和块拆进子目录,避免大量文件挤在我们本地磁盘时序数据库的同一个目录里。

# Configuration options of the schema.
# See: https://grafana.com/docs/loki/latest/configure/#schema_config
# See: https://grafana.com/docs/loki/latest/configure/#period_config
schema_config:
  
  # Configures the chunk index schema and where it is stored.
  configs:
 
    # Configure what index schemas should be used for from specific time periods
    # The date of the first day that index buckets should be created
    - from: "2024-01-01"
 
      # Which index to use. Either 'tsdb' or 'boltdb-shipper'.  <store>
      # and <object_store> below affect which <storage_config> key is used.
      store: tsdb
      # Which store to use for the chunks
      object_store: filesystem
      # The schema version to use (current recommended schema is v13).
      schema: v13
  
      # Configures how the index is updated and stored
      index:
        # Path prefix for index tables. Prefix always needs to end with a path
        # delimiter '/', except when the prefix is empty (default is "index/").
        path_prefix: "index/"
        # Table prefix for all period tables (default is "")
        prefix: "index_"
        # Table period. Retention is only available if the index period is 24h.
        # Single store TSDB and single store BoltDB require 24h index period.
        period: "24h"

      # Configure how the chunks are updated and stored
      chunks:
        # Table prefix for all period tables
        prefix: "chunks_"
        # Table period
        period: "24h"

      # Default number of shards that will be created is fine unless high cardinality is
      # encountered (many unique label combinations).
      row_shards: 16

Pattern ingester
#

pattern ingester 允许对日志做模式分析,也能创建 Bloom 过滤器。Bloom 过滤器是一种空间高效的、概率型的数据结构,用来判断某个数据是否属于某个子集。

负责构建 bloom 过滤器的 bloom 服务器的配置在 bloom_build 段;负责根据过滤表达式提供块过滤查询的 bloom gateway 服务器的配置在 bloom_gateway 段。在当前版本的 Loki 中,这两个服务器都是实验性的。

# Configuration options of the pattern ingester.
# See: https://grafana.com/docs/loki/latest/configure/#pattern-ingester
pattern_ingester:

  # Enable the pattern ingester
  enabled: true

  # Metric aggregation settings
  metric_aggregation:

    # Address of the Loki instance to push aggregated metrics to,
    # matching `server.http_listen_address` and `server.http_listen_port`
    loki_address: 127.0.0.1:8080

    # HTTP client tuning
    http_client_config:
      enable_http2: true
      proxy_from_environment: false
      # Fail fast on slow pushes
      timeout: 10s
      # Disabled for security
      follow_redirects: false

    # Reduce load by incresing the default value (30s) of the interval between operations
    pull_push_interval: 2m

  # Configures how the lifecycle of the pattern ingester will operate and where
  # it will register for discovery.
  lifecycler:
    # `ring` inherits from `common.ring` (in-memory)
    # Default period at which to heartbeat
    heartbeat_period: 5s
    # Default heartbeat timeout after which instance is assumed to be unhealthy
    heartbeat_timeout: 1m    

# Configuration options for the bloom planner and builder servers
bloom_build:

  # Enable the experimental feature
  enabled: true

  # Limit concurrency so two bloom‑build tasks run at once
  max_builders: 2
  # Retry each individual bloom‑build task twice on failure before marking it as failed
  task_max_retries: 2
  # How long the planner will wait for a builder to acknowledge or complete a task before requeuing
  builder_response_timeout: 30s
  # ZFS already compresses disk storage, but this helps in-memory transfer efficiency and page size
  bloom_block_encoding: "zstd"
  # Once a new bloom block is built, fetch it into the gateway's cache so queries can use it without extra latency
  prefetch_blocks: true

  # Decrease the default to 150MB to keep down the heap footprint of each builder task.
  # Smaller blocks give the builder more, finer‑grained units of work.
  # In a single‑instance environment, this helps distribute CPU and I/O more evenly across cores.
  max_block_size: 150MiB
  # Maximum size of the raw bloom filter per individual time series. Filters larger than this are dropped.
  max_bloom_size: 64MiB
  # Instruct the planner to break the series key‑space into 128 slices so builds can run in parallel,
  # smaller units, aiming for roughly 8 GB of series data per bloom‑build task.
  planning_strategy: "split_keyspace_by_factor"
  split_keyspace_by: 128
  split_target_series_chunk_size: 8GB

  # Configuration options for the bloom planner server
  planner:

    # Running the bloom creation planning twice a day is enough
    planning_interval: 12h

    # Cover recent activity and include recent historical context.
    # Setting `min_table_offset`to 0 ensures that the current active index table (where most
    # writes happen) is included, which enables faster recent queries.
    # Setting `max_table_offset` to 2 means the planner includes the last two inactive tables
    # as well, which helps with queries that span recent time windows (e.g., last 24–48h).
    # Because older tables rarely change, there is little benefit in trying to replan them
    # every time unless retention requirements change.
    min_table_offset: 0
    max_table_offset: 2

    retention:
      # Enable bloom retention
      enabled: true
    queue:
      # Reduce the default maximum number of tasks to queue per tenant to keep the queue size
      # modest, reducing the change of OOM and GC pressure in our single instance. Even under
      # heavy indexing, 1000 pending bloom‑build tasks provides ample headroom.
      max_queued_tasks_per_tenant: 1000
      # Move queued tasks off the heap and onto the ZFS filesystem to avoi bloating memory.
      # ZFS has built-in compression, which makes on-disk queues very space-efficient.
      store_tasks_on_disk: true
      # Directory to store tasks on disk.
      tasks_disk_directory: /var/lib/loki/bloom-planner-queue
      # Default setting not to clean the tasks directory upon startup.
      clean_tasks_directory: false

  # Configuration options for the bloom builder server
  builder:
    # Address and port of the bloom planner,
    # matching `server.grpc_listen_address` and `server.grpc_listen_port`.
    planner_address: 127.0.0.1:8081

    # See: https://grafana.com/docs/loki/latest/configure/#grpc_client
    grpc_config:
      # Decrease the maximum size of messages from 100MB to 10MB to prevent a single huge
      # bloom‑filter transfer from triggering a GC stall or OOM in our single-instance deploy
      # and to align with expected bloom-block sizes
      max_send_msg_size: 10485760
      max_recv_msg_size: 10485760

    # Controls how the builder retries when an individual bloom‑build task (its gRPC call to 
    # the planner) fails temporarily, e.g., due to CPU contention, or I/O stall).
    # It implements an exponential‑style retry delay so that the system:
    # 1. Doesn’t hammer the planner continuously on every failure
    # 2. Gives transient issues time to clear before trying again.
    # 3. Eventually gives up (after `max_retries`) 
    backoff_config:
      # These backoff settings keep bloom‑build tasks responsive to transient hiccups while 
      # ensuring fail‑fast behavior for persistent problems—ideal for a single‑instance

      # Prevents hot‑looping on very rapid retries (100 ms can be too tight under load).
      # A slightly longer base delay gives transient pressure (e.g. brief CPU spikes or 
      # filesystem contention) time to settle.
      min_period: 250ms
      # Caps backoff so that, in persistent error scenarios, we don’t end up waiting a 
      # full 10 s before retrying. A 5 s ceiling balances giving the system breathing 
      # space versus surfacing issues faster.
      max_period: 5s
      # Halves the default retry count so that truly failing tasks will give up sooner,
      # free up queue slots, and let you detect and investigate root causes, rather than 
      # thrashing on repeated futile retries.
      max_retries: 5

bloom_gateway:

  # Turn the gateway on so queries can use Bloom filters to skip irrelevant chunks
  # and actually apply the bloom‑based chunk filtering in the read path
  enabled: true
  enable_filtering: true

  # Number of parallel workers testing chunks against Bloom filters
  worker_concurrency: 2
  # Lower the number of blocks each worker can check at once to reduce peak memory and gRPC streams
  block_query_concurrency: 4
  # Reduce the size of the in-flight Bloom-filter checks per tenant queue to keep memory bounded
  # and back-presure predictable in our single-instance.
  max_outstanding_per_tenant: 256
  # Redice the chunk-filter tasks to batch together to reduce per-RPC payload size, easing gRPC
  # backpressure and GC presure.
  num_multiplex_tasks: 128

  client:
    # Point the gateway's gRPC client at the planner endpoint,
    # matching `server.grpc_listen_address` and `server.grpc_listen_port`.
    addresses: 127.0.0.1:8081
    pool_config:
      # Decreas how often the client refreshes its list of gateway backends, to reduce DNS or
      # service-discovery churn on a stable, single-node address list.
      check_interval: 30s
    grpc_client_config:
      # Cap gRPC message sizes to 10 MB to bound per-RPC memory (from 100 MB) to reduce chances of
      # triggering GC spikes if a single RPC returns many blocks.
      max_send_msg_size: 10MiB
      max_recv_msg_size: 10MiB

这些设置合在一起,让我们的 Loki 实例真正能用 Bloom 过滤器加速查询,同时在单节点 ZFS 系统上把资源使用控制在有界且可预测的范围内。

  • 内存:更低的并发、更小的批量、以及在途任务/RPC 大小的更紧限制,能防止单个进程把内存撑爆。
  • CPU:更少的 worker 与块检查次数,契合 2–4 核这类适中的核心数,避免过度的上下文切换。
  • 文件系统:磁盘上的 Bloom 块由 ZFS 压缩与缓存处理;较小的内存缓冲区与 ARC 配合良好,不会挤掉热数据。

Ruler
#

Loki 的 Ruler 会持续针对我们的日志数据评估 Prometheus 风格的记录规则与告警规则。在现阶段,我们不使用任何规则,既不用记录规则也不用告警规则。本系列后面会在单独一篇文章里配置并使用 Alertmanager。

# Top‑level storage config for the ruler (replaces deprecated `ruler.storage`)
ruler_storage:
  backend: filesystem
  local:
    # Where rule files in YAML format will be stored
    directory: /var/lib/loki/rules

ruler:
  # Do not expose the alert‑rule API until Alertmanager is in play
  enable_api: false

Frontend
#

Loki 中的 frontend 位于查询链路的边缘。它接受进来的 HTTP 查询,处理请求层面的问题(超时、请求体大小限制、日志记录),执行按租户的并发控制,然后把工作转交给 querier 或 scheduler。调优 frontend 让我们能在吞吐、延迟与资源使用之间取得平衡。

frontend:

  # Log slow queries
  log_queries_longer_than: 500ms

  # Include these request headers in slow‑query logs
  log_query_request_headers: "User‑Agent,X‑Request‑ID"

  # Enable per‑query stats
  query_stats_enabled: true

  # Bump max body size of requests from 10 MB to 20 MB
  max_body_size: 20971520

  # Throttle concurrent outstanding queries per tenant to bound memory,
  # improving efficiency of ZFS ARC, if present
  max_outstanding_per_tenant: 512

  # Increase the time between DNS lookups of the scheduler
  scheduler_dns_lookup_period: 30s

  # Reduce the time to wait for in‑flight queries on shutdown
  graceful_shutdown_timeout: 2m

供参考:encoding 参数的默认值(即 json)只影响 frontend 如何解释经 HTTP 进来的查询负载,不影响它如何与 querier 或 scheduler 通信——那些交互始终使用 gRPC 加 protobuf。此外,HTTP 响应默认会被压缩。

在我们的单实例 Loki 中不会使用分片,因此 frontend.enable_sharding: false 与 frontend.strategy: default 的默认值就够用了。

慢查询日志与统计让我们能调优性能。它们会以类似下面的格式出现在 journald 里:

# journalctl --unit=loki --follow
level=info ts=2025-05-12T14:50:02.123Z caller=frontend.go:XXX msg="slow query detected" query_duration=611.342ms method=GET path=/loki/api/v1/query_range params="..." headers="User-Agent=Grafana/X.X"
查询 Loki

Querier
#

querier 是 Loki 执行日志查询的主力。它同时从内存中的 ingester 与长期存储(块)拉取数据,合并并过滤日志流,应用查询变换(例如 |= 或 |~),最后把组装好的结果返回给 frontend 或直接返回给客户端。

querier:
  # Adapt the number of concurrent queries for 2-4 CPU cores
  max_concurrent: 4

  # Decrease message size from 100 MiB to 10 MiB to bound memory per-RPC
  grpc_client_config:
    max_send_msg_size: 10485760
    max_recv_msg_size: 10485760

这一段里大多数默认值本来就是面向单实例 Loki 安装的,所以我们只需调整并发数与消息大小。下面列出各指令及其默认值,你可以加进配置文件作参考,也可以跳过以保持精简。

  # Default values of the engine, for reference
  engine:
    # Cap how far an instant query looks back
    max_look_back_period: 30s
    # topk sketch size
    max_count_min_sketch_heap_size: 10000

  # Default values regarding multi-tenancy, for reference
  # Read both ingesters & store
  query_store_only: false
  # Skip store if object store is unavailable
  query_ingester_only: false
  # Single-tenant mode
  multi_tenant_queries_enabled: false
  # No header-based overrides
  per_request_limits_enabled: false
  # No partitioning of ingesters
  query_partition_ingesters: false

  # Default values of query size and volume limits, for reference
  # Prevent runaway chunk scans
  max_chunks_per_query: 2000000
  # Cap series returned
  max_query_series: 500
  # Allow going all the way back in time when querying data and metadata
  max_query_lookback: 0s
  # Maximum span of a single query
  max_query_length: 30d1h
  # Do not limit the length of the range in range queries
  max_query_range: 0s
  # Maximum number of queries that will be scheduled in parallel by the frontend
  max_query_parallelism: 32
  # Maximum number of queries will be scheduled in parallel by the frontend for TSDB schemas.
  tsdb_max_query_parallelism: 128
  # Target maximum number of bytes assigned to a single sharded query
  tsdb_max_bytes_per_shard: 600MB
  # Sharding strategy to use in query planning
  tsdb_sharding_strategy: "power_of_two"

  # Default values of frontend and scheduler integration, for reference. When neither
  # `frontend_address` nor `scheduler_address` are set, queries are only received via HTTP endpoint.
  frontend_address: ""
  scheduler_address: ""

Query range
#

这个块决定范围查询如何被拆分以并行执行,以及它们的部分结果在组装前如何缓存。Loki 在 query_range/querier 范围内提供六种独立的结果缓存:

缓存类型缓存内容
时间范围结果范围查询返回的最终合并时序数据点
索引统计看板中使用的序列数与标签基数统计
日志量指标某时间范围内匹配查询的日志行总数与总大小
序列列表匹配给定日志选择器的序列键集合
标签值某个标签名与选择器下观测到的全部值
即时指标单点指标查询(例如错误率、now 时刻的 gauge)

我们会把它们全部配置为使用 Redis,以便享受跨重启的持久性。遗憾的是,目前 Loki 没有提供减少这类配置冗长度的办法。

其他指令的默认值都符合我们的需要。下面显式写出其中两个,供参考。

query_range:
  # Keep raw time bounds, i.e., do not mutate incoming queries to align their
  # start and end with their step (this is the default behaviour).
  align_queries_with_step: false
  # Do not attempt to parallelise query execution via a shared scheduler (default behaviour).
  parallelise_shardable_queries: false

  # Time-range results cache
  cache_results: true
  results_cache:
    cache:
      redis:
        endpoint: 127.0.0.1:6379
        password: <password>
        expiration: 1h
        pool_size: 10
        idle_timeout: 30s
        max_connection_age: 5m
    compression: snappy

  # Index‐stats cache
  cache_index_stats_results: true
  index_stats_results_cache:
    cache:
      redis:
        endpoint: 127.0.0.1:6379
        password: <password>
        # Fresher index counts
        expiration: 15m
        pool_size: 5
        idle_timeout: 30s
        max_connection_age: 5m
    compression: snappy

  # Volume‐results cache
  cache_volume_results: true
  volume_results_cache:
    cache:
      redis:
        endpoint: 127.0.0.1:6379
        password: <password>
        expiration: 1h
        pool_size: 5
        idle_timeout: 30s
        max_connection_age: 5m
    compression: snappy

  # Series‐results cache
  cache_series_results: true
  series_results_cache:
    cache:
      redis:
        endpoint: 127.0.0.1:6379
        password: <password>
        expiration: 1h
        pool_size: 5
        idle_timeout: 30s
        max_connection_age: 5m
    compression: snappy

  # Label‐values cache
  cache_label_results: true
  label_results_cache:
    cache:
      redis:
        endpoint: 127.0.0.1:6379
        password: <password>
        # Labels change less often
        expiration: 2h
        pool_size: 5
        idle_timeout: 30s
        max_connection_age: 5m
    compression: snappy

  # Instant‐metric cache
  cache_instant_metric_results: true
  instant_metric_results_cache:
    cache:
      redis:
        endpoint: 127.0.0.1:6379
        password: <password>
        expiration: 30m
        pool_size: 5
        idle_timeout: 30s
        max_connection_age: 5m
    compression: snappy

一些用例有助于理解每种缓存里存的是什么。下面的 LogQL 表达式并不高效,但刻意保持简单。

缓存类型LogQL 表达式用例
时间范围结果`count_over_time({job=“nginx”}= “GET” [5m])`
索引统计`count_over_time({job=“nginx”}= “GET” [1h])`
日志量`count_over_time({job=“nginx”}= “GET” [5m])`
序列列表`count_over_time({job=“nginx”}= “GET” [1h])`
标签值`label_values({job=“nginx”}= “GET”, status)`
即时指标`count_over_time({job=“nginx”}= “GET” [1m])`

尽管有些示例是重复的,但每一个在底层都以不同方式被缓存和使用。这里有点超前,但请注意同一查询(例如 count_over_time({job="nginx"} |= "GET" [1m]))可能用到多个缓存,也就是说它如何被缓存取决于它怎么执行:

  • 如果在 Grafana 图形面板里用(带时间范围),它会作为范围查询执行(经由 /loki/api/v1/query_range),结果缓存在时间范围结果缓存里。
  • 如果用在 gauge 面板、告警规则或 Grafana 的「Instant」模式里,它变成即时查询(经由 /loki/api/v1/query),返回单个值,因此结果缓存在即时指标缓存里。
  • 如果 Grafana 需要为某个筛选条件(例如 status)自动补全标签值,它可能会执行 label_values(...) 这类查询,由标签值缓存提供服务。

所以,即便两个查询在 LogQL 里看起来一样,Loki 也可能因执行方式与位置不同而采用不同的缓存与读取路径。

日志摄入
#

Loki 让日志流经一组组件来摄入,每个组件在接受、处理、存储和索引日志数据方面都有特定职责。虽然有些组件是可选的、或只在大规模部署中使用,但理解整个摄入路径有助于弄清日志如何被打标签、路由、存储和高效查询。下面是摄入管线的概要流程:

  1. Distributor。接受来自客户端(例如 Promtail)的日志条目,校验它们,按标签拆分成日志流,并用一致性哈希把它们分配给 ingester。它确保具有相同标签集的日志被路由到同一个 ingester。

  2. Ingester。从 distributor 接收日志并暂存在内存中。它把日志攒成压缩块,当块达到大小、时效或空闲阈值时刷写到长期存储。Ingester 还处理日志复制,并为查询暴露最近的日志。

  3. Query frontend (可选)。位于 Grafana(或 API 客户端)与 querier 之间。它通过把大查询拆成子查询、缓存结果、分发负载来提升查询响应性。在高流量或多租户场景下尤其有用。

  4. Query scheduler (可选)。通过把查询排队与执行解耦来提升可扩展性与公平性。它接收来自 query frontend 的子查询,排进按租户的队列,再分派给 querier 执行。

  5. Querier。执行用 LogQL 写的用户查询。它从 ingester 取最近的日志、从存储取历史块,合并结果,按标签与内容过滤,再返回给用户。

  6. Index gateway。充当 querier 与索引存储之间的中间层。它缓存并提供索引数据(即标签 → 块的映射),减轻索引后端的压力、降低查询延迟。

  7. Chunk store。压缩日志块的长期存储后端。可以是本地文件系统、对象存储(例如 S3、GCS)或其他受支持的存储。块以高效的压缩格式存放。

  8. Index store。存放关于「按标签匹配器去何处找日志」的元数据。这个索引把日志流标签映射到块引用,用于在查询执行时快速找到候选块。

  9. Promtail。日志投递器,从文件、journald 或 syslog 等来源读取日志。它附加标签(例如 job、host、app),并通过 HTTP 或 gRPC 把增强后的日志发给 Loki 的 distributor。

摄入日志

数据存在哪里
#

Grafana Loki 把数据存成块(chunks)和索引(indexes):

  • 块。包含实际的日志数据,压缩后存放在对象存储系统中。
  • 索引。包含存放在数据库中的元数据(标签)。

Loki 支持多种存储后端,最相关的有:

  • 本地:文件系统上的时序数据库(TSDB)。
  • 远程:S3 或其他对象存储系统,用于扩展。

数据存放在一个目录里,本例中是 /var/lib/loki/,由 common.path_prefix 键定义。

在 chunks/ 里我们会看到两个子目录:fake/ 和 index/。前者是单租户部署中的租户 id,存放所有块(日志数据);后者存放索引文件(把标签映射到块的元数据)。

在我们的单租户实例中,会用文件系统存放块(/var/lib/loki/chunks/fake)。本系列后面会可选地切换到 S3。

目录用途
chunks/fake/存放单租户实例的所有块(日志数据)
chunks/index/存放索引文件(把标签映射到块的元数据)
compactor/compactor 的工作文件(保留/删除操作)
wal/预写日志,在刷写之前缓冲最近的日志条目
tsdb-shipper-active/上传前存放活跃的 TSDB 块(索引与元数据)
tsdb-shipper-cache/已上传或已下载索引块的缓存
rules/规则组(记录与告警)的本地目录

TSDB shipper 目录在 Loki 使用 TSDB 索引存储时启用,这是默认行为,由 schema_config.configs.store 键启用——即便在纯本地模式下(即不上传到对象存储)也是如此。

  • tsdb-shipper-active/ 包含当前正在构建与压实的 TSDB 块文件。
  • tsdb-shipper-cache/ 存放已上传或已下载块的元数据,用于更快访问与去重。

为防止崩溃丢数据,Loki 使用存放在 wal/ 子目录中、按段切分的 WAL,服务器重启时可以重放它来恢复数据。ingester 与 ruler 组件都会用到这个 WAL。

本系列后面我们会使用告警规则。当 ruler_storage.backend 配置键使用 filesystem 时,Loki 会把规则组定义存放在 rules/ 目录。


  1. 位于 /etc/systemd/system/loki.service。↩︎

  2. Thanos 对象存储客户端提供了一个与各种对象存储厂商打交道的统一接口。↩︎

  3. Bloom 过滤器是一种空间高效的概率型数据结构,用来判断某个元素是否是某个集合的成员。↩︎

Grafana - 这篇文章属于一个选集。
§ 4: 本文

相关文章