一、nginx日志管理
nginx有非常灵活的日志记录模式,每个级别的配置可以有各自独立的访问日志。日志格式通过log_format命令定义格式;
1. log_format 定义日志格式语法
# 配置语法:包括:error.log access.log
Syntax: log_format name [escape=default|json] string ...;
Default: log_format combined "...";
Context: http
2. 默认nginx定义语法格式如下
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
3. Nginx日志格式允许包含的内置变量
$remote_addr
$remote_user
$time_local
$request
$time_iso8601
$status
$body_bytes_sent
$bytes_sent
$msec
$http_referer
$http_user_agent
$http_x_forwarded_for
$request_length
$request_time
4. access_log 日志配置语法
Syntax: access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off;
Default:
access_log logs/access.log combined;
Context: http, server, location, if in location, limit_except
5. Nginx Access 日志配置实践
server {
listen 80;
server_name code.xiaoma.com;
access_log /var/log/nginx/code.xiaoma.com.log main;
location / {
root /code;
}
location /favicon.ico {
access_log off;
return 200;
}
}
6. 日志切割logrotate
[root@study nginx]
/var/log/nginx/*.log {
daily
missingok
rotate 52
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
}
7. 日志切割后的效果
[root@study ~]
total 28
-rw-r-----. 1 nginx adm 0 Aug 5 21:48 access.log
-rw-r--r--. 1 root root 578 Jul 29 00:06 access.log-20210729.gz
-rw-r-----. 1 nginx adm 1942 Jul 29 21:52 access.log-20210805
-rw-r-----. 1 nginx adm 0 Aug 5 21:48 error.log
-rw-r--r--. 1 root root 161 Feb 19 22:49 error.log-20210221.gz
-rw-rw-r--. 1 nginx root 1514 Jul 29 20:10 error.log-20210729.gz
-rw-r-----. 1 nginx adm 8347 Aug 5 21:48 error.log-20210805
|