GoAccess 是开源实时 Nginx 日志分析工具,需匹配日志格式(如含 $request_time 需 --log-format 显式配置)、设置权限(如加入 adm 组)、选择终端或 HTML 实时模式,并可用 systemd 托管服务实现持久化监控。

GoAccess 是一款开源、实时、终端友好的 Nginx 日志分析工具,支持从标准 access.log 中解析请求、IP、状态码、UA、响应时间等关键指标,并以交互式终端界面或 HTML 报表形式呈现。部署它做实时可视化,核心在于日志格式匹配、权限配置和运行模式选择。
确认 Nginx 日志格式与 GoAccess 兼容
GoAccess 默认支持 Common Log Format(CLF) 和 Combined Log Format,但很多 Nginx 配置启用了自定义字段(如 $request_time、$upstream_response_time),需显式声明解析规则。
- 检查 Nginx 的 log_format,例如:
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'"$status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" $request_time;' - 若含 $request_time 等扩展字段,启动 GoAccess 时必须用 --log-format 显式指定模板,例如:
goaccess access.log --log-format='%h %^[%d:%t %^] "%r" %s %b "%R" "%u" %^ %T' --date-format='%d/%b/%Y' --time-format='%H:%M:%S' - 推荐先用 --dry-run 测试日志是否可被正确解析:
goaccess access.log --log-format=COMBINED --dry-run
启用实时监控:终端模式 or HTML 实时报表
GoAccess 支持两种实时方式:终端内滚动刷新(适合运维看板),或生成自动刷新的 HTML 页面(适合团队共享)。
-
终端实时模式(需保持 SSH 连接):
goaccess /var/log/nginx/access.log -f --log-format=COMBINED --date-format='%d/%b/%Y' --time-format='%H:%M:%S'
按 q 退出,按 shift + F 进入跟随模式(类似 tail -f) -
HTML 实时报表(后台常驻 + 自动刷新):
goaccess /var/log/nginx/access.log -o /usr/share/nginx/html/report.html --real-time-html --ws-url=wss://your-domain.com:7890 --log-format=COMBINED
需配合 WebSocket 服务(内置 ws-server 或用 nginx 反代),浏览器打开 report.html 即可见动态更新图表
权限与日志轮转适配
GoAccess 需要读取日志文件,而 Nginx 日志通常属 root:adm,普通用户无法直接访问。
- 将运行 GoAccess 的用户加入 adm 组:
sudo usermod -a -G adm www-data(若用 www-data 启动) - 或改日志权限(不推荐生产环境):
sudo chmod 644 /var/log/nginx/access.log* - 对接 logrotate:GoAccess 能自动识别新日志文件,但轮转后需确保它监听的是当前 active 文件(建议用 -f 参数配合 --persist 持久化状态,或使用 systemd service 监控文件变化)
轻量集成:用 systemd 托管后台服务
避免手动运行,用 systemd 实现开机自启 + 自动重启,适合长期监控。
- 新建 service 文件:
/etc/systemd/system/goaccess.service - 内容示例(HTML 模式):
[Unit]
Description=GoAccess Real-time Log Analyzer
After=network.target
[Service]
Type=simple
User=www-data
ExecStart=/usr/bin/goaccess /var/log/nginx/access.log -o /var/www/html/report.html --real-time-html --ws-url=wss://logs.example.com:7890 --log-format=COMBINED --date-format='%d/%b/%Y' --time-format='%H:%M:%S'
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target - 启用并启动:
sudo systemctl daemon-reload && sudo systemctl enable goaccess && sudo systemctl start goaccess










