文章目录
1. 安装 Nginx
1.1 添加 Nginx 官方仓库
CentOS 默认仓库中的 Nginx 版本较旧,建议添加官方仓库:
# 安装 EPEL 仓库(基础依赖)
sudo yum install epel-release
# 添加 Nginx 官方仓库
sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
# 更新仓库缓存
sudo yum clean all
sudo yum makecache
1.2 安装 Nginx
sudo yum install nginx
2. 启动 Nginx 并设置开机自启
# 启动服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 确认状态
sudo systemctl status nginx
3. 配置 JSON 日志格式
3.1 编辑 Nginx 配置文件
sudo vim /etc/nginx/nginx.conf
3.2 在 http
块中添加 JSON 日志格式
找到 http { ... }
块,新增以下内容:
http {
# 默认日志格式(可选保留)
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# 新增 JSON 日志格式(使用 escape=json 转义特殊字符)
log_format json_combined escape=json
'{'
'"time_local": "$time_iso8601", '
'"remote_addr": "$remote_addr", '
'"remote_user": "$remote_user", '
'"request": "$request", '
'"status": "$status", '
'"body_bytes_sent": "$body_bytes_sent", '
'"http_referer": "$http_referer", '
'"http_user_agent": "$http_user_agent", '
'"http_x_forwarded_for": "$http_x_forwarded_for", '
'"request_time": "$request_time", '
'"upstream_response_time": "$upstream_response_time"'
'}';
# 其他配置...
}
3.3 应用 JSON 格式到访问日志
在 server
或全局 http
块中修改 access_log
路径:
server {
listen 80;
server_name _;
# 使用 JSON 格式日志
access_log /var/log/nginx/access.json.log json_combined;
# 其他配置...
}
4. 验证配置文件并重启 Nginx
# 检查配置语法
sudo nginx -t
# 重启 Nginx 生效
sudo systemctl restart nginx
5. 测试 JSON 日志格式
5.1 发送测试请求
curl http://localhost
5.2 查看日志内容
sudo tail -f /var/log/nginx/access.json.log
输出应类似:
{
"time_local": "2024-05-20T12:34:56+08:00",
"remote_addr": "192.168.1.100",
"remote_user": "-",
"request": "GET / HTTP/1.1",
"status": "200",
"body_bytes_sent": "612",
"http_referer": "-",
"http_user_agent": "curl/7.76.1",
"http_x_forwarded_for": "-",
"request_time": "0.002",
"upstream_response_time": "0.001"
}
6. 高级配置(可选)
6.1 日志自动切割
使用 logrotate
管理日志文件:
sudo vim /etc/logrotate.d/nginx
添加以下内容:
/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 nginx adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
6.2 扩展日志字段
根据需要修改 json_combined
格式,添加更多变量(如 $host
、$server_name
等)。
总结
- 关键点:通过
log_format
定义 JSON 结构,使用escape=json
确保字符转义。 - 日志路径:默认日志文件为
/var/log/nginx/access.json.log
。 - 验证工具:可使用
jq
命令格式化查看 JSON 日志:sudo apt install jq # Debian/Ubuntu sudo yum install jq # CentOS sudo tail -f /var/log/nginx/access.json.log | jq .