一:编译Shell脚本切割任务。
1.1在任意地方创建一个sh脚本文件。(以service.sh为例)
sudo touch service.sh
1.2编辑脚本任务。(此处以pm2的log为例,根据自身调整)
#!/bin/bash
# 第一行必须是 #!/bin/bash 开头。
#!/bin/bash
echo "日志开始切割"
echo $(date -d "yesterday" +"%Y")-$(date -d "yesterday" +"%m")-$(date -d "yesterday" +"%d") $(date -d "yesterday" +"%k"):$(date -d "yesterday" +"%M"):$(date -d "yesterday" +"%S")
# 必须是周日才执行
if [ $(date -d "yesterday" +"%w") -eq 6 ]
then
# running log
log_files_out_path=".pm2/logs/"
# file name
log_files_name="client-out.log"
# mv file name
log_files_backups_log=$(date -d "today" +"%Y")-$(date -d "today" +"%m")-$(date -d "today" +"%d")
echo ${log_files_out_path}
echo ${log_files_backups_log}
# stop service
/usr/local/lib/node_modules/pm2/bin/pm2 stop /www/serviceCode/serve/bin/service
# update client-out.log => 2020-7-29.log
sudo mv ${log_files_out_path}${log_files_name} ${log_files_out_path}${log_files_backups_log}.log
# mkdir new client-out.log
sudo mkdir ${log_files_out_path}${log_files_name}
# start pm2 service
/usr/local/lib/node_modules/pm2/bin/pm2 start /www/serviceCode/serve/bin/service
else
echo "日期错误"
fi
echo "日志切割完毕"
1.3 赋予脚本执行权限
sudo chmod +x filename
二:crontab
2.1 启动crontab
#在ubuntu下服务名称是cron,不是crond
sudo service cron start
2.2 设定定时任务
sudo crontab -e
2.3 第一次执行此项会进入到一项编辑器选择项。选择vim.basic编辑。
2.3.1 如果不小心选择错了,执行select-editor 重新选择。
select-editor
2.4 进入编辑页,设置任务。
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
#描述一下
# * * * * * 的参数分别为 分 时 日 月 周。
#这里代表今天的37分16时 执行 此路径的sh文件。也就是上面写的切割任务。
#因为着急测试是否成功,所以时间设置的短。测试成功请根据设计要求设置时间执行。
37 16 * * * sh /www/sh/service.sh
2.5 使用root权限执行的,执行成功在根目录会有一个结果文件。
内容:
注意看service服务,uptime:0S,说明刚刚被重启了。
2.6 68W行日志成功被切割。