Nginx log 日志文件较大,按日期生成 实现日志的切割

Nginx日志不处理的话,会一直追加,文件会变得很大,所以理想做法是按天对 Nginx日志进行分割
image
image
image

方法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 ;
# access_log off; # 实在不需要的话,可以将其关闭(如心跳请求,会记录日志)

重新加载配置文件

# 验证文件配置是否正确
nginx -t
# 重新加载配置文件
nginx -s reload

# 观察,如果不生效,就把进程杀掉再打开

如下图所示
img

方法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

img

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"
posted @ 2023-02-06 12:41  VipSoft  阅读(4101)  评论(0编辑  收藏  举报