Writing in the front

Nginx does not store file names in date format. That is, unlike Tomcat, Nginx automatically generates a log file every day. All logs are stored under the same name, and log files can become very large over time. This is very bad for analysis. Nginx doesn’t have this functionality, but we can do this by writing a small script that works with scheduled tasks. Let Nginx generate a log file every day to facilitate subsequent data analysis.

Split Nginx logs

First, we need to create a script file to split the Nginx log.

vim /usr/local/ nginx - 1.19.1 / cutnginxlog. ShCopy the code

The script content is as follows:

#! /bin/sh
# Program:
# Auto cut nginx log script.
 
# nginx log path
LOGS_PATH=/usr/local/ nginx - 1.19.1 / logs TODAY = $(the date-d 'today' +%Y-%m-%d)
 
# Move the log and rename it
mv ${LOGS_PATH}/error.log ${LOGS_PATH}/error_${TODAY}.log
mv ${LOGS_PATH}/access.log ${LOGS_PATH}/access_${TODAY}.log
 
Signal the nginx main process to reopen the log file
kill -USR1 $(cat /usr/local/ nginx - 1.19.1 / logs/nginx pid)Copy the code

The next step is to authorize the cutnginxlog.sh file.

chmod a+x cutnginxlog.sh
Copy the code

Then add a scheduled task, run the cutnginxlog.sh script periodically, and run the following command as user root:

echo '59 23 * * * root /usr/local/nginx-1.19.1/cutnginxlog.sh >> /usr/local/nginx-1.19.1/cutnginxlog.log 2>&1' >> /etc/crontab
Copy the code

This means executing the script every day at 23:59. Automatically write the execution logs (error and correct logs) of automatic tasks to cutnginxlog.log, “command >> 2>&1” means to append the correct and incorrect output to the same file.

Ok, that’s enough for today! Don’t forget to click a like, to see and forward, let more people see, learn together, progress together!!

Write in the last

If you think glacier wrote good, please search and pay attention to “glacier Technology” wechat public number, learn with glacier high concurrency, distributed, micro services, big data, Internet and cloud native technology, “glacier technology” wechat public number updated a large number of technical topics, each technical article is full of dry goods! Many readers have successfully moved to Dachang by reading articles on the “Glacier Technology” wechat official account; There are also many readers to achieve a technological leap, become the company’s technical backbone! If you also want to like them to improve their ability to achieve a leap in technical ability, into the big factory, promotion and salary, then pay attention to the “Glacier Technology” wechat public account, update the super core technology every day dry goods, so that you no longer confused about how to improve technical ability!