Demand
Because Nginx log will continue to grow, so we need to cut the log, convenient management, the need to achieve the following effects:
- The log is automatically cut by date, and the minimum unit is days.
- When the total amount of logs exceeds a certain amount, the log will be cleaned automatically and the total limit cannot exceed 1000MB.
- Write to the crontab timer task.
Analysis
- The Nginx log directory has access.log and Error.log, respectively, according to the date of automatic cutting log to the daily log in the "Yyyymmdd_access/error.log" format to save, with the MV to rename each day's log files.
- Clean up the log is simple, just to determine the size of the folder, and then a certain date before the log file cleanup is ok.
- Crontab task is also relatively simple, the details can be seen here.
- The crux of the problem is that after using the MV to rename the log file yesterday, Nginx will still write to the renamed file (such as Access_20160409.log) to the log, our intention is to make Nginx regenerate a new log file (Access.log) and write.
As we all know,linux system everything is a file, so each process has its file descriptor, The Nginx process writes its own file descriptor to the Nginx.pid, and we need to tell Nginx to reopen a new log file (the configuration details of the log file can be seen here, simply by letting the log record what. So we need this directive:
kill -USR1 `cat ${pid_path}`
This instruction means: first cat to Nginx PID, is an integer, and then send the signal USR1 to the process, the nginx process received this signal, according to the configuration to reopen a new log file, and write the log.
Realize
Script cut_nginx_log.sh:
#!/bin/bashlog_path=/path/to/nginx/pid_path=/path/to/nginx.pid#清理掉指定日期前的日志DAYS=30#生成昨天的日志文件${log_path}${log_path}-d"yesterday" +"%Y%m%d"${log_path}${log_path}-d"yesterday" +"%Y%m%d"${pid_path}`#文件夹大小-s${log_path}if-gt1000];then ${logs_path}"access_*" -type f -mtime +$DAYS -exec rm {} \; ${logs_path}"error_*" -type f -mtime +$DAYS -exec rm {} \;fi
Add to Crontab:
(self-executing at 0 o ' Day)
crontab -e00 * * * /path/to/script
At this point to solve the automatic cutting and clean the log function, there is a question welcome.
'). addclass (' pre-numbering '). Hide (); $ (this). addclass (' has-numbering '). Parent (). append ($numbering); for (i = 1; i <= lines; i++) {$numbering. Append ($ ('
'). Text (i)); }; $numbering. FadeIn (1700); }); });
The above describes the Linux server automatically cut and clean the log, including the Linux content, I hope to be interested in PHP tutorial friends helpful.