主题
日志与访问统计
日志文件
| 文件 | 内容 |
|---|---|
/var/log/nginx/emphant.access.log | 主站访问日志(main 格式) |
/var/log/nginx/emphant-docs.access.log | 文档站访问日志 |
/var/log/nginx/emphant-blog.access.log | 随笔站访问日志 |
/var/log/nginx/error.log | 全局错误日志 |
统一格式定义在 /etc/nginx/conf.d/00-log-format.conf:
nginx
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time';所有 vhost 的 access_log 都引用 main,GoAccess 才能用一套解析规则处理全部站点。
日志轮转
nginx 自带的 /etc/logrotate.d/nginx:
- 每天轮转一次;
- 保留 14 份,轮转后 gzip;
delaycompress保证当天仍能读未压缩文件;- 轮转后
invoke-rc.d nginx rotate让 nginx 重新打开文件句柄。
GoAccess 面板
面板是纯静态 HTML,放在 /var/www/emphant-logs/,通过主站的 /logs/ 访问,带 basic auth:
https://emphant.com/logs/生成命令(在服务器上执行):
bash
goaccess /var/log/nginx/emphant.access.log \
--log-format='%h - %^ [%d:%t %^] "%r" %s %b "%R" "%u" %T' \
--date-format='%d/%b/%Y' \
--time-format='%H:%M:%S' \
--output=/var/www/emphant-logs/index.html \
--html-report-title='Emphant 访问统计' \
--ignore-crawlers解析格式对应 main 的字段顺序:
| 占位符 | 字段 |
|---|---|
%h | $remote_addr |
%d:%t | $time_local |
%r | $request |
%s | $status |
%b | $body_bytes_sent |
%R | $http_referer |
%u | $http_user_agent |
%T | $request_time |
三个站点的日志可以一起喂给同一份报告:
bash
goaccess /var/log/nginx/emphant.access.log \
/var/log/nginx/emphant-docs.access.log \
/var/log/nginx/emphant-blog.access.log \
...(同上参数)面板访问控制
bash
# 新增或修改账号
htpasswd -b /etc/nginx/.htpasswd <用户名> '<密码>'nginx 配置片段在 /etc/nginx/conf.d/emphant-logs.inc,由主站 server include。面板本身带 X-Robots-Tag: noindex,且 /logs/ 不写访问日志,避免统计自己。
常用排查命令
bash
# 最近 100 条请求
tail -100 /var/log/nginx/emphant.access.log
# 状态码分布
awk '{print $9}' /var/log/nginx/emphant.access.log | sort | uniq -c | sort -rn | head
# 404 最多的路径
awk '$9==404 {print $7}' /var/log/nginx/emphant.access.log | sort | uniq -c | sort -rn | head
# 慢请求(按 request_time 排序,最后一列是秒)
awk '{print $NF, $7}' /var/log/nginx/emphant.access.log | sort -rn | head
# 实时看错误
tail -f /var/log/nginx/error.log关于隐私
日志只用于运维与访问统计,包含 IP、UA、Referer。面板需要账号才能访问,不对公网开放。若将来要接入第三方分析服务,需同步更新隐私页。