Example 1,Cut nginx logs by date and automatically delete logs generated seven days ago (logs have been synchronized to dedicated log storage servers, so you can safely delete historical logs .)
#! /Bin/bash
# Initialization
LOGS_PATH =/data/nginx/logs/www.domain.com
YESTERDAY = $ (date-d "yesterday" + % Y-% m-% d)
# Daily log cutting
Mv $ {LOGS_PATH}/access. log $ {LOGS_PATH}/access _ $ {YESTERDAY}. log
# Send the USR1 signal to the Nginx main process and re-open the log file. Otherwise, it will continue to write content to the mv file, leading to a failure in cutting.
Kill-USR1 'PS axu | grep "nginx: master process" | grep-v grep | awk '{print $2 }''
# Delete logs 7 days ago
Cd $ {LOGS_PATH}
Find.-ctime + 7-name "* 20 [1-9] [3-9] *" | xargs rm-f
Exit 0
Add the script to the scheduled task and run it once a day:
1 0 ***/usr/local/script/cut_del_logs.sh
This method can be found on the internet. Therefore, this article is only used as a personal work record, not a tutorial. Just take a look at it and don't worry too much.
Example 2. Store and delete logs by day for more than 7 days
Script content:
#! /Bin/bash
# A nginx access log segmentation shell script
Cd/data/wslogs
Log_dir = "/data/wslogs"
Time = 'date + % Y % m % d'
Nginx_dir = "/usr/local/webserver/nginx"
# Log segmentation, classified by day
Website = 'ls $ log_dir/access * | xargs-n 1 | cut-f 2-d "."'
For I in $ website
Do
Mkdir-p $ log_dir/backup/$ time/$ I
Mv $ log_dir/access. $ I. log $ log_dir/backup/$ time/$ I/$ time. log
Done
$ Nginx_dir/sbin/nginx-s reload
# Delete all logs that have exceeded 7 days.
If ["'date + % A'" = "Sun"]; then
All_list = 'ls $ log_dir/backup | xargs-n 1'
For del in $ all_list
Do
Let results = $ time-$ del
If [$ results-gt 7]; then
Rm-fr $ log_dir/backup/$ del
Fi
Done
Fi
Note that the Nginx access log naming format must be access. domain name. log, for example, access. www_1987_com.log, the original point in the domain name. must be replaced with other characters, such as underline _
You can modify some location parameters in the code as needed, modify the/etc/crontab file, and add 00 00 *** root/data/logcron. sh, which is executed at every day.