crontab+Shell 定时切割服务器日志

1 篇文章 0 订阅
1 篇文章 0 订阅

一:编译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行日志成功被切割。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值