日志解析
1)基本配置
# cat /etc/nginx/nginx.conf -n
40 access_log /var/log/nginx/access.log;
41 error_log /var/log/nginx/error.log;
注意:
nginx日志属性设置的完整格式是:
属性名称 access_log
存储位置 /var/log/nginx/access.log
日志格式 位置为空表示使用默认的combined 日志格式。它是通过log_format设置的
2)默认日志格式
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
案例
1)设置日志格式
# vim /etc/nginx/nginx.conf
# Logging Settings
## 设定日志格式的方法: log_format 格式名称 "日志表现样式"
log_format proxy_format '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent "$http_referer"'
'"$http_user_agent" "$http_x_real_ip" "$http_x_forwarded_for"';
2)使用日志格式
access_log 日志路径 格式名称;
3)负载均衡配置文件
# vim /etc/nginx/conf.d/upstream.conf
upstream backends {
server 172.16.179.131:10086;
}
server {
listen 8080;
server_name localhost;
location / {
proxy_pass http://backends;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
4)后端代理配置文件
# vim /etc/nginx/conf.d/backend.conf
server {
listen 172.16.179.131:10086;
location / {
proxy_pass http://172.16.179.130:10087/;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server {
listen 172.16.179.131:10087;
root /var/www/html/app1/;
access_log /var/log/nginx/app1/access.log proxy_format;
real_ip_header X-Forwarded-For;
set_real_ip_from 172.16.0.0/16;
real_ip_recursive on;
location / {
root /var/www/html/nihao/;
try_files $uri $uri/ =404;
}
}
5)准备后端服务文件
mkdir -p /var/www/html/app1/
echo '<h1>backend_app1</h1>' > /var/www/html/app1/index.html
mkdir /var/log/nginx/app1 -p
6)检查nginx配置后重载服务
/usr/sbin/nginx -t
systemctl reload nginx
netstat -tnulp | grep nginx
7)查看效果
在多台主机上执行如下命令
curl http://172.16.179.131
8)查看app1日志
172.16.179.1 - - [04/Jun/2019:20:24:32 +0800] "GET / HTTP/1.0" 304 0 "-""curl/7.47.0" "172.16.179.1" "172.16.179.1, 172.16.179.131"
172.16.179.130 - - [04/Jun/2019:20:26:13 +0800] "GET / HTTP/1.0" 200 23 "-""curl/7.47.0" "172.16.179.130" "172.16.179.130, 172.16.179.131"