Nginx日志不处理的话,会一直追加,文件会变得很大
方法1:给日志文件名加上日期【推荐】
log_format access-upstream '$time_iso8601|$request|$remote_addr|$upstream_response_time|$http_user_agent|$http_x_forwarded_for'; map $time_iso8601 $logdate { '~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd; default 'date-not-found'; }
access_log logs/access-$logdate.log ;
# 验证文件配置是否正确 nginx -t # 重新加载配置文件 nginx -s reload # 观察,如果不生效,就把进程杀掉再打开
如下图所示
方法2:文件切割
会 kill 进程,比较复杂,不推荐
Linux
nginx_log.sh
#!/bin/bash date=$(date +%F -d -1day) cd /usr/local/nginx/logs if [ ! -d bak ] ; then mkdir -p bak fi mv access.log bak/access_$date.log mv error.log bak/error_$date.log # /usr/bin/nginx -s reload kill -s SIGUSR1 $(cat /usr/local/nginx/logs/nginx.pid) tar -jcvf bak/$date.tar.gz bak/access_$date.log bak/error_$date.log find /usr/local/nginx/logs/bak -mtime +30 -name "*.gz" -exec rm -rf {} \; find /usr/local/nginx/logs/bak -mtime +1 -name "*.log" -exec rm -rf {} \;
添加到定时任务
crontab -e #打开定时任务 i #进入编辑模式 0 1 * * * /bin/sh /opt/shell/nginx_log.sh #添加任务 :wq! #保存退出
如果报错:
tar (child): bzip2: Cannot exec: No such file or directory
tar (child): Error is not recoverable: exiting now
yum -y install bzip2
Windows
taskkill /F /IM nginx.exe > nul rem date格式:Wed 11/02/2016 set today=%date:~0,4%-%date:~5,2%-%date:~8,2% set dir=D:\nginx-1.20.1\logs\backup md "%dir%" rem access log move "D:\nginx-1.20.1\logs\access.log" "%dir%\access-%today%.log" start "D:\nginx-1.20.1\nginx.exe"
标签:log,nginx,access,Nginx,date,日志,bak,logs From: https://www.cnblogs.com/vipsoft/p/16669189.html