1、Nginx訪問日志(access.log)介紹
NGINX軟件會把每個用戶訪問網站的日志記錄到指定的日志文件里,供網站者分析用戶的瀏覽行為,此功能由http_log_module模塊負責。
2、訪問日志參數
Nginx的訪問日志主要有兩個參數控制
| 參數 |
說明 |
| log_format |
用來記錄日志的格式(可以定義多種日志格式,取不同名字即可) |
| access_log |
用來指定日志文件的路徑及使用何種日志格式記錄日志 |
Nginx日志默認參數配置如下,
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
Nginx記錄日志默認參數配置如下,
access_log logs/access.log main;
3、訪問日志配置說明
日志的格式定義說明
語法
定義變量 log_format string ...;
配置再http標簽內,日志格式說明,注意所有日志段都已空格分開。
Nginx日志變量說明
| Nginx變量 |
說明 |
| $remote_addr |
記錄訪問網站的客戶端地址 |
| $http_x_forwarded_for |
當前有地理服務器時,設置web節點記錄客戶端節點的配置,此參數生效的前提是代理服務器也進行了相關的設置 |
| $remote_user |
遠程客戶端用戶名稱 |
| $time_local |
記錄訪問時間與時區 |
| $request |
用戶的http請求起始行信息 |
| $status |
http狀態碼,記錄請求返回的狀態碼,例如200、404、301等 |
| $body_bytes_sent |
服務器發送客戶端的響應body字節數 |
| $http_referer |
記錄此請求是從哪個鏈接訪問過來的,可以根據referer進行防盜鏈設置 |
| $http_user_agent |
記錄客戶端訪問信息,例如:瀏覽器、手機客戶端。 |
4、訪問配置驗證
以下頁面訪問后,打印出的日志
192.168.19.1 - - [17/Jul/2020:23:32:35 +0800] "POST /zabbix/jsrpc.php?output=json-rpc HTTP/1.1" 200 75 "http://192.168.19.154/zabbix/zabbix.php?action=dashboard.view&ddreset=1" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
192.168.19.1 - - [22/Aug/2020:11:30:14 +0800] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
對應說明自行分析,應該不難。
5、Nginx訪問日志分割
默認情況下,nginx會把所有的訪問日志生產到一個指定的access.log文件里面去,時間長了會越積越多,因此有必要對日志進行分割。
按天數分割,具體腳本如下,
[root@www conf]# cat cut_nginx_log.sh
#!/bin/sh
Dateformat=`date +%Y%m%d`
Basedir="/usr/local/nginx"
Nginxlogdir="$Basedir/logs"
Logname="access"
[ -d $Nginxlogdir ] && cd $Nginxlogdir || exit 1
[ -f ${Logname}.log ] || exit 1
/bin/mv ${Logname}.log ${Dateformat}_${Logname}.log
$Basedir/sbin/nginx -s reload
[root@www conf]# sh -x cut_nginx_log.sh 驗證腳本,注意生產驗證時間
[root@www logs]# ll 查看
total 8
-rw-r--r-- 1 root root 0 Aug 22 12:28 20200822_access.log
每天凌晨00點30分執行腳本
[root@www logs]# crontab -l
# cut nginx access log by sunny
30 00 * * * /bin/sh /usr/local/nginx/conf/cut_nginx_log.sh >/dev/null 2>&1
