In linux, Shell scripts split Nginx logs and regularly clean up examples

Source: Internet
Author: User

I. Create a script file

Vim cut_nginx_log.sh
#! /Bin/bash
# Nginx access log segmentation shell script
# Www.webyang.net
# Log Directory
Log_dir = "/usr/local/nginx/logs /"
Cd $ log_dir
Time = 'date + % Y % m % d -- date = "-1 day "'
# Nginx Startup directory
Nginx_dir = "/etc/init. d/nginx"
# Log Retention days
Save_days = 15
# Location where the log file name is located '/', key (number of '/' + 1)
Num = 6;
 
# Here to be optimized (get the file name without a suffix)
Website = 'ls $ log_dir *. log | xargs-n 1 | cut-f 1-d "." | cut-f $ num-d "/"'
# All log files in the log directory are folders, and corresponding time files are created cyclically.
For I in $ website
Do
# Determine whether a directory exists
If [! -D $ log_dir $ I]; then
Mkdir "$ I"
Fi
Mv $ log_dir $ I. log $ log_dir $ I/$ I-$ time. log
Done
 
# Delete data before the specified number of days
Find $ log_dir/-mtime + $ save_days-exec rm-rf {}\;
 
# Enable nginx smoothly
$ Nginx_dir reload

2. Set crontab and cut regularly every day

If not, run yum-y install crontabs.
Enter the crontab-e command,
Enter the following content:
00 00 ***/bin/bash/usr/local/nginx/cut_nginx_log.sh

1. 00 means 00: 00, that is, A.M.. You do not need to define "***" as "day, month, and year".
2. "/usr/local/nginx/cut_nginx_log.sh" is your shell path.

OK! At every day, the log is automatically cut and stored in a directory named after the website log file.

III. Presentation

Web1.log => web1/web1-20160322.log web1/web1-20160323.log
Web2.log => web2/web2-20160322.log web2/web2-20160323.log

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.