Nginx log cutting - Hourly
Preface
Recently debug interface, do ip authorization related to the view nginx logs, but because of the daily volume of data is too large, leading to export logs from the scene too strenuous, time is too long, so do not expect a log time to cut!
principle
In fact, simple principle, the implementation of what is the time to make a shell script so that the original script access.log in accordance with the time format to rename it, and save it.
Shell Script
#!/bin/bash
# Every hour running time.
# by bobliu.
# The Nginx logs path
log_year=$(date +"%Y")
log_month=$(date +"%m")
log_day=$(date +"%d")
log_hour=$(date +"%H")
log_min=$(date +"%M")
logs_path="/usr/local/nginx/logs/"
save_path="/usr/local/nginx/logs/log"
if [ ! -d "$save_path" ]; then
mkdir -p "$save_path"
fi
mv ${logs_path}access.log ${save_path}access_${log_year}${log_month}${log_day}_${log_hour}_${log_min}.log
if [ $log_hour = 00 ]; then
mv ${logs_path}error.log ${save_path}error_$log_year$log_month$log_day.log
fi
kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
Above sh saved in a file named: logs.sh
Note: if sh file is written in the development of windows, when you upload to linux environment, the emergence of "syntax error: unexpected end of file", may be unable to compile, so it is necessary to do the following hints
- cd storage path to the script execution
vim logs.sh
If vim command to enter the following command is invalid, if ignored can edit this article
yum -y install vim-enhanced
- Enter the following two commands, converting the coding format encoded unix
:set fileformat=unix
:wq
Validation script
To verify whether the next script is executable, enter the following command under check whether the script is executable
sh logs.sh
Timing Configuration
Finally, we formulated the script as a scheduled task under linux
- Create a scheduled task
crontab -e
- Input i, enter edit, configured to perform a fifth hour
: Wq to save, verify5 * * * * sh /usr/local/nginx/logs/logs.sh