Linux下应用程序日志管理

需求描述:应用程序日志位于/tmp/logs目录下,当日志文件大于500M时,进行文件备份,最多可备份5个文件;程序重启时将tmp目录下的日志文件压缩成.tar,设备重新起来后候并将日志文件解压恢复到tmp目录下

1.在/etc/logrotate.d目录下放置自定义好的配置文件/etc/logrotate.d/weipai,内容如下:

/tmp/logs/*.log {
    size 500k 
    rotate 5 
    create   
    missingok  
    notifempty    
	nocompress 
    postrotate
        wp.sh check 
    endscript
}

位于/tmp/logs目录下的日志文件,由logrotate负责进行日志分割转储,各配置项参数说明详见官方文档。logrotate实际是一个脚本,当 logrotate 运行时,它将读取配置文件/etc/logrotate.conf,以确定需要轮换的日志文件位置、需要轮换的频率以及需要保留的归档日志数量等。另外还需要介绍一个目录 /etc/logrotate.d,这个目录包含大多数应用程序的配置。在/etc/logrotate.conf中,/etc/logrotate.d被include。
logrotate 是基于 cron 运行的,系统按计划运行 logrotate,一般来说是每天。在大多数发行版中,每天运行 logrotate 的脚本位于 /etc/cron.daily/logrotate 中。

logrotate -v /etc/logrotate.d/weipai 

手动切割日志,-v显示转储过程,建议在执行前先使用-d(debug模式)验证一下

2.自定义日志处理脚本/usr/bin/wp.sh
1)编写脚本

#!/bin/bash

rotate=5
target=weipai
log_directory="/tmp/logs"
backup_directory="/config/${target}"


# 检查并打包压缩日志
check_and_compress_logs() {
	time=$(date +"%Y%m%d")
    check_file=${log_directory}/${target}.log.${rotate}
    mkdir -p "$backup_directory"
	if [ -e "$check_file" ]; then
		find "$backup_directory" -maxdepth 1 -type f -regex ".*/log-[0-${rotate}]+\.tar\.gz" -exec rm {} +
		tar -czvf "${backup_directory}/log-$time.tar.gz" -C "$log_directory" `find "$log_directory" -maxdepth 1 -type f -regex ".*/${target}\.log\.[0-9]+" -printf "%f\n"`
		find "$log_directory" -maxdepth 1 -type f -regex ".*/${target}\.log\.[0-9]+" -exec rm {} +
	fi
}

archive_file=${backup_directory}/log.bak.tar.gz

# 备份
backup_logs() {
    mkdir -p "$backup_directory"
	tar -czf "$archive_file" -C "$log_directory" .
}

# 恢复目录
restore_logs() {
	mkdir -p "$log_directory"
    tar -xzf "$archive_file" -C "$log_directory"
    rm ${archive_file}
}

# 主逻辑
case "$1" in
    check)
        check_and_compress_logs
        ;;
    backup) 
        backup_logs 
        ;;
    restore) 
        restore_logs 
        ;;
    *)
        echo "Usage: wp.sh [check|backup|restore]"
        ;;
esac

2)授予可执行权限 chmod 777 wp.sh
3)将脚本复制到/usr/bin 目录下

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值