Ubuntu服务器数量一多,登录每台机器手动翻/var/log就变成一种低效且容易遗漏的运维方式。要解决这个问题,最直接的办法是搭建一个轻量集中日志系统:在每台服务器上装一个采集端,把syslog、认证日志、应用日志统一发到一台日志服务器,再用一个带Web界面的工具做检索和查看。下面按实际部署顺序,把关键步骤和配置讲清楚。

架构选型:Loki + Promtail 还是 Elasticsearch + Filebeat

集中日志方案很多,但对Ubuntu服务器运维来说,优先考虑资源占用和维护成本。Elasticsearch功能强,但内存消耗大,单机部署容易吃紧。Loki是Grafana出品的日志聚合系统,索引只针对标签,原文按块存储,配合Promtail采集端,资源占用小,适合中小规模服务器集群。本文以Loki + Promtail + Grafana为例,部署在一台Ubuntu 22.04日志服务器上,客户端同样为Ubuntu系统。

日志服务器端安装Loki

先在日志服务器上下载Loki二进制文件。以root用户执行以下命令,创建专用系统用户和目录:

useradd --system --no-create-home --shell /usr/sbin/nologin loki
mkdir -p /etc/loki /var/lib/loki /var/log/loki
chown -R loki:loki /etc/loki /var/lib/loki /var/log/loki

下载Loki最新稳定版,解压后把可执行文件放到/usr/local/bin:

cd /tmp
curl -LO https://github.com/grafana/loki/releases/download/v2.9.4/loki-linux-amd64.zip
unzip loki-linux-amd64.zip
mv loki-linux-amd64 /usr/local/bin/loki
chmod +x /usr/local/bin/loki

创建Loki配置文件/etc/loki/loki-config.yaml,内容如下:

auth_enabled: false

server:
  http_listen_port: 3100
  grpc_listen_port: 9096

common:
  instance_addr: 127.0.0.1
  path_prefix: /var/lib/loki
  storage:
    filesystem:
      chunks_directory: /var/lib/loki/chunks
      rules_directory: /var/lib/loki/rules
  replication_factor: 1
  ring:
    kvstore:
      store: inmemory

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

limits_config:
  retention_period: 744h
  allow_structured_metadata: true

compactor:
  working_directory: /var/lib/loki/compactor
  shared_store: filesystem

该配置关闭认证,监听3100端口,数据存储在本地文件系统,日志保留31天。创建systemd服务文件/etc/systemd/system/loki.service:

[Unit]
Description=Loki log aggregation service
After=network.target

[Service]
User=loki
Group=loki
ExecStart=/usr/local/bin/loki -config.file=/etc/loki/loki-config.yaml
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target

启动并设置开机自启:

systemctl daemon-reload
systemctl enable --now loki
systemctl status loki

确认服务运行正常后,Loki端就绪。

客户端安装Promtail并配置采集规则

每台需要收集日志的Ubuntu服务器都要安装Promtail。同样创建系统用户和目录:

useradd --system --no-create-home --shell /usr/sbin/nologin promtail
mkdir -p /etc/promtail /var/log/promtail
chown -R promtail:promtail /etc/promtail /var/log/promtail

下载Promtail二进制文件:

cd /tmp
curl -LO https://github.com/grafana/loki/releases/download/v2.9.4/promtail-linux-amd64.zip
unzip promtail-linux-amd64.zip
mv promtail-linux-amd64 /usr/local/bin/promtail
chmod +x /usr/local/bin/promtail

创建Promtail配置/etc/promtail/promtail-config.yaml,核心是定义采集目标和推送地址:

server:
  http_listen_port: 9080
  grpc_listen_port: 0

positions:
  filename: /var/log/promtail/positions.yaml

clients:
  - url: http://日志服务器IP:3100/loki/api/v1/push

scrape_configs:
  - job_name: system
    static_configs:
      - targets:
          - localhost
        labels:
          job: system
          host: 本机主机名
          __path__: /var/log/syslog

  - job_name: auth
    static_configs:
      - targets:
          - localhost
        labels:
          job: auth
          host: 本机主机名
          __path__: /var/log/auth.log

  - job_name: kernel
    static_configs:
      - targets:
          - localhost
        labels:
          job: kernel
          host: 本机主机名
          __path__: /var/log/kern.log

  - job_name: nginx
    static_configs:
      - targets:
          - localhost
        labels:
          job: nginx
          host: 本机主机名
          __path__: /var/log/nginx/*.log

这里采集了系统日志、认证日志、内核日志和Nginx访问/错误日志。如果应用日志路径不同,按需添加新的job_name和__path__。注意labels中的host必须每台机器不同,否则检索时无法区分来源。创建systemd服务:

[Unit]
Description=Promtail log collector
After=network.target

[Service]
User=promtail
Group=promtail
ExecStart=/usr/local/bin/promtail -config.file=/etc/promtail/promtail-config.yaml
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target

启动Promtail:

systemctl daemon-reload
systemctl enable --now promtail
systemctl status promtail

Promtail默认会记录读取位置到positions.yaml,重启后不会重复采集已读日志。

安装Grafana并接入Loki数据源

日志服务器上安装Grafana用于查询和展示。Ubuntu 22.04可以直接用官方仓库安装:

apt-get install -y apt-transport-https software-properties-common wget
wget -q -O /usr/share/keyrings/grafana.key https://apt.grafana.com/gpg.key
echo "deb [signed-by=/usr/share/keyrings/grafana.key] https://apt.grafana.com stable main" | tee /etc/apt/sources.list.d/grafana.list
apt-get update
apt-get install -y grafana
systemctl enable --now grafana-server

浏览器访问http://日志服务器IP:3000,默认账号admin/admin,首次登录会要求修改密码。进入后点击左侧Connections -> Add data source,搜索Loki,在URL处填写http://localhost:3100,点击Save & test,显示成功即可。

日志查询与常用过滤语法

进入Grafana左侧Explore,选择Loki数据源,就可以用LogQL查询日志。最基础的查询是直接输入标签选择器:

{job="system"}

查看某台主机的所有日志:

{host="web-server-01"}

按关键词过滤,例如查找sshd相关记录:

{job="auth"} |= "sshd"

查找包含“error”但不包含“debug”的日志:

{job="system"} |= "error" != "debug"

使用正则匹配IP地址:

{job="nginx"} |~ "([0-9]{1,3}\.){3}[0-9]{1,3}"

统计最近5分钟内每台主机的日志条数:

sum by (host) (rate({job="system"}[5m]))

这些查询可以直接在Explore中运行,也可以保存到Dashboard面板中做持续监控。

日志保留策略与磁盘空间控制

Loki默认不删除日志,必须显式配置保留期。前面配置中已设置retention_period: 744h,即31天。但还需要开启自动删除,在limits_config中加入:

limits_config:
  retention_period: 744h
  retention_stream:
    - selector: '{job="nginx"}'
      priority: 1
      period: 168h

这样Nginx访问日志只保留7天,系统日志保留31天,有效控制磁盘占用。同时建议定期检查/var/lib/loki目录大小,必要时调整保留期或增加存储空间。Promtail端也要注意positions.yaml文件会持续增长,但单个文件通常很小,无需特别处理。

多机部署时的标签规范

标签设计直接影响后续查询效率。Loki的标签基数不能过高,否则索引膨胀。建议每台机器只设置host和job两个核心标签,不要在标签中放入IP、路径等高频变化值。如果需要在查询时按IP或应用名过滤,可以用结构化元数据或查询时正则提取,而不是在Promtail中定义成标签。例如Nginx日志中的状态码、响应时间等,用LogQL的pattern解析器在查询时提取,比直接打标签更合理。

故障排查与常见问题

Promtail无法推送日志到Loki时,先检查Promtail日志:

journalctl -u promtail -f

常见错误包括:目标Loki地址不通、防火墙拦截3100端口、Promtail运行用户对日志文件无读取权限。Ubuntu默认的/var/log/syslog和auth.log权限为640,属于syslog和adm组,Promtail以promtail用户运行会读不到。解决办法是将promtail用户加入adm组:

usermod -a -G adm promtail
systemctl restart promtail

Nginx日志默认属于www-data用户,如果Promtail读不到,同样需要把promtail加入www-data组或调整日志目录权限。另一个常见问题是时间戳不一致,确保所有服务器开启NTP时间同步,否则日志顺序会混乱。

安全加固建议

上述配置关闭了Loki认证,适合内网可信环境。如果日志服务器暴露在公网或存在多租户需求,应启用Loki的basic auth或接入反向代理。至少要在防火墙层面限制3100端口只允许内网服务器访问。Grafana的3000端口也应限制来源IP,并修改默认管理员密码。对于日志内容本身,注意auth.log中可能包含登录用户名、来源IP等敏感信息,集中存储后要控制访问权限。

这套方案部署完成后,日常运维只需打开Grafana,在Explore中输入LogQL查询,就能跨所有服务器检索日志。相比逐台登录服务器翻文件,效率提升明显,而且日志集中后可以做统一的保留策略和告警规则。对于Ubuntu服务器数量在几台到几十台的场景,Loki + Promtail的资源占用和运维成本都控制在很低的水平,是一个实用的选择。

本文由人工智能生成,已经人工复核后发布。